commit 887e47a8446f1a7de0c24d20ac0c77ea840533de Author: NunoSempere Date: Thu Apr 14 21:48:30 2022 -0400 feat: Proof of concept of simple squiggle diff --git a/index.js b/index.js new file mode 100644 index 0000000..cb050bf --- /dev/null +++ b/index.js @@ -0,0 +1,157 @@ +import { create, all } from "mathjs"; +const math = create(all); + +// Helper functions +let printNode = (x) => console.log(JSON.stringify(x, null, 4)); + +let isNumber = (x) => typeof x === "number" && isFinite(x); + +let isConstantNode = (arg) => { + return !!arg.value && isNumber(arg.value); +}; +let isArgLognormal = (arg) => { + let isFn = typeof arg.fn != "undefined"; + let andNameIsLognormal = isFn && arg.fn.name == "lognormal"; + let andHasArgs = andNameIsLognormal && !!arg.args; + let andHasTwoArgs = andHasArgs && arg.args.length == 2; + let andTwoArgsAreConstant = arg.args + .map( + (innerArg) => isConstantNode(innerArg) + // innerArg + ) + .reduce((a, b) => a && b, true); + return andTwoArgsAreConstant; +}; + +let getFactors = (node) => { + return node.args.map((arg) => arg.value); +}; + +let createLogarithmNode = (mu, sigma) => { + let node1 = new math.ConstantNode(mu); + let node2 = new math.ConstantNode(sigma); + let node3 = new math.FunctionNode("lognormal", [node1, node2]); + return node3; +}; + +// Main function +let transformerInner = (string) => { + let nodes = math.parse(string); + let transformed = nodes.transform(function (node, path, parent) { + if (node.type == "OperatorNode" && node.op == "*") { + let hasArgs = node.args && node.args.length == 2; + if (hasArgs) { + let areArgsLognormal = node.args + .map((arg) => isArgLognormal(arg)) + .reduce((a, b) => a && b, true); + if (areArgsLognormal) { + let factors = node.args.map((arg) => getFactors(arg)); + let mean1 = factors[0][0]; + let std1 = factors[0][1]; + let mean2 = factors[1][0]; + let std2 = factors[1][1]; + + let newMean = mean1 + mean2; + let newStd = Math.sqrt(std1 ** 2 + std2 ** 2); + return createLogarithmNode(newMean, newStd); + return new math.SymbolNode("xx"); + } else { + return node; + } + } else { + return node; + } + } else if (node.type == "OperatorNode" && node.op == "/") { + let hasArgs = node.args && node.args.length == 2; + if (hasArgs) { + let areArgsLognormal = node.args + .map((arg) => isArgLognormal(arg)) + .reduce((a, b) => a && b, true); + if (areArgsLognormal) { + let factors = node.args.map((arg) => getFactors(arg)); + let mean1 = factors[0][0]; + let std1 = factors[0][1]; + let mean2 = factors[1][0]; + let std2 = factors[1][1]; + + let newMean = mean1 + mean2; + let newStd = Math.sqrt(std1 ** 2 + std2 ** 2); + return createLogarithmNode(newMean, newStd); + return new math.SymbolNode("xx"); + } + } + } + return node; + }); + + return transformed.toString(); +}; + +let from90PercentCI = (low, high) => { + let normal95confidencePoint = 1.6448536269514722; + let logLow = Math.log(low); + let logHigh = Math.log(high); + let mu = (logLow + logHigh) / 2; + let sigma = (logHigh - logLow) / (2.0 * normal95confidencePoint); + return [mu, sigma]; +}; + +let simplePreprocessor = (string) => { + // left for documentation purposes only + function replacer(match, p1, p2) { + console.log(match); + // p1 is nondigits, p2 digits, and p3 non-alphanumericsa + console.log([p1, p2]); + let result = from90PercentCI(p1, p2); + return `lognormal(${result[0]}, ${result[1]})`; + } + let newString = string.replace(/(\d+) to (\d+)/g, replacer); + console.log(newString); + return newString; // abc - 12345 - #$*% +}; + +// simplePreprocessor("1 to 10 + 1 to 20"); + +let preprocessor = (string) => { + // work in progress, currently not working + let regex = /([\d]+\.?[\d]*|\.[\d]+) to ([\d]+\.?[\d]*|\.[\d]+)/g; + function replacer(match, p1, p2) { + let result = from90PercentCI(p1, p2); + return `lognormal(${result[0]}, ${result[1]})`; + } + let newString = string.replace(regex, replacer); + if (newString != string) console.log(`\tPreprocessing: ${newString}`); + return newString; // abc - 12345 - #$*% +}; +// preprocessor("1.2 to 10.5 * 1.1 to 20 * 1 to 2.5 * 1 to 5"); + +let transformer = (string) => { + string = preprocessor(string); + let stringNew = transformerInner(string); + while (stringNew != string) { + console.log(`\tNew transformation: ${stringNew}`); + string = stringNew; + stringNew = transformerInner(string); + } + return stringNew; +}; + +let testTransformer = (string) => { + console.log(`New test: ${string}`); + console.group(); + let result = transformer(string); + console.groupEnd(); + console.log(`Result: ${result}`); + console.log(""); +}; + +// Defs +let tests = [ + `lognormal(1,10) * lognormal(1,10) + lognormal(1,10)`, + `lognormal(1,10) * lognormal(1,10) * lognormal(1,10)`, + `1 to 10 * lognormal(1, 10)`, + `lognormal(1, 10) * 1 to 20`, + `1 to 20 * 100 to 1000`, +]; +console.clear(); +tests.forEach((test) => testTransformer(test)); diff --git a/node_modules/.bin/mathjs b/node_modules/.bin/mathjs new file mode 120000 index 0000000..d147838 --- /dev/null +++ b/node_modules/.bin/mathjs @@ -0,0 +1 @@ +../mathjs/bin/cli.js \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..df30ce1 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,103 @@ +{ + "name": "squiggle-simplex", + "version": "1.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@babel/runtime": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.17.9.tgz", + "integrity": "sha512-lSiBBvodq29uShpWGNbgFdKYNiFDo5/HIYsaCEY9ff4sb10x9jizo2+pRrSyF4jKZCXqgzuqBOQKbUm90gQwJg==", + "dependencies": { + "regenerator-runtime": "^0.13.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/complex.js": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/complex.js/-/complex.js-2.1.1.tgz", + "integrity": "sha512-8njCHOTtFFLtegk6zQo0kkVX1rngygb/KQI6z1qZxlFI3scluC+LVTCFbrkWjBv4vvLlbQ9t88IPMC6k95VTTg==", + "engines": { + "node": "*" + }, + "funding": { + "type": "patreon", + "url": "https://www.patreon.com/infusion" + } + }, + "node_modules/decimal.js": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.3.1.tgz", + "integrity": "sha512-V0pfhfr8suzyPGOx3nmq4aHqabehUZn6Ch9kyFpV79TGDTWFmHqUqXdabR7QHqxzrYolF4+tVmJhUG4OURg5dQ==" + }, + "node_modules/escape-latex": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/escape-latex/-/escape-latex-1.2.0.tgz", + "integrity": "sha512-nV5aVWW1K0wEiUIEdZ4erkGGH8mDxGyxSeqPzRNtWP7ataw+/olFObw7hujFWlVjNsaDFw5VZ5NzVSIqRgfTiw==" + }, + "node_modules/fraction.js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.2.0.tgz", + "integrity": "sha512-MhLuK+2gUcnZe8ZHlaaINnQLl0xRIGRfcGk2yl8xoQAfHrSsL3rYu6FCmBdkdbhc9EPlwyGHewaRsvwRMJtAlA==", + "engines": { + "node": "*" + }, + "funding": { + "type": "patreon", + "url": "https://www.patreon.com/infusion" + } + }, + "node_modules/javascript-natural-sort": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/javascript-natural-sort/-/javascript-natural-sort-0.7.1.tgz", + "integrity": "sha1-+eIwPUUH9tdDVac2ZNFED7Wg71k=" + }, + "node_modules/mathjs": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/mathjs/-/mathjs-10.4.3.tgz", + "integrity": "sha512-C50lWorCOplBec9Ik5fzhHuOx4G4+mtdz3r1G2I1/r8yj+CpYFXLXNqTdg59oKmIF1tKcIzpxlC4s2dGL7f3pg==", + "dependencies": { + "@babel/runtime": "^7.17.8", + "complex.js": "^2.1.0", + "decimal.js": "^10.3.1", + "escape-latex": "^1.2.0", + "fraction.js": "^4.2.0", + "javascript-natural-sort": "^0.7.1", + "seedrandom": "^3.0.5", + "tiny-emitter": "^2.1.0", + "typed-function": "^2.1.0" + }, + "bin": { + "mathjs": "bin/cli.js" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.13.9", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", + "integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==" + }, + "node_modules/seedrandom": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/seedrandom/-/seedrandom-3.0.5.tgz", + "integrity": "sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==" + }, + "node_modules/tiny-emitter": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tiny-emitter/-/tiny-emitter-2.1.0.tgz", + "integrity": "sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q==" + }, + "node_modules/typed-function": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/typed-function/-/typed-function-2.1.0.tgz", + "integrity": "sha512-bctQIOqx2iVbWGDGPWwIm18QScpu2XRmkC19D8rQGFsjKSgteq/o1hTZvIG/wuDq8fanpBDrLkLq+aEN/6y5XQ==", + "engines": { + "node": ">= 10" + } + } + } +} diff --git a/node_modules/@babel/runtime/LICENSE b/node_modules/@babel/runtime/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/runtime/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +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. diff --git a/node_modules/@babel/runtime/README.md b/node_modules/@babel/runtime/README.md new file mode 100644 index 0000000..be27e83 --- /dev/null +++ b/node_modules/@babel/runtime/README.md @@ -0,0 +1,19 @@ +# @babel/runtime + +> babel's modular runtime helpers + +See our website [@babel/runtime](https://babeljs.io/docs/en/babel-runtime) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/runtime +``` + +or using yarn: + +```sh +yarn add @babel/runtime +``` diff --git a/node_modules/@babel/runtime/helpers/AsyncGenerator.js b/node_modules/@babel/runtime/helpers/AsyncGenerator.js new file mode 100644 index 0000000..e6a15a7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/AsyncGenerator.js @@ -0,0 +1,98 @@ +var AwaitValue = require("./AwaitValue.js"); + +function AsyncGenerator(gen) { + var front, back; + + function send(key, arg) { + return new Promise(function (resolve, reject) { + var request = { + key: key, + arg: arg, + resolve: resolve, + reject: reject, + next: null + }; + + if (back) { + back = back.next = request; + } else { + front = back = request; + resume(key, arg); + } + }); + } + + function resume(key, arg) { + try { + var result = gen[key](arg); + var value = result.value; + var wrappedAwait = value instanceof AwaitValue; + Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { + if (wrappedAwait) { + resume(key === "return" ? "return" : "next", arg); + return; + } + + settle(result.done ? "return" : "normal", arg); + }, function (err) { + resume("throw", err); + }); + } catch (err) { + settle("throw", err); + } + } + + function settle(type, value) { + switch (type) { + case "return": + front.resolve({ + value: value, + done: true + }); + break; + + case "throw": + front.reject(value); + break; + + default: + front.resolve({ + value: value, + done: false + }); + break; + } + + front = front.next; + + if (front) { + resume(front.key, front.arg); + } else { + back = null; + } + } + + this._invoke = send; + + if (typeof gen["return"] !== "function") { + this["return"] = undefined; + } +} + +AsyncGenerator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function () { + return this; +}; + +AsyncGenerator.prototype.next = function (arg) { + return this._invoke("next", arg); +}; + +AsyncGenerator.prototype["throw"] = function (arg) { + return this._invoke("throw", arg); +}; + +AsyncGenerator.prototype["return"] = function (arg) { + return this._invoke("return", arg); +}; + +module.exports = AsyncGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/AwaitValue.js b/node_modules/@babel/runtime/helpers/AwaitValue.js new file mode 100644 index 0000000..5ddee2e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/AwaitValue.js @@ -0,0 +1,5 @@ +function _AwaitValue(value) { + this.wrapped = value; +} + +module.exports = _AwaitValue, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js b/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js new file mode 100644 index 0000000..9080fd6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js @@ -0,0 +1,30 @@ +function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { + var desc = {}; + Object.keys(descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0) { + Object.defineProperty(target, property, desc); + desc = null; + } + + return desc; +} + +module.exports = _applyDecoratedDescriptor, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/applyDecs.js b/node_modules/@babel/runtime/helpers/applyDecs.js new file mode 100644 index 0000000..b27baad --- /dev/null +++ b/node_modules/@babel/runtime/helpers/applyDecs.js @@ -0,0 +1,284 @@ +var _typeof = require("./typeof.js")["default"]; + +function createMetadataMethodsForProperty(metadataMap, kind, property, decoratorFinishedRef) { + return { + getMetadata: function getMetadata(key) { + assertNotFinished(decoratorFinishedRef, "getMetadata"), assertMetadataKey(key); + var metadataForKey = metadataMap[key]; + if (void 0 !== metadataForKey) if (1 === kind) { + var pub = metadataForKey["public"]; + if (void 0 !== pub) return pub[property]; + } else if (2 === kind) { + var priv = metadataForKey["private"]; + if (void 0 !== priv) return priv.get(property); + } else if (Object.hasOwnProperty.call(metadataForKey, "constructor")) return metadataForKey.constructor; + }, + setMetadata: function setMetadata(key, value) { + assertNotFinished(decoratorFinishedRef, "setMetadata"), assertMetadataKey(key); + var metadataForKey = metadataMap[key]; + + if (void 0 === metadataForKey && (metadataForKey = metadataMap[key] = {}), 1 === kind) { + var pub = metadataForKey["public"]; + void 0 === pub && (pub = metadataForKey["public"] = {}), pub[property] = value; + } else if (2 === kind) { + var priv = metadataForKey.priv; + void 0 === priv && (priv = metadataForKey["private"] = new Map()), priv.set(property, value); + } else metadataForKey.constructor = value; + } + }; +} + +function convertMetadataMapToFinal(obj, metadataMap) { + var parentMetadataMap = obj[Symbol.metadata || Symbol["for"]("Symbol.metadata")], + metadataKeys = Object.getOwnPropertySymbols(metadataMap); + + if (0 !== metadataKeys.length) { + for (var i = 0; i < metadataKeys.length; i++) { + var key = metadataKeys[i], + metaForKey = metadataMap[key], + parentMetaForKey = parentMetadataMap ? parentMetadataMap[key] : null, + pub = metaForKey["public"], + parentPub = parentMetaForKey ? parentMetaForKey["public"] : null; + pub && parentPub && Object.setPrototypeOf(pub, parentPub); + var priv = metaForKey["private"]; + + if (priv) { + var privArr = Array.from(priv.values()), + parentPriv = parentMetaForKey ? parentMetaForKey["private"] : null; + parentPriv && (privArr = privArr.concat(parentPriv)), metaForKey["private"] = privArr; + } + + parentMetaForKey && Object.setPrototypeOf(metaForKey, parentMetaForKey); + } + + parentMetadataMap && Object.setPrototypeOf(metadataMap, parentMetadataMap), obj[Symbol.metadata || Symbol["for"]("Symbol.metadata")] = metadataMap; + } +} + +function createAddInitializerMethod(initializers, decoratorFinishedRef) { + return function (initializer) { + assertNotFinished(decoratorFinishedRef, "addInitializer"), assertCallable(initializer, "An initializer"), initializers.push(initializer); + }; +} + +function memberDec(dec, name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value) { + var kindStr; + + switch (kind) { + case 1: + kindStr = "accessor"; + break; + + case 2: + kindStr = "method"; + break; + + case 3: + kindStr = "getter"; + break; + + case 4: + kindStr = "setter"; + break; + + default: + kindStr = "field"; + } + + var metadataKind, + metadataName, + ctx = { + kind: kindStr, + name: isPrivate ? "#" + name : name, + isStatic: isStatic, + isPrivate: isPrivate + }, + decoratorFinishedRef = { + v: !1 + }; + + if (0 !== kind && (ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef)), isPrivate) { + metadataKind = 2, metadataName = Symbol(name); + var access = {}; + 0 === kind ? (access.get = desc.get, access.set = desc.set) : 2 === kind ? access.get = function () { + return desc.value; + } : (1 !== kind && 3 !== kind || (access.get = function () { + return desc.get.call(this); + }), 1 !== kind && 4 !== kind || (access.set = function (v) { + desc.set.call(this, v); + })), ctx.access = access; + } else metadataKind = 1, metadataName = name; + + try { + return dec(value, Object.assign(ctx, createMetadataMethodsForProperty(metadataMap, metadataKind, metadataName, decoratorFinishedRef))); + } finally { + decoratorFinishedRef.v = !0; + } +} + +function assertNotFinished(decoratorFinishedRef, fnName) { + if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished"); +} + +function assertMetadataKey(key) { + if ("symbol" != _typeof(key)) throw new TypeError("Metadata keys must be symbols, received: " + key); +} + +function assertCallable(fn, hint) { + if ("function" != typeof fn) throw new TypeError(hint + " must be a function"); +} + +function assertValidReturnValue(kind, value) { + var type = _typeof(value); + + if (1 === kind) { + if ("object" !== type || null === value) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); + void 0 !== value.get && assertCallable(value.get, "accessor.get"), void 0 !== value.set && assertCallable(value.set, "accessor.set"), void 0 !== value.init && assertCallable(value.init, "accessor.init"), void 0 !== value.initializer && assertCallable(value.initializer, "accessor.initializer"); + } else if ("function" !== type) { + var hint; + throw hint = 0 === kind ? "field" : 10 === kind ? "class" : "method", new TypeError(hint + " decorators must return a function or void 0"); + } +} + +function getInit(desc) { + var initializer; + return null == (initializer = desc.init) && (initializer = desc.initializer) && "undefined" != typeof console && console.warn(".initializer has been renamed to .init as of March 2022"), initializer; +} + +function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, metadataMap, initializers) { + var desc, + initializer, + value, + newValue, + get, + set, + decs = decInfo[0]; + if (isPrivate ? desc = 0 === kind || 1 === kind ? { + get: decInfo[3], + set: decInfo[4] + } : 3 === kind ? { + get: decInfo[3] + } : 4 === kind ? { + set: decInfo[3] + } : { + value: decInfo[3] + } : 0 !== kind && (desc = Object.getOwnPropertyDescriptor(base, name)), 1 === kind ? value = { + get: desc.get, + set: desc.set + } : 2 === kind ? value = desc.value : 3 === kind ? value = desc.get : 4 === kind && (value = desc.set), "function" == typeof decs) void 0 !== (newValue = memberDec(decs, name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value)) && (assertValidReturnValue(kind, newValue), 0 === kind ? initializer = newValue : 1 === kind ? (initializer = getInit(newValue), get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue);else for (var i = decs.length - 1; i >= 0; i--) { + var newInit; + if (void 0 !== (newValue = memberDec(decs[i], name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value))) assertValidReturnValue(kind, newValue), 0 === kind ? newInit = newValue : 1 === kind ? (newInit = getInit(newValue), get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue, void 0 !== newInit && (void 0 === initializer ? initializer = newInit : "function" == typeof initializer ? initializer = [initializer, newInit] : initializer.push(newInit)); + } + + if (0 === kind || 1 === kind) { + if (void 0 === initializer) initializer = function initializer(instance, init) { + return init; + };else if ("function" != typeof initializer) { + var ownInitializers = initializer; + + initializer = function initializer(instance, init) { + for (var value = init, i = 0; i < ownInitializers.length; i++) { + value = ownInitializers[i].call(instance, value); + } + + return value; + }; + } else { + var originalInitializer = initializer; + + initializer = function initializer(instance, init) { + return originalInitializer.call(instance, init); + }; + } + ret.push(initializer); + } + + 0 !== kind && (1 === kind ? (desc.get = value.get, desc.set = value.set) : 2 === kind ? desc.value = value : 3 === kind ? desc.get = value : 4 === kind && (desc.set = value), isPrivate ? 1 === kind ? (ret.push(function (instance, args) { + return value.get.call(instance, args); + }), ret.push(function (instance, args) { + return value.set.call(instance, args); + })) : 2 === kind ? ret.push(value) : ret.push(function (instance, args) { + return value.call(instance, args); + }) : Object.defineProperty(base, name, desc)); +} + +function applyMemberDecs(ret, Class, protoMetadataMap, staticMetadataMap, decInfos) { + for (var protoInitializers, staticInitializers, existingProtoNonFields = new Map(), existingStaticNonFields = new Map(), i = 0; i < decInfos.length; i++) { + var decInfo = decInfos[i]; + + if (Array.isArray(decInfo)) { + var base, + metadataMap, + initializers, + kind = decInfo[1], + name = decInfo[2], + isPrivate = decInfo.length > 3, + isStatic = kind >= 5; + + if (isStatic ? (base = Class, metadataMap = staticMetadataMap, 0 !== (kind -= 5) && (initializers = staticInitializers = staticInitializers || [])) : (base = Class.prototype, metadataMap = protoMetadataMap, 0 !== kind && (initializers = protoInitializers = protoInitializers || [])), 0 !== kind && !isPrivate) { + var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields, + existingKind = existingNonFields.get(name) || 0; + if (!0 === existingKind || 3 === existingKind && 4 !== kind || 4 === existingKind && 3 !== kind) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name); + !existingKind && kind > 2 ? existingNonFields.set(name, kind) : existingNonFields.set(name, !0); + } + + applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, metadataMap, initializers); + } + } + + pushInitializers(ret, protoInitializers), pushInitializers(ret, staticInitializers); +} + +function pushInitializers(ret, initializers) { + initializers && ret.push(function (instance) { + for (var i = 0; i < initializers.length; i++) { + initializers[i].call(instance); + } + + return instance; + }); +} + +function applyClassDecs(ret, targetClass, metadataMap, classDecs) { + if (classDecs.length > 0) { + for (var initializers = [], newClass = targetClass, name = targetClass.name, i = classDecs.length - 1; i >= 0; i--) { + var decoratorFinishedRef = { + v: !1 + }; + + try { + var ctx = Object.assign({ + kind: "class", + name: name, + addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef) + }, createMetadataMethodsForProperty(metadataMap, 0, name, decoratorFinishedRef)), + nextNewClass = classDecs[i](newClass, ctx); + } finally { + decoratorFinishedRef.v = !0; + } + + void 0 !== nextNewClass && (assertValidReturnValue(10, nextNewClass), newClass = nextNewClass); + } + + ret.push(newClass, function () { + for (var i = 0; i < initializers.length; i++) { + initializers[i].call(newClass); + } + }); + } +} + +function applyDecs(targetClass, memberDecs, classDecs) { + var ret = [], + staticMetadataMap = {}, + protoMetadataMap = {}; + return applyMemberDecs(ret, targetClass, protoMetadataMap, staticMetadataMap, memberDecs), convertMetadataMapToFinal(targetClass.prototype, protoMetadataMap), applyClassDecs(ret, targetClass, staticMetadataMap, classDecs), convertMetadataMapToFinal(targetClass, staticMetadataMap), ret; +} + +module.exports = applyDecs, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/arrayLikeToArray.js b/node_modules/@babel/runtime/helpers/arrayLikeToArray.js new file mode 100644 index 0000000..465974f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/arrayLikeToArray.js @@ -0,0 +1,11 @@ +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) { + arr2[i] = arr[i]; + } + + return arr2; +} + +module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/arrayWithHoles.js b/node_modules/@babel/runtime/helpers/arrayWithHoles.js new file mode 100644 index 0000000..b5680a0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/arrayWithHoles.js @@ -0,0 +1,5 @@ +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} + +module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js b/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js new file mode 100644 index 0000000..30bf377 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js @@ -0,0 +1,7 @@ +var arrayLikeToArray = require("./arrayLikeToArray.js"); + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); +} + +module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/assertThisInitialized.js b/node_modules/@babel/runtime/helpers/assertThisInitialized.js new file mode 100644 index 0000000..70ea855 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/assertThisInitialized.js @@ -0,0 +1,9 @@ +function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +} + +module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js b/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js new file mode 100644 index 0000000..cf7d480 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js @@ -0,0 +1,56 @@ +function _asyncGeneratorDelegate(inner, awaitWrap) { + var iter = {}, + waiting = false; + + function pump(key, value) { + waiting = true; + value = new Promise(function (resolve) { + resolve(inner[key](value)); + }); + return { + done: false, + value: awaitWrap(value) + }; + } + + ; + + iter[typeof Symbol !== "undefined" && Symbol.iterator || "@@iterator"] = function () { + return this; + }; + + iter.next = function (value) { + if (waiting) { + waiting = false; + return value; + } + + return pump("next", value); + }; + + if (typeof inner["throw"] === "function") { + iter["throw"] = function (value) { + if (waiting) { + waiting = false; + throw value; + } + + return pump("throw", value); + }; + } + + if (typeof inner["return"] === "function") { + iter["return"] = function (value) { + if (waiting) { + waiting = false; + return value; + } + + return pump("return", value); + }; + } + + return iter; +} + +module.exports = _asyncGeneratorDelegate, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/asyncIterator.js b/node_modules/@babel/runtime/helpers/asyncIterator.js new file mode 100644 index 0000000..d8e11f0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/asyncIterator.js @@ -0,0 +1,50 @@ +function _asyncIterator(iterable) { + var method, + async, + sync, + retry = 2; + + for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { + if (async && null != (method = iterable[async])) return method.call(iterable); + if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable)); + async = "@@asyncIterator", sync = "@@iterator"; + } + + throw new TypeError("Object is not async iterable"); +} + +function AsyncFromSyncIterator(s) { + function AsyncFromSyncIteratorContinuation(r) { + if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); + var done = r.done; + return Promise.resolve(r.value).then(function (value) { + return { + value: value, + done: done + }; + }); + } + + return AsyncFromSyncIterator = function AsyncFromSyncIterator(s) { + this.s = s, this.n = s.next; + }, AsyncFromSyncIterator.prototype = { + s: null, + n: null, + next: function next() { + return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); + }, + "return": function _return(value) { + var ret = this.s["return"]; + return void 0 === ret ? Promise.resolve({ + value: value, + done: !0 + }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); + }, + "throw": function _throw(value) { + var thr = this.s["return"]; + return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); + } + }, new AsyncFromSyncIterator(s); +} + +module.exports = _asyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/asyncToGenerator.js b/node_modules/@babel/runtime/helpers/asyncToGenerator.js new file mode 100644 index 0000000..becd163 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/asyncToGenerator.js @@ -0,0 +1,37 @@ +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); + }); + }; +} + +module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js b/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js new file mode 100644 index 0000000..f0f30ed --- /dev/null +++ b/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js @@ -0,0 +1,7 @@ +var AwaitValue = require("./AwaitValue.js"); + +function _awaitAsyncGenerator(value) { + return new AwaitValue(value); +} + +module.exports = _awaitAsyncGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/checkPrivateRedeclaration.js b/node_modules/@babel/runtime/helpers/checkPrivateRedeclaration.js new file mode 100644 index 0000000..6cd0fcb --- /dev/null +++ b/node_modules/@babel/runtime/helpers/checkPrivateRedeclaration.js @@ -0,0 +1,7 @@ +function _checkPrivateRedeclaration(obj, privateCollection) { + if (privateCollection.has(obj)) { + throw new TypeError("Cannot initialize the same private elements twice on an object"); + } +} + +module.exports = _checkPrivateRedeclaration, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js new file mode 100644 index 0000000..ea1c860 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js @@ -0,0 +1,22 @@ +function _classApplyDescriptorDestructureSet(receiver, descriptor) { + if (descriptor.set) { + if (!("__destrObj" in descriptor)) { + descriptor.__destrObj = { + set value(v) { + descriptor.set.call(receiver, v); + } + + }; + } + + return descriptor.__destrObj; + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + + return descriptor; + } +} + +module.exports = _classApplyDescriptorDestructureSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js new file mode 100644 index 0000000..b9d0e94 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js @@ -0,0 +1,9 @@ +function _classApplyDescriptorGet(receiver, descriptor) { + if (descriptor.get) { + return descriptor.get.call(receiver); + } + + return descriptor.value; +} + +module.exports = _classApplyDescriptorGet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js new file mode 100644 index 0000000..9824b5c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js @@ -0,0 +1,13 @@ +function _classApplyDescriptorSet(receiver, descriptor, value) { + if (descriptor.set) { + descriptor.set.call(receiver, value); + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + + descriptor.value = value; + } +} + +module.exports = _classApplyDescriptorSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classCallCheck.js b/node_modules/@babel/runtime/helpers/classCallCheck.js new file mode 100644 index 0000000..1418845 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classCallCheck.js @@ -0,0 +1,7 @@ +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} + +module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js new file mode 100644 index 0000000..7f5213b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js @@ -0,0 +1,7 @@ +function _classCheckPrivateStaticAccess(receiver, classConstructor) { + if (receiver !== classConstructor) { + throw new TypeError("Private static access of wrong provenance"); + } +} + +module.exports = _classCheckPrivateStaticAccess, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js new file mode 100644 index 0000000..87ec4ea --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js @@ -0,0 +1,7 @@ +function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { + if (descriptor === undefined) { + throw new TypeError("attempted to " + action + " private static field before its declaration"); + } +} + +module.exports = _classCheckPrivateStaticFieldDescriptor, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js b/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js new file mode 100644 index 0000000..5c422bf --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js @@ -0,0 +1,9 @@ +function _classExtractFieldDescriptor(receiver, privateMap, action) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to " + action + " private field on non-instance"); + } + + return privateMap.get(receiver); +} + +module.exports = _classExtractFieldDescriptor, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classNameTDZError.js b/node_modules/@babel/runtime/helpers/classNameTDZError.js new file mode 100644 index 0000000..9a48c70 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classNameTDZError.js @@ -0,0 +1,5 @@ +function _classNameTDZError(name) { + throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); +} + +module.exports = _classNameTDZError, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js new file mode 100644 index 0000000..07abfe5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js @@ -0,0 +1,10 @@ +var classApplyDescriptorDestructureSet = require("./classApplyDescriptorDestructureSet.js"); + +var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js"); + +function _classPrivateFieldDestructureSet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} + +module.exports = _classPrivateFieldDestructureSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js new file mode 100644 index 0000000..470ded7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js @@ -0,0 +1,10 @@ +var classApplyDescriptorGet = require("./classApplyDescriptorGet.js"); + +var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js"); + +function _classPrivateFieldGet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} + +module.exports = _classPrivateFieldGet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldInitSpec.js b/node_modules/@babel/runtime/helpers/classPrivateFieldInitSpec.js new file mode 100644 index 0000000..a6243c2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldInitSpec.js @@ -0,0 +1,8 @@ +var checkPrivateRedeclaration = require("./checkPrivateRedeclaration.js"); + +function _classPrivateFieldInitSpec(obj, privateMap, value) { + checkPrivateRedeclaration(obj, privateMap); + privateMap.set(obj, value); +} + +module.exports = _classPrivateFieldInitSpec, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js new file mode 100644 index 0000000..571109f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js @@ -0,0 +1,9 @@ +function _classPrivateFieldBase(receiver, privateKey) { + if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { + throw new TypeError("attempted to use private field on non-instance"); + } + + return receiver; +} + +module.exports = _classPrivateFieldBase, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js new file mode 100644 index 0000000..b05e194 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js @@ -0,0 +1,7 @@ +var id = 0; + +function _classPrivateFieldKey(name) { + return "__private_" + id++ + "_" + name; +} + +module.exports = _classPrivateFieldKey, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js new file mode 100644 index 0000000..f8ab842 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js @@ -0,0 +1,11 @@ +var classApplyDescriptorSet = require("./classApplyDescriptorSet.js"); + +var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js"); + +function _classPrivateFieldSet(receiver, privateMap, value) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} + +module.exports = _classPrivateFieldSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js new file mode 100644 index 0000000..540a1f3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js @@ -0,0 +1,9 @@ +function _classPrivateMethodGet(receiver, privateSet, fn) { + if (!privateSet.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + + return fn; +} + +module.exports = _classPrivateMethodGet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateMethodInitSpec.js b/node_modules/@babel/runtime/helpers/classPrivateMethodInitSpec.js new file mode 100644 index 0000000..6c4df76 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateMethodInitSpec.js @@ -0,0 +1,8 @@ +var checkPrivateRedeclaration = require("./checkPrivateRedeclaration.js"); + +function _classPrivateMethodInitSpec(obj, privateSet) { + checkPrivateRedeclaration(obj, privateSet); + privateSet.add(obj); +} + +module.exports = _classPrivateMethodInitSpec, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js new file mode 100644 index 0000000..226789d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js @@ -0,0 +1,5 @@ +function _classPrivateMethodSet() { + throw new TypeError("attempted to reassign private method"); +} + +module.exports = _classPrivateMethodSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js new file mode 100644 index 0000000..120c74d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js @@ -0,0 +1,13 @@ +var classApplyDescriptorDestructureSet = require("./classApplyDescriptorDestructureSet.js"); + +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); + +var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js"); + +function _classStaticPrivateFieldDestructureSet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} + +module.exports = _classStaticPrivateFieldDestructureSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js new file mode 100644 index 0000000..d7201c3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js @@ -0,0 +1,13 @@ +var classApplyDescriptorGet = require("./classApplyDescriptorGet.js"); + +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); + +var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js"); + +function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} + +module.exports = _classStaticPrivateFieldSpecGet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js new file mode 100644 index 0000000..2aa13ef --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js @@ -0,0 +1,14 @@ +var classApplyDescriptorSet = require("./classApplyDescriptorSet.js"); + +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); + +var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js"); + +function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} + +module.exports = _classStaticPrivateFieldSpecSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js new file mode 100644 index 0000000..d77c842 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js @@ -0,0 +1,8 @@ +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); + +function _classStaticPrivateMethodGet(receiver, classConstructor, method) { + classCheckPrivateStaticAccess(receiver, classConstructor); + return method; +} + +module.exports = _classStaticPrivateMethodGet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js new file mode 100644 index 0000000..2e1c83f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js @@ -0,0 +1,5 @@ +function _classStaticPrivateMethodSet() { + throw new TypeError("attempted to set read only static private field"); +} + +module.exports = _classStaticPrivateMethodSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/construct.js b/node_modules/@babel/runtime/helpers/construct.js new file mode 100644 index 0000000..c2518af --- /dev/null +++ b/node_modules/@babel/runtime/helpers/construct.js @@ -0,0 +1,22 @@ +var setPrototypeOf = require("./setPrototypeOf.js"); + +var isNativeReflectConstruct = require("./isNativeReflectConstruct.js"); + +function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + module.exports = _construct = Reflect.construct, module.exports.__esModule = true, module.exports["default"] = module.exports; + } else { + module.exports = _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + } + + return _construct.apply(null, arguments); +} + +module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createClass.js b/node_modules/@babel/runtime/helpers/createClass.js new file mode 100644 index 0000000..4273e7a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createClass.js @@ -0,0 +1,20 @@ +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; +} + +module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js b/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js new file mode 100644 index 0000000..0835893 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js @@ -0,0 +1,60 @@ +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + + if (!it) { + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + + var F = function F() {}; + + return { + s: F, + n: function n() { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function e(_e) { + throw _e; + }, + f: F + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var normalCompletion = true, + didErr = false, + err; + return { + s: function s() { + it = it.call(o); + }, + n: function n() { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function e(_e2) { + didErr = true; + err = _e2; + }, + f: function f() { + try { + if (!normalCompletion && it["return"] != null) it["return"](); + } finally { + if (didErr) throw err; + } + } + }; +} + +module.exports = _createForOfIteratorHelper, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js b/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js new file mode 100644 index 0000000..65d3bc9 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js @@ -0,0 +1,24 @@ +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +function _createForOfIteratorHelperLoose(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (it) return (it = it.call(o)).next.bind(it); + + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + return function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +module.exports = _createForOfIteratorHelperLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createSuper.js b/node_modules/@babel/runtime/helpers/createSuper.js new file mode 100644 index 0000000..624728b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createSuper.js @@ -0,0 +1,24 @@ +var getPrototypeOf = require("./getPrototypeOf.js"); + +var isNativeReflectConstruct = require("./isNativeReflectConstruct.js"); + +var possibleConstructorReturn = require("./possibleConstructorReturn.js"); + +function _createSuper(Derived) { + var hasNativeReflectConstruct = isNativeReflectConstruct(); + return function _createSuperInternal() { + var Super = getPrototypeOf(Derived), + result; + + if (hasNativeReflectConstruct) { + var NewTarget = getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + + return possibleConstructorReturn(this, result); + }; +} + +module.exports = _createSuper, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/decorate.js b/node_modules/@babel/runtime/helpers/decorate.js new file mode 100644 index 0000000..3bd35e7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/decorate.js @@ -0,0 +1,400 @@ +var toArray = require("./toArray.js"); + +var toPropertyKey = require("./toPropertyKey.js"); + +function _decorate(decorators, factory, superClass, mixins) { + var api = _getDecoratorsApi(); + + if (mixins) { + for (var i = 0; i < mixins.length; i++) { + api = mixins[i](api); + } + } + + var r = factory(function initialize(O) { + api.initializeInstanceElements(O, decorated.elements); + }, superClass); + var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); + api.initializeClassElements(r.F, decorated.elements); + return api.runClassFinishers(r.F, decorated.finishers); +} + +function _getDecoratorsApi() { + _getDecoratorsApi = function _getDecoratorsApi() { + return api; + }; + + var api = { + elementsDefinitionOrder: [["method"], ["field"]], + initializeInstanceElements: function initializeInstanceElements(O, elements) { + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + if (element.kind === kind && element.placement === "own") { + this.defineClassElement(O, element); + } + }, this); + }, this); + }, + initializeClassElements: function initializeClassElements(F, elements) { + var proto = F.prototype; + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + var placement = element.placement; + + if (element.kind === kind && (placement === "static" || placement === "prototype")) { + var receiver = placement === "static" ? F : proto; + this.defineClassElement(receiver, element); + } + }, this); + }, this); + }, + defineClassElement: function defineClassElement(receiver, element) { + var descriptor = element.descriptor; + + if (element.kind === "field") { + var initializer = element.initializer; + descriptor = { + enumerable: descriptor.enumerable, + writable: descriptor.writable, + configurable: descriptor.configurable, + value: initializer === void 0 ? void 0 : initializer.call(receiver) + }; + } + + Object.defineProperty(receiver, element.key, descriptor); + }, + decorateClass: function decorateClass(elements, decorators) { + var newElements = []; + var finishers = []; + var placements = { + "static": [], + prototype: [], + own: [] + }; + elements.forEach(function (element) { + this.addElementPlacement(element, placements); + }, this); + elements.forEach(function (element) { + if (!_hasDecorators(element)) return newElements.push(element); + var elementFinishersExtras = this.decorateElement(element, placements); + newElements.push(elementFinishersExtras.element); + newElements.push.apply(newElements, elementFinishersExtras.extras); + finishers.push.apply(finishers, elementFinishersExtras.finishers); + }, this); + + if (!decorators) { + return { + elements: newElements, + finishers: finishers + }; + } + + var result = this.decorateConstructor(newElements, decorators); + finishers.push.apply(finishers, result.finishers); + result.finishers = finishers; + return result; + }, + addElementPlacement: function addElementPlacement(element, placements, silent) { + var keys = placements[element.placement]; + + if (!silent && keys.indexOf(element.key) !== -1) { + throw new TypeError("Duplicated element (" + element.key + ")"); + } + + keys.push(element.key); + }, + decorateElement: function decorateElement(element, placements) { + var extras = []; + var finishers = []; + + for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { + var keys = placements[element.placement]; + keys.splice(keys.indexOf(element.key), 1); + var elementObject = this.fromElementDescriptor(element); + var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); + element = elementFinisherExtras.element; + this.addElementPlacement(element, placements); + + if (elementFinisherExtras.finisher) { + finishers.push(elementFinisherExtras.finisher); + } + + var newExtras = elementFinisherExtras.extras; + + if (newExtras) { + for (var j = 0; j < newExtras.length; j++) { + this.addElementPlacement(newExtras[j], placements); + } + + extras.push.apply(extras, newExtras); + } + } + + return { + element: element, + finishers: finishers, + extras: extras + }; + }, + decorateConstructor: function decorateConstructor(elements, decorators) { + var finishers = []; + + for (var i = decorators.length - 1; i >= 0; i--) { + var obj = this.fromClassDescriptor(elements); + var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); + + if (elementsAndFinisher.finisher !== undefined) { + finishers.push(elementsAndFinisher.finisher); + } + + if (elementsAndFinisher.elements !== undefined) { + elements = elementsAndFinisher.elements; + + for (var j = 0; j < elements.length - 1; j++) { + for (var k = j + 1; k < elements.length; k++) { + if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { + throw new TypeError("Duplicated element (" + elements[j].key + ")"); + } + } + } + } + } + + return { + elements: elements, + finishers: finishers + }; + }, + fromElementDescriptor: function fromElementDescriptor(element) { + var obj = { + kind: element.kind, + key: element.key, + placement: element.placement, + descriptor: element.descriptor + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + if (element.kind === "field") obj.initializer = element.initializer; + return obj; + }, + toElementDescriptors: function toElementDescriptors(elementObjects) { + if (elementObjects === undefined) return; + return toArray(elementObjects).map(function (elementObject) { + var element = this.toElementDescriptor(elementObject); + this.disallowProperty(elementObject, "finisher", "An element descriptor"); + this.disallowProperty(elementObject, "extras", "An element descriptor"); + return element; + }, this); + }, + toElementDescriptor: function toElementDescriptor(elementObject) { + var kind = String(elementObject.kind); + + if (kind !== "method" && kind !== "field") { + throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); + } + + var key = toPropertyKey(elementObject.key); + var placement = String(elementObject.placement); + + if (placement !== "static" && placement !== "prototype" && placement !== "own") { + throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); + } + + var descriptor = elementObject.descriptor; + this.disallowProperty(elementObject, "elements", "An element descriptor"); + var element = { + kind: kind, + key: key, + placement: placement, + descriptor: Object.assign({}, descriptor) + }; + + if (kind !== "field") { + this.disallowProperty(elementObject, "initializer", "A method descriptor"); + } else { + this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); + element.initializer = elementObject.initializer; + } + + return element; + }, + toElementFinisherExtras: function toElementFinisherExtras(elementObject) { + var element = this.toElementDescriptor(elementObject); + + var finisher = _optionalCallableProperty(elementObject, "finisher"); + + var extras = this.toElementDescriptors(elementObject.extras); + return { + element: element, + finisher: finisher, + extras: extras + }; + }, + fromClassDescriptor: function fromClassDescriptor(elements) { + var obj = { + kind: "class", + elements: elements.map(this.fromElementDescriptor, this) + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + return obj; + }, + toClassDescriptor: function toClassDescriptor(obj) { + var kind = String(obj.kind); + + if (kind !== "class") { + throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); + } + + this.disallowProperty(obj, "key", "A class descriptor"); + this.disallowProperty(obj, "placement", "A class descriptor"); + this.disallowProperty(obj, "descriptor", "A class descriptor"); + this.disallowProperty(obj, "initializer", "A class descriptor"); + this.disallowProperty(obj, "extras", "A class descriptor"); + + var finisher = _optionalCallableProperty(obj, "finisher"); + + var elements = this.toElementDescriptors(obj.elements); + return { + elements: elements, + finisher: finisher + }; + }, + runClassFinishers: function runClassFinishers(constructor, finishers) { + for (var i = 0; i < finishers.length; i++) { + var newConstructor = (0, finishers[i])(constructor); + + if (newConstructor !== undefined) { + if (typeof newConstructor !== "function") { + throw new TypeError("Finishers must return a constructor."); + } + + constructor = newConstructor; + } + } + + return constructor; + }, + disallowProperty: function disallowProperty(obj, name, objectType) { + if (obj[name] !== undefined) { + throw new TypeError(objectType + " can't have a ." + name + " property."); + } + } + }; + return api; +} + +function _createElementDescriptor(def) { + var key = toPropertyKey(def.key); + var descriptor; + + if (def.kind === "method") { + descriptor = { + value: def.value, + writable: true, + configurable: true, + enumerable: false + }; + } else if (def.kind === "get") { + descriptor = { + get: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "set") { + descriptor = { + set: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "field") { + descriptor = { + configurable: true, + writable: true, + enumerable: true + }; + } + + var element = { + kind: def.kind === "field" ? "field" : "method", + key: key, + placement: def["static"] ? "static" : def.kind === "field" ? "own" : "prototype", + descriptor: descriptor + }; + if (def.decorators) element.decorators = def.decorators; + if (def.kind === "field") element.initializer = def.value; + return element; +} + +function _coalesceGetterSetter(element, other) { + if (element.descriptor.get !== undefined) { + other.descriptor.get = element.descriptor.get; + } else { + other.descriptor.set = element.descriptor.set; + } +} + +function _coalesceClassElements(elements) { + var newElements = []; + + var isSameElement = function isSameElement(other) { + return other.kind === "method" && other.key === element.key && other.placement === element.placement; + }; + + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + var other; + + if (element.kind === "method" && (other = newElements.find(isSameElement))) { + if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { + if (_hasDecorators(element) || _hasDecorators(other)) { + throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); + } + + other.descriptor = element.descriptor; + } else { + if (_hasDecorators(element)) { + if (_hasDecorators(other)) { + throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); + } + + other.decorators = element.decorators; + } + + _coalesceGetterSetter(element, other); + } + } else { + newElements.push(element); + } + } + + return newElements; +} + +function _hasDecorators(element) { + return element.decorators && element.decorators.length; +} + +function _isDataDescriptor(desc) { + return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); +} + +function _optionalCallableProperty(obj, name) { + var value = obj[name]; + + if (value !== undefined && typeof value !== "function") { + throw new TypeError("Expected '" + name + "' to be a function"); + } + + return value; +} + +module.exports = _decorate, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/defaults.js b/node_modules/@babel/runtime/helpers/defaults.js new file mode 100644 index 0000000..6c1c196 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/defaults.js @@ -0,0 +1,16 @@ +function _defaults(obj, defaults) { + var keys = Object.getOwnPropertyNames(defaults); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = Object.getOwnPropertyDescriptor(defaults, key); + + if (value && value.configurable && obj[key] === undefined) { + Object.defineProperty(obj, key, value); + } + } + + return obj; +} + +module.exports = _defaults, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js b/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js new file mode 100644 index 0000000..cd49128 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js @@ -0,0 +1,24 @@ +function _defineEnumerableProperties(obj, descs) { + for (var key in descs) { + var desc = descs[key]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, key, desc); + } + + if (Object.getOwnPropertySymbols) { + var objectSymbols = Object.getOwnPropertySymbols(descs); + + for (var i = 0; i < objectSymbols.length; i++) { + var sym = objectSymbols[i]; + var desc = descs[sym]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, sym, desc); + } + } + + return obj; +} + +module.exports = _defineEnumerableProperties, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/defineProperty.js b/node_modules/@babel/runtime/helpers/defineProperty.js new file mode 100644 index 0000000..fe7d6bb --- /dev/null +++ b/node_modules/@babel/runtime/helpers/defineProperty.js @@ -0,0 +1,16 @@ +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js new file mode 100644 index 0000000..919aab8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js @@ -0,0 +1,95 @@ +import AwaitValue from "./AwaitValue.js"; +export default function AsyncGenerator(gen) { + var front, back; + + function send(key, arg) { + return new Promise(function (resolve, reject) { + var request = { + key: key, + arg: arg, + resolve: resolve, + reject: reject, + next: null + }; + + if (back) { + back = back.next = request; + } else { + front = back = request; + resume(key, arg); + } + }); + } + + function resume(key, arg) { + try { + var result = gen[key](arg); + var value = result.value; + var wrappedAwait = value instanceof AwaitValue; + Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { + if (wrappedAwait) { + resume(key === "return" ? "return" : "next", arg); + return; + } + + settle(result.done ? "return" : "normal", arg); + }, function (err) { + resume("throw", err); + }); + } catch (err) { + settle("throw", err); + } + } + + function settle(type, value) { + switch (type) { + case "return": + front.resolve({ + value: value, + done: true + }); + break; + + case "throw": + front.reject(value); + break; + + default: + front.resolve({ + value: value, + done: false + }); + break; + } + + front = front.next; + + if (front) { + resume(front.key, front.arg); + } else { + back = null; + } + } + + this._invoke = send; + + if (typeof gen["return"] !== "function") { + this["return"] = undefined; + } +} + +AsyncGenerator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function () { + return this; +}; + +AsyncGenerator.prototype.next = function (arg) { + return this._invoke("next", arg); +}; + +AsyncGenerator.prototype["throw"] = function (arg) { + return this._invoke("throw", arg); +}; + +AsyncGenerator.prototype["return"] = function (arg) { + return this._invoke("return", arg); +}; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/AwaitValue.js b/node_modules/@babel/runtime/helpers/esm/AwaitValue.js new file mode 100644 index 0000000..5237e18 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/AwaitValue.js @@ -0,0 +1,3 @@ +export default function _AwaitValue(value) { + this.wrapped = value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js b/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js new file mode 100644 index 0000000..84b5961 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js @@ -0,0 +1,28 @@ +export default function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { + var desc = {}; + Object.keys(descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0) { + Object.defineProperty(target, property, desc); + desc = null; + } + + return desc; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/applyDecs.js b/node_modules/@babel/runtime/helpers/esm/applyDecs.js new file mode 100644 index 0000000..a6187c0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/applyDecs.js @@ -0,0 +1,282 @@ +import _typeof from "./typeof.js"; + +function createMetadataMethodsForProperty(metadataMap, kind, property, decoratorFinishedRef) { + return { + getMetadata: function getMetadata(key) { + assertNotFinished(decoratorFinishedRef, "getMetadata"), assertMetadataKey(key); + var metadataForKey = metadataMap[key]; + if (void 0 !== metadataForKey) if (1 === kind) { + var pub = metadataForKey["public"]; + if (void 0 !== pub) return pub[property]; + } else if (2 === kind) { + var priv = metadataForKey["private"]; + if (void 0 !== priv) return priv.get(property); + } else if (Object.hasOwnProperty.call(metadataForKey, "constructor")) return metadataForKey.constructor; + }, + setMetadata: function setMetadata(key, value) { + assertNotFinished(decoratorFinishedRef, "setMetadata"), assertMetadataKey(key); + var metadataForKey = metadataMap[key]; + + if (void 0 === metadataForKey && (metadataForKey = metadataMap[key] = {}), 1 === kind) { + var pub = metadataForKey["public"]; + void 0 === pub && (pub = metadataForKey["public"] = {}), pub[property] = value; + } else if (2 === kind) { + var priv = metadataForKey.priv; + void 0 === priv && (priv = metadataForKey["private"] = new Map()), priv.set(property, value); + } else metadataForKey.constructor = value; + } + }; +} + +function convertMetadataMapToFinal(obj, metadataMap) { + var parentMetadataMap = obj[Symbol.metadata || Symbol["for"]("Symbol.metadata")], + metadataKeys = Object.getOwnPropertySymbols(metadataMap); + + if (0 !== metadataKeys.length) { + for (var i = 0; i < metadataKeys.length; i++) { + var key = metadataKeys[i], + metaForKey = metadataMap[key], + parentMetaForKey = parentMetadataMap ? parentMetadataMap[key] : null, + pub = metaForKey["public"], + parentPub = parentMetaForKey ? parentMetaForKey["public"] : null; + pub && parentPub && Object.setPrototypeOf(pub, parentPub); + var priv = metaForKey["private"]; + + if (priv) { + var privArr = Array.from(priv.values()), + parentPriv = parentMetaForKey ? parentMetaForKey["private"] : null; + parentPriv && (privArr = privArr.concat(parentPriv)), metaForKey["private"] = privArr; + } + + parentMetaForKey && Object.setPrototypeOf(metaForKey, parentMetaForKey); + } + + parentMetadataMap && Object.setPrototypeOf(metadataMap, parentMetadataMap), obj[Symbol.metadata || Symbol["for"]("Symbol.metadata")] = metadataMap; + } +} + +function createAddInitializerMethod(initializers, decoratorFinishedRef) { + return function (initializer) { + assertNotFinished(decoratorFinishedRef, "addInitializer"), assertCallable(initializer, "An initializer"), initializers.push(initializer); + }; +} + +function memberDec(dec, name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value) { + var kindStr; + + switch (kind) { + case 1: + kindStr = "accessor"; + break; + + case 2: + kindStr = "method"; + break; + + case 3: + kindStr = "getter"; + break; + + case 4: + kindStr = "setter"; + break; + + default: + kindStr = "field"; + } + + var metadataKind, + metadataName, + ctx = { + kind: kindStr, + name: isPrivate ? "#" + name : name, + isStatic: isStatic, + isPrivate: isPrivate + }, + decoratorFinishedRef = { + v: !1 + }; + + if (0 !== kind && (ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef)), isPrivate) { + metadataKind = 2, metadataName = Symbol(name); + var access = {}; + 0 === kind ? (access.get = desc.get, access.set = desc.set) : 2 === kind ? access.get = function () { + return desc.value; + } : (1 !== kind && 3 !== kind || (access.get = function () { + return desc.get.call(this); + }), 1 !== kind && 4 !== kind || (access.set = function (v) { + desc.set.call(this, v); + })), ctx.access = access; + } else metadataKind = 1, metadataName = name; + + try { + return dec(value, Object.assign(ctx, createMetadataMethodsForProperty(metadataMap, metadataKind, metadataName, decoratorFinishedRef))); + } finally { + decoratorFinishedRef.v = !0; + } +} + +function assertNotFinished(decoratorFinishedRef, fnName) { + if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished"); +} + +function assertMetadataKey(key) { + if ("symbol" != _typeof(key)) throw new TypeError("Metadata keys must be symbols, received: " + key); +} + +function assertCallable(fn, hint) { + if ("function" != typeof fn) throw new TypeError(hint + " must be a function"); +} + +function assertValidReturnValue(kind, value) { + var type = _typeof(value); + + if (1 === kind) { + if ("object" !== type || null === value) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); + void 0 !== value.get && assertCallable(value.get, "accessor.get"), void 0 !== value.set && assertCallable(value.set, "accessor.set"), void 0 !== value.init && assertCallable(value.init, "accessor.init"), void 0 !== value.initializer && assertCallable(value.initializer, "accessor.initializer"); + } else if ("function" !== type) { + var hint; + throw hint = 0 === kind ? "field" : 10 === kind ? "class" : "method", new TypeError(hint + " decorators must return a function or void 0"); + } +} + +function getInit(desc) { + var initializer; + return null == (initializer = desc.init) && (initializer = desc.initializer) && "undefined" != typeof console && console.warn(".initializer has been renamed to .init as of March 2022"), initializer; +} + +function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, metadataMap, initializers) { + var desc, + initializer, + value, + newValue, + get, + set, + decs = decInfo[0]; + if (isPrivate ? desc = 0 === kind || 1 === kind ? { + get: decInfo[3], + set: decInfo[4] + } : 3 === kind ? { + get: decInfo[3] + } : 4 === kind ? { + set: decInfo[3] + } : { + value: decInfo[3] + } : 0 !== kind && (desc = Object.getOwnPropertyDescriptor(base, name)), 1 === kind ? value = { + get: desc.get, + set: desc.set + } : 2 === kind ? value = desc.value : 3 === kind ? value = desc.get : 4 === kind && (value = desc.set), "function" == typeof decs) void 0 !== (newValue = memberDec(decs, name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value)) && (assertValidReturnValue(kind, newValue), 0 === kind ? initializer = newValue : 1 === kind ? (initializer = getInit(newValue), get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue);else for (var i = decs.length - 1; i >= 0; i--) { + var newInit; + if (void 0 !== (newValue = memberDec(decs[i], name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value))) assertValidReturnValue(kind, newValue), 0 === kind ? newInit = newValue : 1 === kind ? (newInit = getInit(newValue), get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue, void 0 !== newInit && (void 0 === initializer ? initializer = newInit : "function" == typeof initializer ? initializer = [initializer, newInit] : initializer.push(newInit)); + } + + if (0 === kind || 1 === kind) { + if (void 0 === initializer) initializer = function initializer(instance, init) { + return init; + };else if ("function" != typeof initializer) { + var ownInitializers = initializer; + + initializer = function initializer(instance, init) { + for (var value = init, i = 0; i < ownInitializers.length; i++) { + value = ownInitializers[i].call(instance, value); + } + + return value; + }; + } else { + var originalInitializer = initializer; + + initializer = function initializer(instance, init) { + return originalInitializer.call(instance, init); + }; + } + ret.push(initializer); + } + + 0 !== kind && (1 === kind ? (desc.get = value.get, desc.set = value.set) : 2 === kind ? desc.value = value : 3 === kind ? desc.get = value : 4 === kind && (desc.set = value), isPrivate ? 1 === kind ? (ret.push(function (instance, args) { + return value.get.call(instance, args); + }), ret.push(function (instance, args) { + return value.set.call(instance, args); + })) : 2 === kind ? ret.push(value) : ret.push(function (instance, args) { + return value.call(instance, args); + }) : Object.defineProperty(base, name, desc)); +} + +function applyMemberDecs(ret, Class, protoMetadataMap, staticMetadataMap, decInfos) { + for (var protoInitializers, staticInitializers, existingProtoNonFields = new Map(), existingStaticNonFields = new Map(), i = 0; i < decInfos.length; i++) { + var decInfo = decInfos[i]; + + if (Array.isArray(decInfo)) { + var base, + metadataMap, + initializers, + kind = decInfo[1], + name = decInfo[2], + isPrivate = decInfo.length > 3, + isStatic = kind >= 5; + + if (isStatic ? (base = Class, metadataMap = staticMetadataMap, 0 !== (kind -= 5) && (initializers = staticInitializers = staticInitializers || [])) : (base = Class.prototype, metadataMap = protoMetadataMap, 0 !== kind && (initializers = protoInitializers = protoInitializers || [])), 0 !== kind && !isPrivate) { + var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields, + existingKind = existingNonFields.get(name) || 0; + if (!0 === existingKind || 3 === existingKind && 4 !== kind || 4 === existingKind && 3 !== kind) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name); + !existingKind && kind > 2 ? existingNonFields.set(name, kind) : existingNonFields.set(name, !0); + } + + applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, metadataMap, initializers); + } + } + + pushInitializers(ret, protoInitializers), pushInitializers(ret, staticInitializers); +} + +function pushInitializers(ret, initializers) { + initializers && ret.push(function (instance) { + for (var i = 0; i < initializers.length; i++) { + initializers[i].call(instance); + } + + return instance; + }); +} + +function applyClassDecs(ret, targetClass, metadataMap, classDecs) { + if (classDecs.length > 0) { + for (var initializers = [], newClass = targetClass, name = targetClass.name, i = classDecs.length - 1; i >= 0; i--) { + var decoratorFinishedRef = { + v: !1 + }; + + try { + var ctx = Object.assign({ + kind: "class", + name: name, + addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef) + }, createMetadataMethodsForProperty(metadataMap, 0, name, decoratorFinishedRef)), + nextNewClass = classDecs[i](newClass, ctx); + } finally { + decoratorFinishedRef.v = !0; + } + + void 0 !== nextNewClass && (assertValidReturnValue(10, nextNewClass), newClass = nextNewClass); + } + + ret.push(newClass, function () { + for (var i = 0; i < initializers.length; i++) { + initializers[i].call(newClass); + } + }); + } +} + +export default function applyDecs(targetClass, memberDecs, classDecs) { + var ret = [], + staticMetadataMap = {}, + protoMetadataMap = {}; + return applyMemberDecs(ret, targetClass, protoMetadataMap, staticMetadataMap, memberDecs), convertMetadataMapToFinal(targetClass.prototype, protoMetadataMap), applyClassDecs(ret, targetClass, staticMetadataMap, classDecs), convertMetadataMapToFinal(targetClass, staticMetadataMap), ret; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js b/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js new file mode 100644 index 0000000..edbeb8e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js @@ -0,0 +1,9 @@ +export default function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) { + arr2[i] = arr[i]; + } + + return arr2; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js b/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js new file mode 100644 index 0000000..be734fc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js @@ -0,0 +1,3 @@ +export default function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js b/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js new file mode 100644 index 0000000..f7d8dc7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js @@ -0,0 +1,4 @@ +import arrayLikeToArray from "./arrayLikeToArray.js"; +export default function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js b/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js new file mode 100644 index 0000000..bbf849c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js @@ -0,0 +1,7 @@ +export default function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js b/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js new file mode 100644 index 0000000..a7ccd67 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js @@ -0,0 +1,54 @@ +export default function _asyncGeneratorDelegate(inner, awaitWrap) { + var iter = {}, + waiting = false; + + function pump(key, value) { + waiting = true; + value = new Promise(function (resolve) { + resolve(inner[key](value)); + }); + return { + done: false, + value: awaitWrap(value) + }; + } + + ; + + iter[typeof Symbol !== "undefined" && Symbol.iterator || "@@iterator"] = function () { + return this; + }; + + iter.next = function (value) { + if (waiting) { + waiting = false; + return value; + } + + return pump("next", value); + }; + + if (typeof inner["throw"] === "function") { + iter["throw"] = function (value) { + if (waiting) { + waiting = false; + throw value; + } + + return pump("throw", value); + }; + } + + if (typeof inner["return"] === "function") { + iter["return"] = function (value) { + if (waiting) { + waiting = false; + return value; + } + + return pump("return", value); + }; + } + + return iter; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/asyncIterator.js b/node_modules/@babel/runtime/helpers/esm/asyncIterator.js new file mode 100644 index 0000000..030c44e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/asyncIterator.js @@ -0,0 +1,48 @@ +export default function _asyncIterator(iterable) { + var method, + async, + sync, + retry = 2; + + for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { + if (async && null != (method = iterable[async])) return method.call(iterable); + if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable)); + async = "@@asyncIterator", sync = "@@iterator"; + } + + throw new TypeError("Object is not async iterable"); +} + +function AsyncFromSyncIterator(s) { + function AsyncFromSyncIteratorContinuation(r) { + if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); + var done = r.done; + return Promise.resolve(r.value).then(function (value) { + return { + value: value, + done: done + }; + }); + } + + return AsyncFromSyncIterator = function AsyncFromSyncIterator(s) { + this.s = s, this.n = s.next; + }, AsyncFromSyncIterator.prototype = { + s: null, + n: null, + next: function next() { + return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); + }, + "return": function _return(value) { + var ret = this.s["return"]; + return void 0 === ret ? Promise.resolve({ + value: value, + done: !0 + }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); + }, + "throw": function _throw(value) { + var thr = this.s["return"]; + return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); + } + }, new AsyncFromSyncIterator(s); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js b/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js new file mode 100644 index 0000000..2a25f54 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js @@ -0,0 +1,35 @@ +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); + } +} + +export default 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); + }); + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js new file mode 100644 index 0000000..ccca65e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js @@ -0,0 +1,4 @@ +import AwaitValue from "./AwaitValue.js"; +export default function _awaitAsyncGenerator(value) { + return new AwaitValue(value); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/checkPrivateRedeclaration.js b/node_modules/@babel/runtime/helpers/esm/checkPrivateRedeclaration.js new file mode 100644 index 0000000..9901403 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/checkPrivateRedeclaration.js @@ -0,0 +1,5 @@ +export default function _checkPrivateRedeclaration(obj, privateCollection) { + if (privateCollection.has(obj)) { + throw new TypeError("Cannot initialize the same private elements twice on an object"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js new file mode 100644 index 0000000..4472adc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js @@ -0,0 +1,20 @@ +export default function _classApplyDescriptorDestructureSet(receiver, descriptor) { + if (descriptor.set) { + if (!("__destrObj" in descriptor)) { + descriptor.__destrObj = { + set value(v) { + descriptor.set.call(receiver, v); + } + + }; + } + + return descriptor.__destrObj; + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + + return descriptor; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js new file mode 100644 index 0000000..0fad169 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js @@ -0,0 +1,7 @@ +export default function _classApplyDescriptorGet(receiver, descriptor) { + if (descriptor.get) { + return descriptor.get.call(receiver); + } + + return descriptor.value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js new file mode 100644 index 0000000..f295f3e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js @@ -0,0 +1,11 @@ +export default function _classApplyDescriptorSet(receiver, descriptor, value) { + if (descriptor.set) { + descriptor.set.call(receiver, value); + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + + descriptor.value = value; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classCallCheck.js b/node_modules/@babel/runtime/helpers/esm/classCallCheck.js new file mode 100644 index 0000000..2f1738a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classCallCheck.js @@ -0,0 +1,5 @@ +export default function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js new file mode 100644 index 0000000..098ed30 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js @@ -0,0 +1,5 @@ +export default function _classCheckPrivateStaticAccess(receiver, classConstructor) { + if (receiver !== classConstructor) { + throw new TypeError("Private static access of wrong provenance"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js new file mode 100644 index 0000000..0ef34b8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js @@ -0,0 +1,5 @@ +export default function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { + if (descriptor === undefined) { + throw new TypeError("attempted to " + action + " private static field before its declaration"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js b/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js new file mode 100644 index 0000000..8dabe9a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js @@ -0,0 +1,7 @@ +export default function _classExtractFieldDescriptor(receiver, privateMap, action) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to " + action + " private field on non-instance"); + } + + return privateMap.get(receiver); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js b/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js new file mode 100644 index 0000000..f7b6dd5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js @@ -0,0 +1,3 @@ +export default function _classNameTDZError(name) { + throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js new file mode 100644 index 0000000..fb58833 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js @@ -0,0 +1,6 @@ +import classApplyDescriptorDestructureSet from "./classApplyDescriptorDestructureSet.js"; +import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js"; +export default function _classPrivateFieldDestructureSet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js new file mode 100644 index 0000000..53cd137 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js @@ -0,0 +1,6 @@ +import classApplyDescriptorGet from "./classApplyDescriptorGet.js"; +import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js"; +export default function _classPrivateFieldGet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldInitSpec.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldInitSpec.js new file mode 100644 index 0000000..2253dd8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldInitSpec.js @@ -0,0 +1,5 @@ +import checkPrivateRedeclaration from "./checkPrivateRedeclaration.js"; +export default function _classPrivateFieldInitSpec(obj, privateMap, value) { + checkPrivateRedeclaration(obj, privateMap); + privateMap.set(obj, value); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js new file mode 100644 index 0000000..5b10916 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js @@ -0,0 +1,7 @@ +export default function _classPrivateFieldBase(receiver, privateKey) { + if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { + throw new TypeError("attempted to use private field on non-instance"); + } + + return receiver; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js new file mode 100644 index 0000000..5b7e5ac --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js @@ -0,0 +1,4 @@ +var id = 0; +export default function _classPrivateFieldKey(name) { + return "__private_" + id++ + "_" + name; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js new file mode 100644 index 0000000..ad91be4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js @@ -0,0 +1,7 @@ +import classApplyDescriptorSet from "./classApplyDescriptorSet.js"; +import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js"; +export default function _classPrivateFieldSet(receiver, privateMap, value) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js new file mode 100644 index 0000000..38b9d58 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js @@ -0,0 +1,7 @@ +export default function _classPrivateMethodGet(receiver, privateSet, fn) { + if (!privateSet.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + + return fn; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodInitSpec.js b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodInitSpec.js new file mode 100644 index 0000000..18d1291 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodInitSpec.js @@ -0,0 +1,5 @@ +import checkPrivateRedeclaration from "./checkPrivateRedeclaration.js"; +export default function _classPrivateMethodInitSpec(obj, privateSet) { + checkPrivateRedeclaration(obj, privateSet); + privateSet.add(obj); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js new file mode 100644 index 0000000..2bbaf3a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js @@ -0,0 +1,3 @@ +export default function _classPrivateMethodSet() { + throw new TypeError("attempted to reassign private method"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js new file mode 100644 index 0000000..77afcfb --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js @@ -0,0 +1,8 @@ +import classApplyDescriptorDestructureSet from "./classApplyDescriptorDestructureSet.js"; +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js"; +export default function _classStaticPrivateFieldDestructureSet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js new file mode 100644 index 0000000..d253d31 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js @@ -0,0 +1,8 @@ +import classApplyDescriptorGet from "./classApplyDescriptorGet.js"; +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js"; +export default function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js new file mode 100644 index 0000000..b0b0cc6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js @@ -0,0 +1,9 @@ +import classApplyDescriptorSet from "./classApplyDescriptorSet.js"; +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js"; +export default function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js new file mode 100644 index 0000000..fddc7b2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js @@ -0,0 +1,5 @@ +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +export default function _classStaticPrivateMethodGet(receiver, classConstructor, method) { + classCheckPrivateStaticAccess(receiver, classConstructor); + return method; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js new file mode 100644 index 0000000..d5ab60a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js @@ -0,0 +1,3 @@ +export default function _classStaticPrivateMethodSet() { + throw new TypeError("attempted to set read only static private field"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/construct.js b/node_modules/@babel/runtime/helpers/esm/construct.js new file mode 100644 index 0000000..0c39835 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/construct.js @@ -0,0 +1,18 @@ +import setPrototypeOf from "./setPrototypeOf.js"; +import isNativeReflectConstruct from "./isNativeReflectConstruct.js"; +export default function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + _construct = Reflect.construct; + } else { + _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }; + } + + return _construct.apply(null, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createClass.js b/node_modules/@babel/runtime/helpers/esm/createClass.js new file mode 100644 index 0000000..b320731 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createClass.js @@ -0,0 +1,18 @@ +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +export default function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js new file mode 100644 index 0000000..a7a2a50 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js @@ -0,0 +1,57 @@ +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +export default function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + + if (!it) { + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + + var F = function F() {}; + + return { + s: F, + n: function n() { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function e(_e) { + throw _e; + }, + f: F + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var normalCompletion = true, + didErr = false, + err; + return { + s: function s() { + it = it.call(o); + }, + n: function n() { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function e(_e2) { + didErr = true; + err = _e2; + }, + f: function f() { + try { + if (!normalCompletion && it["return"] != null) it["return"](); + } finally { + if (didErr) throw err; + } + } + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js new file mode 100644 index 0000000..640ec68 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js @@ -0,0 +1,21 @@ +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +export default function _createForOfIteratorHelperLoose(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (it) return (it = it.call(o)).next.bind(it); + + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + return function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createSuper.js b/node_modules/@babel/runtime/helpers/esm/createSuper.js new file mode 100644 index 0000000..ea5ea99 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createSuper.js @@ -0,0 +1,19 @@ +import getPrototypeOf from "./getPrototypeOf.js"; +import isNativeReflectConstruct from "./isNativeReflectConstruct.js"; +import possibleConstructorReturn from "./possibleConstructorReturn.js"; +export default function _createSuper(Derived) { + var hasNativeReflectConstruct = isNativeReflectConstruct(); + return function _createSuperInternal() { + var Super = getPrototypeOf(Derived), + result; + + if (hasNativeReflectConstruct) { + var NewTarget = getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + + return possibleConstructorReturn(this, result); + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/decorate.js b/node_modules/@babel/runtime/helpers/esm/decorate.js new file mode 100644 index 0000000..daf56da --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/decorate.js @@ -0,0 +1,396 @@ +import toArray from "./toArray.js"; +import toPropertyKey from "./toPropertyKey.js"; +export default function _decorate(decorators, factory, superClass, mixins) { + var api = _getDecoratorsApi(); + + if (mixins) { + for (var i = 0; i < mixins.length; i++) { + api = mixins[i](api); + } + } + + var r = factory(function initialize(O) { + api.initializeInstanceElements(O, decorated.elements); + }, superClass); + var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); + api.initializeClassElements(r.F, decorated.elements); + return api.runClassFinishers(r.F, decorated.finishers); +} + +function _getDecoratorsApi() { + _getDecoratorsApi = function _getDecoratorsApi() { + return api; + }; + + var api = { + elementsDefinitionOrder: [["method"], ["field"]], + initializeInstanceElements: function initializeInstanceElements(O, elements) { + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + if (element.kind === kind && element.placement === "own") { + this.defineClassElement(O, element); + } + }, this); + }, this); + }, + initializeClassElements: function initializeClassElements(F, elements) { + var proto = F.prototype; + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + var placement = element.placement; + + if (element.kind === kind && (placement === "static" || placement === "prototype")) { + var receiver = placement === "static" ? F : proto; + this.defineClassElement(receiver, element); + } + }, this); + }, this); + }, + defineClassElement: function defineClassElement(receiver, element) { + var descriptor = element.descriptor; + + if (element.kind === "field") { + var initializer = element.initializer; + descriptor = { + enumerable: descriptor.enumerable, + writable: descriptor.writable, + configurable: descriptor.configurable, + value: initializer === void 0 ? void 0 : initializer.call(receiver) + }; + } + + Object.defineProperty(receiver, element.key, descriptor); + }, + decorateClass: function decorateClass(elements, decorators) { + var newElements = []; + var finishers = []; + var placements = { + "static": [], + prototype: [], + own: [] + }; + elements.forEach(function (element) { + this.addElementPlacement(element, placements); + }, this); + elements.forEach(function (element) { + if (!_hasDecorators(element)) return newElements.push(element); + var elementFinishersExtras = this.decorateElement(element, placements); + newElements.push(elementFinishersExtras.element); + newElements.push.apply(newElements, elementFinishersExtras.extras); + finishers.push.apply(finishers, elementFinishersExtras.finishers); + }, this); + + if (!decorators) { + return { + elements: newElements, + finishers: finishers + }; + } + + var result = this.decorateConstructor(newElements, decorators); + finishers.push.apply(finishers, result.finishers); + result.finishers = finishers; + return result; + }, + addElementPlacement: function addElementPlacement(element, placements, silent) { + var keys = placements[element.placement]; + + if (!silent && keys.indexOf(element.key) !== -1) { + throw new TypeError("Duplicated element (" + element.key + ")"); + } + + keys.push(element.key); + }, + decorateElement: function decorateElement(element, placements) { + var extras = []; + var finishers = []; + + for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { + var keys = placements[element.placement]; + keys.splice(keys.indexOf(element.key), 1); + var elementObject = this.fromElementDescriptor(element); + var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); + element = elementFinisherExtras.element; + this.addElementPlacement(element, placements); + + if (elementFinisherExtras.finisher) { + finishers.push(elementFinisherExtras.finisher); + } + + var newExtras = elementFinisherExtras.extras; + + if (newExtras) { + for (var j = 0; j < newExtras.length; j++) { + this.addElementPlacement(newExtras[j], placements); + } + + extras.push.apply(extras, newExtras); + } + } + + return { + element: element, + finishers: finishers, + extras: extras + }; + }, + decorateConstructor: function decorateConstructor(elements, decorators) { + var finishers = []; + + for (var i = decorators.length - 1; i >= 0; i--) { + var obj = this.fromClassDescriptor(elements); + var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); + + if (elementsAndFinisher.finisher !== undefined) { + finishers.push(elementsAndFinisher.finisher); + } + + if (elementsAndFinisher.elements !== undefined) { + elements = elementsAndFinisher.elements; + + for (var j = 0; j < elements.length - 1; j++) { + for (var k = j + 1; k < elements.length; k++) { + if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { + throw new TypeError("Duplicated element (" + elements[j].key + ")"); + } + } + } + } + } + + return { + elements: elements, + finishers: finishers + }; + }, + fromElementDescriptor: function fromElementDescriptor(element) { + var obj = { + kind: element.kind, + key: element.key, + placement: element.placement, + descriptor: element.descriptor + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + if (element.kind === "field") obj.initializer = element.initializer; + return obj; + }, + toElementDescriptors: function toElementDescriptors(elementObjects) { + if (elementObjects === undefined) return; + return toArray(elementObjects).map(function (elementObject) { + var element = this.toElementDescriptor(elementObject); + this.disallowProperty(elementObject, "finisher", "An element descriptor"); + this.disallowProperty(elementObject, "extras", "An element descriptor"); + return element; + }, this); + }, + toElementDescriptor: function toElementDescriptor(elementObject) { + var kind = String(elementObject.kind); + + if (kind !== "method" && kind !== "field") { + throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); + } + + var key = toPropertyKey(elementObject.key); + var placement = String(elementObject.placement); + + if (placement !== "static" && placement !== "prototype" && placement !== "own") { + throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); + } + + var descriptor = elementObject.descriptor; + this.disallowProperty(elementObject, "elements", "An element descriptor"); + var element = { + kind: kind, + key: key, + placement: placement, + descriptor: Object.assign({}, descriptor) + }; + + if (kind !== "field") { + this.disallowProperty(elementObject, "initializer", "A method descriptor"); + } else { + this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); + element.initializer = elementObject.initializer; + } + + return element; + }, + toElementFinisherExtras: function toElementFinisherExtras(elementObject) { + var element = this.toElementDescriptor(elementObject); + + var finisher = _optionalCallableProperty(elementObject, "finisher"); + + var extras = this.toElementDescriptors(elementObject.extras); + return { + element: element, + finisher: finisher, + extras: extras + }; + }, + fromClassDescriptor: function fromClassDescriptor(elements) { + var obj = { + kind: "class", + elements: elements.map(this.fromElementDescriptor, this) + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + return obj; + }, + toClassDescriptor: function toClassDescriptor(obj) { + var kind = String(obj.kind); + + if (kind !== "class") { + throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); + } + + this.disallowProperty(obj, "key", "A class descriptor"); + this.disallowProperty(obj, "placement", "A class descriptor"); + this.disallowProperty(obj, "descriptor", "A class descriptor"); + this.disallowProperty(obj, "initializer", "A class descriptor"); + this.disallowProperty(obj, "extras", "A class descriptor"); + + var finisher = _optionalCallableProperty(obj, "finisher"); + + var elements = this.toElementDescriptors(obj.elements); + return { + elements: elements, + finisher: finisher + }; + }, + runClassFinishers: function runClassFinishers(constructor, finishers) { + for (var i = 0; i < finishers.length; i++) { + var newConstructor = (0, finishers[i])(constructor); + + if (newConstructor !== undefined) { + if (typeof newConstructor !== "function") { + throw new TypeError("Finishers must return a constructor."); + } + + constructor = newConstructor; + } + } + + return constructor; + }, + disallowProperty: function disallowProperty(obj, name, objectType) { + if (obj[name] !== undefined) { + throw new TypeError(objectType + " can't have a ." + name + " property."); + } + } + }; + return api; +} + +function _createElementDescriptor(def) { + var key = toPropertyKey(def.key); + var descriptor; + + if (def.kind === "method") { + descriptor = { + value: def.value, + writable: true, + configurable: true, + enumerable: false + }; + } else if (def.kind === "get") { + descriptor = { + get: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "set") { + descriptor = { + set: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "field") { + descriptor = { + configurable: true, + writable: true, + enumerable: true + }; + } + + var element = { + kind: def.kind === "field" ? "field" : "method", + key: key, + placement: def["static"] ? "static" : def.kind === "field" ? "own" : "prototype", + descriptor: descriptor + }; + if (def.decorators) element.decorators = def.decorators; + if (def.kind === "field") element.initializer = def.value; + return element; +} + +function _coalesceGetterSetter(element, other) { + if (element.descriptor.get !== undefined) { + other.descriptor.get = element.descriptor.get; + } else { + other.descriptor.set = element.descriptor.set; + } +} + +function _coalesceClassElements(elements) { + var newElements = []; + + var isSameElement = function isSameElement(other) { + return other.kind === "method" && other.key === element.key && other.placement === element.placement; + }; + + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + var other; + + if (element.kind === "method" && (other = newElements.find(isSameElement))) { + if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { + if (_hasDecorators(element) || _hasDecorators(other)) { + throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); + } + + other.descriptor = element.descriptor; + } else { + if (_hasDecorators(element)) { + if (_hasDecorators(other)) { + throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); + } + + other.decorators = element.decorators; + } + + _coalesceGetterSetter(element, other); + } + } else { + newElements.push(element); + } + } + + return newElements; +} + +function _hasDecorators(element) { + return element.decorators && element.decorators.length; +} + +function _isDataDescriptor(desc) { + return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); +} + +function _optionalCallableProperty(obj, name) { + var value = obj[name]; + + if (value !== undefined && typeof value !== "function") { + throw new TypeError("Expected '" + name + "' to be a function"); + } + + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/defaults.js b/node_modules/@babel/runtime/helpers/esm/defaults.js new file mode 100644 index 0000000..3de1d8e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/defaults.js @@ -0,0 +1,14 @@ +export default function _defaults(obj, defaults) { + var keys = Object.getOwnPropertyNames(defaults); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = Object.getOwnPropertyDescriptor(defaults, key); + + if (value && value.configurable && obj[key] === undefined) { + Object.defineProperty(obj, key, value); + } + } + + return obj; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js b/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js new file mode 100644 index 0000000..7981acd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js @@ -0,0 +1,22 @@ +export default function _defineEnumerableProperties(obj, descs) { + for (var key in descs) { + var desc = descs[key]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, key, desc); + } + + if (Object.getOwnPropertySymbols) { + var objectSymbols = Object.getOwnPropertySymbols(descs); + + for (var i = 0; i < objectSymbols.length; i++) { + var sym = objectSymbols[i]; + var desc = descs[sym]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, sym, desc); + } + } + + return obj; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/defineProperty.js b/node_modules/@babel/runtime/helpers/esm/defineProperty.js new file mode 100644 index 0000000..7cf6e59 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/defineProperty.js @@ -0,0 +1,14 @@ +export default function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/extends.js b/node_modules/@babel/runtime/helpers/esm/extends.js new file mode 100644 index 0000000..b9b138d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/extends.js @@ -0,0 +1,17 @@ +export default function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + return _extends.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/get.js b/node_modules/@babel/runtime/helpers/esm/get.js new file mode 100644 index 0000000..92038bd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/get.js @@ -0,0 +1,20 @@ +import superPropBase from "./superPropBase.js"; +export default function _get() { + if (typeof Reflect !== "undefined" && Reflect.get) { + _get = Reflect.get; + } else { + _get = function _get(target, property, receiver) { + var base = superPropBase(target, property); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.get) { + return desc.get.call(arguments.length < 3 ? target : receiver); + } + + return desc.value; + }; + } + + return _get.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js b/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js new file mode 100644 index 0000000..5abafe3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js @@ -0,0 +1,6 @@ +export default function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/identity.js b/node_modules/@babel/runtime/helpers/esm/identity.js new file mode 100644 index 0000000..a1e7e4c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/identity.js @@ -0,0 +1,3 @@ +export default function _identity(x) { + return x; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/inherits.js b/node_modules/@babel/runtime/helpers/esm/inherits.js new file mode 100644 index 0000000..e099909 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/inherits.js @@ -0,0 +1,18 @@ +import setPrototypeOf from "./setPrototypeOf.js"; +export default function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + Object.defineProperty(subClass, "prototype", { + writable: false + }); + if (superClass) setPrototypeOf(subClass, superClass); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js b/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js new file mode 100644 index 0000000..90bb796 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js @@ -0,0 +1,6 @@ +import setPrototypeOf from "./setPrototypeOf.js"; +export default function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + setPrototypeOf(subClass, superClass); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js b/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js new file mode 100644 index 0000000..26fdea0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js @@ -0,0 +1,9 @@ +export default function _initializerDefineProperty(target, property, descriptor, context) { + if (!descriptor) return; + Object.defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js b/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js new file mode 100644 index 0000000..30d518c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js @@ -0,0 +1,3 @@ +export default function _initializerWarningHelper(descriptor, context) { + throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/instanceof.js b/node_modules/@babel/runtime/helpers/esm/instanceof.js new file mode 100644 index 0000000..8c43b71 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/instanceof.js @@ -0,0 +1,7 @@ +export default function _instanceof(left, right) { + if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { + return !!right[Symbol.hasInstance](left); + } else { + return left instanceof right; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js b/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js new file mode 100644 index 0000000..c2df7b6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js @@ -0,0 +1,5 @@ +export default function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js b/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js new file mode 100644 index 0000000..01ee6b3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js @@ -0,0 +1,51 @@ +import _typeof from "./typeof.js"; + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +export default 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; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js b/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js new file mode 100644 index 0000000..7b1bc82 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js @@ -0,0 +1,3 @@ +export default function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js b/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js new file mode 100644 index 0000000..0da1624 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js @@ -0,0 +1,12 @@ +export default function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArray.js b/node_modules/@babel/runtime/helpers/esm/iterableToArray.js new file mode 100644 index 0000000..cfe9fbd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/iterableToArray.js @@ -0,0 +1,3 @@ +export default function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js new file mode 100644 index 0000000..c72ca94 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js @@ -0,0 +1,29 @@ +export default function _iterableToArrayLimit(arr, i) { + var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; + + if (_i == null) return; + var _arr = []; + var _n = true; + var _d = false; + + var _s, _e; + + try { + for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js new file mode 100644 index 0000000..27c15e0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js @@ -0,0 +1,14 @@ +export default function _iterableToArrayLimitLoose(arr, i) { + var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); + + if (_i == null) return; + var _arr = []; + + for (_i = _i.call(arr), _step; !(_step = _i.next()).done;) { + _arr.push(_step.value); + + if (i && _arr.length === i) break; + } + + return _arr; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/jsx.js b/node_modules/@babel/runtime/helpers/esm/jsx.js new file mode 100644 index 0000000..9a6a94c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/jsx.js @@ -0,0 +1,26 @@ +var REACT_ELEMENT_TYPE; +export default function _createRawReactElement(type, props, key, children) { + REACT_ELEMENT_TYPE || (REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103); + var defaultProps = type && type.defaultProps, + childrenLength = arguments.length - 3; + if (props || 0 === childrenLength || (props = { + children: void 0 + }), 1 === childrenLength) props.children = children;else if (childrenLength > 1) { + for (var childArray = new Array(childrenLength), i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 3]; + } + + props.children = childArray; + } + if (props && defaultProps) for (var propName in defaultProps) { + void 0 === props[propName] && (props[propName] = defaultProps[propName]); + } else props || (props = defaultProps || {}); + return { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: void 0 === key ? null : "" + key, + ref: null, + props: props, + _owner: null + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js b/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js new file mode 100644 index 0000000..f687959 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js @@ -0,0 +1,9 @@ +import arrayLikeToArray from "./arrayLikeToArray.js"; +export default function _maybeArrayLike(next, arr, i) { + if (arr && !Array.isArray(arr) && typeof arr.length === "number") { + var len = arr.length; + return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); + } + + return next(arr, i); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js b/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js new file mode 100644 index 0000000..d6cd864 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js @@ -0,0 +1,5 @@ +export default function _newArrowCheck(innerThis, boundThis) { + if (innerThis !== boundThis) { + throw new TypeError("Cannot instantiate an arrow function"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js b/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js new file mode 100644 index 0000000..b349d00 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js @@ -0,0 +1,3 @@ +export default function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js b/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js new file mode 100644 index 0000000..82d8296 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js @@ -0,0 +1,3 @@ +export default function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js b/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js new file mode 100644 index 0000000..82b67d2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js @@ -0,0 +1,3 @@ +export default function _objectDestructuringEmpty(obj) { + if (obj == null) throw new TypeError("Cannot destructure undefined"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectSpread.js b/node_modules/@babel/runtime/helpers/esm/objectSpread.js new file mode 100644 index 0000000..889a5f0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectSpread.js @@ -0,0 +1,19 @@ +import defineProperty from "./defineProperty.js"; +export default function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? Object(arguments[i]) : {}; + var ownKeys = Object.keys(source); + + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function (sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + })); + } + + ownKeys.forEach(function (key) { + defineProperty(target, key, source[key]); + }); + } + + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectSpread2.js b/node_modules/@babel/runtime/helpers/esm/objectSpread2.js new file mode 100644 index 0000000..76f2968 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectSpread2.js @@ -0,0 +1,27 @@ +import defineProperty from "./defineProperty.js"; + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + + return keys; +} + +export default function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { + defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js b/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js new file mode 100644 index 0000000..0fef321 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js @@ -0,0 +1,19 @@ +import objectWithoutPropertiesLoose from "./objectWithoutPropertiesLoose.js"; +export default function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + var target = objectWithoutPropertiesLoose(source, excluded); + var key, i; + + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js b/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js new file mode 100644 index 0000000..c36815c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js @@ -0,0 +1,14 @@ +export default function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/package.json b/node_modules/@babel/runtime/helpers/esm/package.json new file mode 100644 index 0000000..aead43d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js b/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js new file mode 100644 index 0000000..56d5544 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js @@ -0,0 +1,11 @@ +import _typeof from "./typeof.js"; +import assertThisInitialized from "./assertThisInitialized.js"; +export default function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + + return assertThisInitialized(self); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/readOnlyError.js b/node_modules/@babel/runtime/helpers/esm/readOnlyError.js new file mode 100644 index 0000000..166e40e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/readOnlyError.js @@ -0,0 +1,3 @@ +export default function _readOnlyError(name) { + throw new TypeError("\"" + name + "\" is read-only"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/set.js b/node_modules/@babel/runtime/helpers/esm/set.js new file mode 100644 index 0000000..9c54773 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/set.js @@ -0,0 +1,51 @@ +import superPropBase from "./superPropBase.js"; +import defineProperty from "./defineProperty.js"; + +function set(target, property, value, receiver) { + if (typeof Reflect !== "undefined" && Reflect.set) { + set = Reflect.set; + } else { + set = function set(target, property, value, receiver) { + var base = superPropBase(target, property); + var desc; + + if (base) { + desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.set) { + desc.set.call(receiver, value); + return true; + } else if (!desc.writable) { + return false; + } + } + + desc = Object.getOwnPropertyDescriptor(receiver, property); + + if (desc) { + if (!desc.writable) { + return false; + } + + desc.value = value; + Object.defineProperty(receiver, property, desc); + } else { + defineProperty(receiver, property, value); + } + + return true; + }; + } + + return set(target, property, value, receiver); +} + +export default function _set(target, property, value, receiver, isStrict) { + var s = set(target, property, value, receiver || target); + + if (!s && isStrict) { + throw new Error('failed to set property'); + } + + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js b/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js new file mode 100644 index 0000000..e6ef03e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js @@ -0,0 +1,8 @@ +export default function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js b/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js new file mode 100644 index 0000000..cadd9bb --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js @@ -0,0 +1,7 @@ +export default function _skipFirstGeneratorNext(fn) { + return function () { + var it = fn.apply(this, arguments); + it.next(); + return it; + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/slicedToArray.js b/node_modules/@babel/runtime/helpers/esm/slicedToArray.js new file mode 100644 index 0000000..618200b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/slicedToArray.js @@ -0,0 +1,7 @@ +import arrayWithHoles from "./arrayWithHoles.js"; +import iterableToArrayLimit from "./iterableToArrayLimit.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableRest from "./nonIterableRest.js"; +export default function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js b/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js new file mode 100644 index 0000000..efc7429 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js @@ -0,0 +1,7 @@ +import arrayWithHoles from "./arrayWithHoles.js"; +import iterableToArrayLimitLoose from "./iterableToArrayLimitLoose.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableRest from "./nonIterableRest.js"; +export default function _slicedToArrayLoose(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/superPropBase.js b/node_modules/@babel/runtime/helpers/esm/superPropBase.js new file mode 100644 index 0000000..feffe6f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/superPropBase.js @@ -0,0 +1,9 @@ +import getPrototypeOf from "./getPrototypeOf.js"; +export default function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = getPrototypeOf(object); + if (object === null) break; + } + + return object; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js new file mode 100644 index 0000000..421f18a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js @@ -0,0 +1,11 @@ +export default function _taggedTemplateLiteral(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + return Object.freeze(Object.defineProperties(strings, { + raw: { + value: Object.freeze(raw) + } + })); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js new file mode 100644 index 0000000..c8f081e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js @@ -0,0 +1,8 @@ +export default function _taggedTemplateLiteralLoose(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + strings.raw = raw; + return strings; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/tdz.js b/node_modules/@babel/runtime/helpers/esm/tdz.js new file mode 100644 index 0000000..d5d0adc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/tdz.js @@ -0,0 +1,3 @@ +export default function _tdzError(name) { + throw new ReferenceError(name + " is not defined - temporal dead zone"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/temporalRef.js b/node_modules/@babel/runtime/helpers/esm/temporalRef.js new file mode 100644 index 0000000..b25f7c4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/temporalRef.js @@ -0,0 +1,5 @@ +import undef from "./temporalUndefined.js"; +import err from "./tdz.js"; +export default function _temporalRef(val, name) { + return val === undef ? err(name) : val; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js b/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js new file mode 100644 index 0000000..1a35717 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js @@ -0,0 +1 @@ +export default function _temporalUndefined() {} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toArray.js b/node_modules/@babel/runtime/helpers/esm/toArray.js new file mode 100644 index 0000000..ad7c871 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toArray.js @@ -0,0 +1,7 @@ +import arrayWithHoles from "./arrayWithHoles.js"; +import iterableToArray from "./iterableToArray.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableRest from "./nonIterableRest.js"; +export default function _toArray(arr) { + return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js b/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js new file mode 100644 index 0000000..bd91285 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js @@ -0,0 +1,7 @@ +import arrayWithoutHoles from "./arrayWithoutHoles.js"; +import iterableToArray from "./iterableToArray.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableSpread from "./nonIterableSpread.js"; +export default function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toPrimitive.js b/node_modules/@babel/runtime/helpers/esm/toPrimitive.js new file mode 100644 index 0000000..fa32dda --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toPrimitive.js @@ -0,0 +1,13 @@ +import _typeof from "./typeof.js"; +export default function _toPrimitive(input, hint) { + if (_typeof(input) !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (_typeof(res) !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + + return (hint === "string" ? String : Number)(input); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js b/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js new file mode 100644 index 0000000..0fcc93b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js @@ -0,0 +1,6 @@ +import _typeof from "./typeof.js"; +import toPrimitive from "./toPrimitive.js"; +export default function _toPropertyKey(arg) { + var key = toPrimitive(arg, "string"); + return _typeof(key) === "symbol" ? key : String(key); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/typeof.js b/node_modules/@babel/runtime/helpers/esm/typeof.js new file mode 100644 index 0000000..92100c6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/typeof.js @@ -0,0 +1,9 @@ +export default function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js b/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js new file mode 100644 index 0000000..c0f63bd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js @@ -0,0 +1,9 @@ +import arrayLikeToArray from "./arrayLikeToArray.js"; +export default function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js new file mode 100644 index 0000000..723b2dd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js @@ -0,0 +1,6 @@ +import AsyncGenerator from "./AsyncGenerator.js"; +export default function _wrapAsyncGenerator(fn) { + return function () { + return new AsyncGenerator(fn.apply(this, arguments)); + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js b/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js new file mode 100644 index 0000000..512630d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js @@ -0,0 +1,37 @@ +import getPrototypeOf from "./getPrototypeOf.js"; +import setPrototypeOf from "./setPrototypeOf.js"; +import isNativeFunction from "./isNativeFunction.js"; +import construct from "./construct.js"; +export default function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); + } + + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); + } + + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return setPrototypeOf(Wrapper, Class); + }; + + return _wrapNativeSuper(Class); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js b/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js new file mode 100644 index 0000000..beac1e1 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js @@ -0,0 +1,50 @@ +import _typeof from "./typeof.js"; +import setPrototypeOf from "./setPrototypeOf.js"; +import inherits from "./inherits.js"; +export default function _wrapRegExp() { + _wrapRegExp = function _wrapRegExp(re, groups) { + return new BabelRegExp(re, void 0, groups); + }; + + var _super = RegExp.prototype, + _groups = new WeakMap(); + + function BabelRegExp(re, flags, groups) { + var _this = new RegExp(re, flags); + + return _groups.set(_this, groups || _groups.get(re)), setPrototypeOf(_this, BabelRegExp.prototype); + } + + function buildGroups(result, re) { + var g = _groups.get(re); + + return Object.keys(g).reduce(function (groups, name) { + return groups[name] = result[g[name]], groups; + }, Object.create(null)); + } + + return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) { + var result = _super.exec.call(this, str); + + return result && (result.groups = buildGroups(result, this)), result; + }, BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { + if ("string" == typeof substitution) { + var groups = _groups.get(this); + + return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { + return "$" + groups[name]; + })); + } + + if ("function" == typeof substitution) { + var _this = this; + + return _super[Symbol.replace].call(this, str, function () { + var args = arguments; + return "object" != _typeof(args[args.length - 1]) && (args = [].slice.call(args)).push(buildGroups(args, _this)), substitution.apply(this, args); + }); + } + + return _super[Symbol.replace].call(this, str, substitution); + }, _wrapRegExp.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js b/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js new file mode 100644 index 0000000..9170bd4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js @@ -0,0 +1,3 @@ +export default function _writeOnlyError(name) { + throw new TypeError("\"" + name + "\" is write-only"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/extends.js b/node_modules/@babel/runtime/helpers/extends.js new file mode 100644 index 0000000..e8509df --- /dev/null +++ b/node_modules/@babel/runtime/helpers/extends.js @@ -0,0 +1,18 @@ +function _extends() { + module.exports = _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _extends.apply(this, arguments); +} + +module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/get.js b/node_modules/@babel/runtime/helpers/get.js new file mode 100644 index 0000000..7ddd81b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/get.js @@ -0,0 +1,23 @@ +var superPropBase = require("./superPropBase.js"); + +function _get() { + if (typeof Reflect !== "undefined" && Reflect.get) { + module.exports = _get = Reflect.get, module.exports.__esModule = true, module.exports["default"] = module.exports; + } else { + module.exports = _get = function _get(target, property, receiver) { + var base = superPropBase(target, property); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.get) { + return desc.get.call(arguments.length < 3 ? target : receiver); + } + + return desc.value; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + } + + return _get.apply(this, arguments); +} + +module.exports = _get, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/getPrototypeOf.js b/node_modules/@babel/runtime/helpers/getPrototypeOf.js new file mode 100644 index 0000000..02da563 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/getPrototypeOf.js @@ -0,0 +1,8 @@ +function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _getPrototypeOf(o); +} + +module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/identity.js b/node_modules/@babel/runtime/helpers/identity.js new file mode 100644 index 0000000..3d00062 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/identity.js @@ -0,0 +1,5 @@ +function _identity(x) { + return x; +} + +module.exports = _identity, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/inherits.js b/node_modules/@babel/runtime/helpers/inherits.js new file mode 100644 index 0000000..0b10f28 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/inherits.js @@ -0,0 +1,21 @@ +var setPrototypeOf = require("./setPrototypeOf.js"); + +function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + Object.defineProperty(subClass, "prototype", { + writable: false + }); + if (superClass) setPrototypeOf(subClass, superClass); +} + +module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/inheritsLoose.js b/node_modules/@babel/runtime/helpers/inheritsLoose.js new file mode 100644 index 0000000..df6de46 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/inheritsLoose.js @@ -0,0 +1,9 @@ +var setPrototypeOf = require("./setPrototypeOf.js"); + +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + setPrototypeOf(subClass, superClass); +} + +module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/initializerDefineProperty.js b/node_modules/@babel/runtime/helpers/initializerDefineProperty.js new file mode 100644 index 0000000..5a595a7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/initializerDefineProperty.js @@ -0,0 +1,11 @@ +function _initializerDefineProperty(target, property, descriptor, context) { + if (!descriptor) return; + Object.defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); +} + +module.exports = _initializerDefineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/initializerWarningHelper.js b/node_modules/@babel/runtime/helpers/initializerWarningHelper.js new file mode 100644 index 0000000..001d8a3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/initializerWarningHelper.js @@ -0,0 +1,5 @@ +function _initializerWarningHelper(descriptor, context) { + throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); +} + +module.exports = _initializerWarningHelper, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/instanceof.js b/node_modules/@babel/runtime/helpers/instanceof.js new file mode 100644 index 0000000..08eea81 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/instanceof.js @@ -0,0 +1,9 @@ +function _instanceof(left, right) { + if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { + return !!right[Symbol.hasInstance](left); + } else { + return left instanceof right; + } +} + +module.exports = _instanceof, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/interopRequireDefault.js b/node_modules/@babel/runtime/helpers/interopRequireDefault.js new file mode 100644 index 0000000..5faa0e4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/interopRequireDefault.js @@ -0,0 +1,7 @@ +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; +} + +module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/interopRequireWildcard.js b/node_modules/@babel/runtime/helpers/interopRequireWildcard.js new file mode 100644 index 0000000..0f8ffbf --- /dev/null +++ b/node_modules/@babel/runtime/helpers/interopRequireWildcard.js @@ -0,0 +1,53 @@ +var _typeof = require("./typeof.js")["default"]; + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function _getRequireWildcardCache(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; +} + +module.exports = _interopRequireWildcard, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/isNativeFunction.js b/node_modules/@babel/runtime/helpers/isNativeFunction.js new file mode 100644 index 0000000..5c3d98f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/isNativeFunction.js @@ -0,0 +1,5 @@ +function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} + +module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js b/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js new file mode 100644 index 0000000..f07899d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js @@ -0,0 +1,14 @@ +function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } +} + +module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/iterableToArray.js b/node_modules/@babel/runtime/helpers/iterableToArray.js new file mode 100644 index 0000000..5b9038a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/iterableToArray.js @@ -0,0 +1,5 @@ +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +} + +module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js b/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js new file mode 100644 index 0000000..8d01fb3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js @@ -0,0 +1,31 @@ +function _iterableToArrayLimit(arr, i) { + var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; + + if (_i == null) return; + var _arr = []; + var _n = true; + var _d = false; + + var _s, _e; + + try { + for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; +} + +module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js b/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js new file mode 100644 index 0000000..bca5452 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js @@ -0,0 +1,16 @@ +function _iterableToArrayLimitLoose(arr, i) { + var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); + + if (_i == null) return; + var _arr = []; + + for (_i = _i.call(arr), _step; !(_step = _i.next()).done;) { + _arr.push(_step.value); + + if (i && _arr.length === i) break; + } + + return _arr; +} + +module.exports = _iterableToArrayLimitLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/jsx.js b/node_modules/@babel/runtime/helpers/jsx.js new file mode 100644 index 0000000..bc19ec4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/jsx.js @@ -0,0 +1,29 @@ +var REACT_ELEMENT_TYPE; + +function _createRawReactElement(type, props, key, children) { + REACT_ELEMENT_TYPE || (REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103); + var defaultProps = type && type.defaultProps, + childrenLength = arguments.length - 3; + if (props || 0 === childrenLength || (props = { + children: void 0 + }), 1 === childrenLength) props.children = children;else if (childrenLength > 1) { + for (var childArray = new Array(childrenLength), i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 3]; + } + + props.children = childArray; + } + if (props && defaultProps) for (var propName in defaultProps) { + void 0 === props[propName] && (props[propName] = defaultProps[propName]); + } else props || (props = defaultProps || {}); + return { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: void 0 === key ? null : "" + key, + ref: null, + props: props, + _owner: null + }; +} + +module.exports = _createRawReactElement, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/maybeArrayLike.js b/node_modules/@babel/runtime/helpers/maybeArrayLike.js new file mode 100644 index 0000000..212d68c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/maybeArrayLike.js @@ -0,0 +1,12 @@ +var arrayLikeToArray = require("./arrayLikeToArray.js"); + +function _maybeArrayLike(next, arr, i) { + if (arr && !Array.isArray(arr) && typeof arr.length === "number") { + var len = arr.length; + return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); + } + + return next(arr, i); +} + +module.exports = _maybeArrayLike, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/newArrowCheck.js b/node_modules/@babel/runtime/helpers/newArrowCheck.js new file mode 100644 index 0000000..86a91f2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/newArrowCheck.js @@ -0,0 +1,7 @@ +function _newArrowCheck(innerThis, boundThis) { + if (innerThis !== boundThis) { + throw new TypeError("Cannot instantiate an arrow function"); + } +} + +module.exports = _newArrowCheck, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/nonIterableRest.js b/node_modules/@babel/runtime/helpers/nonIterableRest.js new file mode 100644 index 0000000..e791108 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/nonIterableRest.js @@ -0,0 +1,5 @@ +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/nonIterableSpread.js b/node_modules/@babel/runtime/helpers/nonIterableSpread.js new file mode 100644 index 0000000..64379ea --- /dev/null +++ b/node_modules/@babel/runtime/helpers/nonIterableSpread.js @@ -0,0 +1,5 @@ +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js b/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js new file mode 100644 index 0000000..cb0866e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js @@ -0,0 +1,5 @@ +function _objectDestructuringEmpty(obj) { + if (obj == null) throw new TypeError("Cannot destructure undefined"); +} + +module.exports = _objectDestructuringEmpty, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectSpread.js b/node_modules/@babel/runtime/helpers/objectSpread.js new file mode 100644 index 0000000..cfb4309 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectSpread.js @@ -0,0 +1,22 @@ +var defineProperty = require("./defineProperty.js"); + +function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? Object(arguments[i]) : {}; + var ownKeys = Object.keys(source); + + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function (sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + })); + } + + ownKeys.forEach(function (key) { + defineProperty(target, key, source[key]); + }); + } + + return target; +} + +module.exports = _objectSpread, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectSpread2.js b/node_modules/@babel/runtime/helpers/objectSpread2.js new file mode 100644 index 0000000..7e5db07 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectSpread2.js @@ -0,0 +1,29 @@ +var defineProperty = require("./defineProperty.js"); + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { + defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + + return target; +} + +module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectWithoutProperties.js b/node_modules/@babel/runtime/helpers/objectWithoutProperties.js new file mode 100644 index 0000000..8cf3ab8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectWithoutProperties.js @@ -0,0 +1,22 @@ +var objectWithoutPropertiesLoose = require("./objectWithoutPropertiesLoose.js"); + +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + var target = objectWithoutPropertiesLoose(source, excluded); + var key, i; + + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + + return target; +} + +module.exports = _objectWithoutProperties, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js b/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js new file mode 100644 index 0000000..44d5771 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js @@ -0,0 +1,16 @@ +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; +} + +module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js b/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js new file mode 100644 index 0000000..e1997be --- /dev/null +++ b/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js @@ -0,0 +1,15 @@ +var _typeof = require("./typeof.js")["default"]; + +var assertThisInitialized = require("./assertThisInitialized.js"); + +function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + + return assertThisInitialized(self); +} + +module.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/readOnlyError.js b/node_modules/@babel/runtime/helpers/readOnlyError.js new file mode 100644 index 0000000..93cb90c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/readOnlyError.js @@ -0,0 +1,5 @@ +function _readOnlyError(name) { + throw new TypeError("\"" + name + "\" is read-only"); +} + +module.exports = _readOnlyError, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/set.js b/node_modules/@babel/runtime/helpers/set.js new file mode 100644 index 0000000..6438def --- /dev/null +++ b/node_modules/@babel/runtime/helpers/set.js @@ -0,0 +1,54 @@ +var superPropBase = require("./superPropBase.js"); + +var defineProperty = require("./defineProperty.js"); + +function set(target, property, value, receiver) { + if (typeof Reflect !== "undefined" && Reflect.set) { + set = Reflect.set; + } else { + set = function set(target, property, value, receiver) { + var base = superPropBase(target, property); + var desc; + + if (base) { + desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.set) { + desc.set.call(receiver, value); + return true; + } else if (!desc.writable) { + return false; + } + } + + desc = Object.getOwnPropertyDescriptor(receiver, property); + + if (desc) { + if (!desc.writable) { + return false; + } + + desc.value = value; + Object.defineProperty(receiver, property, desc); + } else { + defineProperty(receiver, property, value); + } + + return true; + }; + } + + return set(target, property, value, receiver); +} + +function _set(target, property, value, receiver, isStrict) { + var s = set(target, property, value, receiver || target); + + if (!s && isStrict) { + throw new Error('failed to set property'); + } + + return value; +} + +module.exports = _set, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/setPrototypeOf.js b/node_modules/@babel/runtime/helpers/setPrototypeOf.js new file mode 100644 index 0000000..7efecad --- /dev/null +++ b/node_modules/@babel/runtime/helpers/setPrototypeOf.js @@ -0,0 +1,9 @@ +function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _setPrototypeOf(o, p); +} + +module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js b/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js new file mode 100644 index 0000000..8890896 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js @@ -0,0 +1,9 @@ +function _skipFirstGeneratorNext(fn) { + return function () { + var it = fn.apply(this, arguments); + it.next(); + return it; + }; +} + +module.exports = _skipFirstGeneratorNext, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/slicedToArray.js b/node_modules/@babel/runtime/helpers/slicedToArray.js new file mode 100644 index 0000000..bce5fc0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/slicedToArray.js @@ -0,0 +1,13 @@ +var arrayWithHoles = require("./arrayWithHoles.js"); + +var iterableToArrayLimit = require("./iterableToArrayLimit.js"); + +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +var nonIterableRest = require("./nonIterableRest.js"); + +function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} + +module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js b/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js new file mode 100644 index 0000000..cc9ace2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js @@ -0,0 +1,13 @@ +var arrayWithHoles = require("./arrayWithHoles.js"); + +var iterableToArrayLimitLoose = require("./iterableToArrayLimitLoose.js"); + +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +var nonIterableRest = require("./nonIterableRest.js"); + +function _slicedToArrayLoose(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} + +module.exports = _slicedToArrayLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/superPropBase.js b/node_modules/@babel/runtime/helpers/superPropBase.js new file mode 100644 index 0000000..dd47fff --- /dev/null +++ b/node_modules/@babel/runtime/helpers/superPropBase.js @@ -0,0 +1,12 @@ +var getPrototypeOf = require("./getPrototypeOf.js"); + +function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = getPrototypeOf(object); + if (object === null) break; + } + + return object; +} + +module.exports = _superPropBase, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js b/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js new file mode 100644 index 0000000..6d9738c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js @@ -0,0 +1,13 @@ +function _taggedTemplateLiteral(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + return Object.freeze(Object.defineProperties(strings, { + raw: { + value: Object.freeze(raw) + } + })); +} + +module.exports = _taggedTemplateLiteral, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js b/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js new file mode 100644 index 0000000..4f151ca --- /dev/null +++ b/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js @@ -0,0 +1,10 @@ +function _taggedTemplateLiteralLoose(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + strings.raw = raw; + return strings; +} + +module.exports = _taggedTemplateLiteralLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/tdz.js b/node_modules/@babel/runtime/helpers/tdz.js new file mode 100644 index 0000000..91ec2b2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/tdz.js @@ -0,0 +1,5 @@ +function _tdzError(name) { + throw new ReferenceError(name + " is not defined - temporal dead zone"); +} + +module.exports = _tdzError, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/temporalRef.js b/node_modules/@babel/runtime/helpers/temporalRef.js new file mode 100644 index 0000000..6afd932 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/temporalRef.js @@ -0,0 +1,9 @@ +var temporalUndefined = require("./temporalUndefined.js"); + +var tdz = require("./tdz.js"); + +function _temporalRef(val, name) { + return val === temporalUndefined ? tdz(name) : val; +} + +module.exports = _temporalRef, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/temporalUndefined.js b/node_modules/@babel/runtime/helpers/temporalUndefined.js new file mode 100644 index 0000000..7aca810 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/temporalUndefined.js @@ -0,0 +1,3 @@ +function _temporalUndefined() {} + +module.exports = _temporalUndefined, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toArray.js b/node_modules/@babel/runtime/helpers/toArray.js new file mode 100644 index 0000000..d0af0e9 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toArray.js @@ -0,0 +1,13 @@ +var arrayWithHoles = require("./arrayWithHoles.js"); + +var iterableToArray = require("./iterableToArray.js"); + +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +var nonIterableRest = require("./nonIterableRest.js"); + +function _toArray(arr) { + return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest(); +} + +module.exports = _toArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toConsumableArray.js b/node_modules/@babel/runtime/helpers/toConsumableArray.js new file mode 100644 index 0000000..9c69072 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toConsumableArray.js @@ -0,0 +1,13 @@ +var arrayWithoutHoles = require("./arrayWithoutHoles.js"); + +var iterableToArray = require("./iterableToArray.js"); + +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +var nonIterableSpread = require("./nonIterableSpread.js"); + +function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); +} + +module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toPrimitive.js b/node_modules/@babel/runtime/helpers/toPrimitive.js new file mode 100644 index 0000000..dc4da81 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toPrimitive.js @@ -0,0 +1,16 @@ +var _typeof = require("./typeof.js")["default"]; + +function _toPrimitive(input, hint) { + if (_typeof(input) !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (_typeof(res) !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + + return (hint === "string" ? String : Number)(input); +} + +module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toPropertyKey.js b/node_modules/@babel/runtime/helpers/toPropertyKey.js new file mode 100644 index 0000000..61367cf --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toPropertyKey.js @@ -0,0 +1,10 @@ +var _typeof = require("./typeof.js")["default"]; + +var toPrimitive = require("./toPrimitive.js"); + +function _toPropertyKey(arg) { + var key = toPrimitive(arg, "string"); + return _typeof(key) === "symbol" ? key : String(key); +} + +module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/typeof.js b/node_modules/@babel/runtime/helpers/typeof.js new file mode 100644 index 0000000..6c7860f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/typeof.js @@ -0,0 +1,11 @@ +function _typeof(obj) { + "@babel/helpers - typeof"; + + return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj); +} + +module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js b/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js new file mode 100644 index 0000000..bfe65e4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js @@ -0,0 +1,12 @@ +var arrayLikeToArray = require("./arrayLikeToArray.js"); + +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); +} + +module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js b/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js new file mode 100644 index 0000000..1fb4fd7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js @@ -0,0 +1,9 @@ +var AsyncGenerator = require("./AsyncGenerator.js"); + +function _wrapAsyncGenerator(fn) { + return function () { + return new AsyncGenerator(fn.apply(this, arguments)); + }; +} + +module.exports = _wrapAsyncGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/wrapNativeSuper.js b/node_modules/@babel/runtime/helpers/wrapNativeSuper.js new file mode 100644 index 0000000..516220b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/wrapNativeSuper.js @@ -0,0 +1,42 @@ +var getPrototypeOf = require("./getPrototypeOf.js"); + +var setPrototypeOf = require("./setPrototypeOf.js"); + +var isNativeFunction = require("./isNativeFunction.js"); + +var construct = require("./construct.js"); + +function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); + } + + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); + } + + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return setPrototypeOf(Wrapper, Class); + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _wrapNativeSuper(Class); +} + +module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/wrapRegExp.js b/node_modules/@babel/runtime/helpers/wrapRegExp.js new file mode 100644 index 0000000..5b8342b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/wrapRegExp.js @@ -0,0 +1,55 @@ +var _typeof = require("./typeof.js")["default"]; + +var setPrototypeOf = require("./setPrototypeOf.js"); + +var inherits = require("./inherits.js"); + +function _wrapRegExp() { + module.exports = _wrapRegExp = function _wrapRegExp(re, groups) { + return new BabelRegExp(re, void 0, groups); + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + + var _super = RegExp.prototype, + _groups = new WeakMap(); + + function BabelRegExp(re, flags, groups) { + var _this = new RegExp(re, flags); + + return _groups.set(_this, groups || _groups.get(re)), setPrototypeOf(_this, BabelRegExp.prototype); + } + + function buildGroups(result, re) { + var g = _groups.get(re); + + return Object.keys(g).reduce(function (groups, name) { + return groups[name] = result[g[name]], groups; + }, Object.create(null)); + } + + return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) { + var result = _super.exec.call(this, str); + + return result && (result.groups = buildGroups(result, this)), result; + }, BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { + if ("string" == typeof substitution) { + var groups = _groups.get(this); + + return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { + return "$" + groups[name]; + })); + } + + if ("function" == typeof substitution) { + var _this = this; + + return _super[Symbol.replace].call(this, str, function () { + var args = arguments; + return "object" != _typeof(args[args.length - 1]) && (args = [].slice.call(args)).push(buildGroups(args, _this)), substitution.apply(this, args); + }); + } + + return _super[Symbol.replace].call(this, str, substitution); + }, _wrapRegExp.apply(this, arguments); +} + +module.exports = _wrapRegExp, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/writeOnlyError.js b/node_modules/@babel/runtime/helpers/writeOnlyError.js new file mode 100644 index 0000000..1329487 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/writeOnlyError.js @@ -0,0 +1,5 @@ +function _writeOnlyError(name) { + throw new TypeError("\"" + name + "\" is write-only"); +} + +module.exports = _writeOnlyError, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/package.json b/node_modules/@babel/runtime/package.json new file mode 100644 index 0000000..2a394c0 --- /dev/null +++ b/node_modules/@babel/runtime/package.json @@ -0,0 +1,866 @@ +{ + "name": "@babel/runtime", + "version": "7.17.9", + "description": "babel's modular runtime helpers", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-runtime" + }, + "homepage": "https://babel.dev/docs/en/next/babel-runtime", + "author": "The Babel Team (https://babel.dev/team)", + "dependencies": { + "regenerator-runtime": "^0.13.4" + }, + "exports": { + "./helpers/applyDecs": [ + { + "node": "./helpers/applyDecs.js", + "import": "./helpers/esm/applyDecs.js", + "default": "./helpers/applyDecs.js" + }, + "./helpers/applyDecs.js" + ], + "./helpers/esm/applyDecs": "./helpers/esm/applyDecs.js", + "./helpers/asyncIterator": [ + { + "node": "./helpers/asyncIterator.js", + "import": "./helpers/esm/asyncIterator.js", + "default": "./helpers/asyncIterator.js" + }, + "./helpers/asyncIterator.js" + ], + "./helpers/esm/asyncIterator": "./helpers/esm/asyncIterator.js", + "./helpers/jsx": [ + { + "node": "./helpers/jsx.js", + "import": "./helpers/esm/jsx.js", + "default": "./helpers/jsx.js" + }, + "./helpers/jsx.js" + ], + "./helpers/esm/jsx": "./helpers/esm/jsx.js", + "./helpers/objectSpread2": [ + { + "node": "./helpers/objectSpread2.js", + "import": "./helpers/esm/objectSpread2.js", + "default": "./helpers/objectSpread2.js" + }, + "./helpers/objectSpread2.js" + ], + "./helpers/esm/objectSpread2": "./helpers/esm/objectSpread2.js", + "./helpers/typeof": [ + { + "node": "./helpers/typeof.js", + "import": "./helpers/esm/typeof.js", + "default": "./helpers/typeof.js" + }, + "./helpers/typeof.js" + ], + "./helpers/esm/typeof": "./helpers/esm/typeof.js", + "./helpers/wrapRegExp": [ + { + "node": "./helpers/wrapRegExp.js", + "import": "./helpers/esm/wrapRegExp.js", + "default": "./helpers/wrapRegExp.js" + }, + "./helpers/wrapRegExp.js" + ], + "./helpers/esm/wrapRegExp": "./helpers/esm/wrapRegExp.js", + "./helpers/AwaitValue": [ + { + "node": "./helpers/AwaitValue.js", + "import": "./helpers/esm/AwaitValue.js", + "default": "./helpers/AwaitValue.js" + }, + "./helpers/AwaitValue.js" + ], + "./helpers/esm/AwaitValue": "./helpers/esm/AwaitValue.js", + "./helpers/AsyncGenerator": [ + { + "node": "./helpers/AsyncGenerator.js", + "import": "./helpers/esm/AsyncGenerator.js", + "default": "./helpers/AsyncGenerator.js" + }, + "./helpers/AsyncGenerator.js" + ], + "./helpers/esm/AsyncGenerator": "./helpers/esm/AsyncGenerator.js", + "./helpers/wrapAsyncGenerator": [ + { + "node": "./helpers/wrapAsyncGenerator.js", + "import": "./helpers/esm/wrapAsyncGenerator.js", + "default": "./helpers/wrapAsyncGenerator.js" + }, + "./helpers/wrapAsyncGenerator.js" + ], + "./helpers/esm/wrapAsyncGenerator": "./helpers/esm/wrapAsyncGenerator.js", + "./helpers/awaitAsyncGenerator": [ + { + "node": "./helpers/awaitAsyncGenerator.js", + "import": "./helpers/esm/awaitAsyncGenerator.js", + "default": "./helpers/awaitAsyncGenerator.js" + }, + "./helpers/awaitAsyncGenerator.js" + ], + "./helpers/esm/awaitAsyncGenerator": "./helpers/esm/awaitAsyncGenerator.js", + "./helpers/asyncGeneratorDelegate": [ + { + "node": "./helpers/asyncGeneratorDelegate.js", + "import": "./helpers/esm/asyncGeneratorDelegate.js", + "default": "./helpers/asyncGeneratorDelegate.js" + }, + "./helpers/asyncGeneratorDelegate.js" + ], + "./helpers/esm/asyncGeneratorDelegate": "./helpers/esm/asyncGeneratorDelegate.js", + "./helpers/asyncToGenerator": [ + { + "node": "./helpers/asyncToGenerator.js", + "import": "./helpers/esm/asyncToGenerator.js", + "default": "./helpers/asyncToGenerator.js" + }, + "./helpers/asyncToGenerator.js" + ], + "./helpers/esm/asyncToGenerator": "./helpers/esm/asyncToGenerator.js", + "./helpers/classCallCheck": [ + { + "node": "./helpers/classCallCheck.js", + "import": "./helpers/esm/classCallCheck.js", + "default": "./helpers/classCallCheck.js" + }, + "./helpers/classCallCheck.js" + ], + "./helpers/esm/classCallCheck": "./helpers/esm/classCallCheck.js", + "./helpers/createClass": [ + { + "node": "./helpers/createClass.js", + "import": "./helpers/esm/createClass.js", + "default": "./helpers/createClass.js" + }, + "./helpers/createClass.js" + ], + "./helpers/esm/createClass": "./helpers/esm/createClass.js", + "./helpers/defineEnumerableProperties": [ + { + "node": "./helpers/defineEnumerableProperties.js", + "import": "./helpers/esm/defineEnumerableProperties.js", + "default": "./helpers/defineEnumerableProperties.js" + }, + "./helpers/defineEnumerableProperties.js" + ], + "./helpers/esm/defineEnumerableProperties": "./helpers/esm/defineEnumerableProperties.js", + "./helpers/defaults": [ + { + "node": "./helpers/defaults.js", + "import": "./helpers/esm/defaults.js", + "default": "./helpers/defaults.js" + }, + "./helpers/defaults.js" + ], + "./helpers/esm/defaults": "./helpers/esm/defaults.js", + "./helpers/defineProperty": [ + { + "node": "./helpers/defineProperty.js", + "import": "./helpers/esm/defineProperty.js", + "default": "./helpers/defineProperty.js" + }, + "./helpers/defineProperty.js" + ], + "./helpers/esm/defineProperty": "./helpers/esm/defineProperty.js", + "./helpers/extends": [ + { + "node": "./helpers/extends.js", + "import": "./helpers/esm/extends.js", + "default": "./helpers/extends.js" + }, + "./helpers/extends.js" + ], + "./helpers/esm/extends": "./helpers/esm/extends.js", + "./helpers/objectSpread": [ + { + "node": "./helpers/objectSpread.js", + "import": "./helpers/esm/objectSpread.js", + "default": "./helpers/objectSpread.js" + }, + "./helpers/objectSpread.js" + ], + "./helpers/esm/objectSpread": "./helpers/esm/objectSpread.js", + "./helpers/inherits": [ + { + "node": "./helpers/inherits.js", + "import": "./helpers/esm/inherits.js", + "default": "./helpers/inherits.js" + }, + "./helpers/inherits.js" + ], + "./helpers/esm/inherits": "./helpers/esm/inherits.js", + "./helpers/inheritsLoose": [ + { + "node": "./helpers/inheritsLoose.js", + "import": "./helpers/esm/inheritsLoose.js", + "default": "./helpers/inheritsLoose.js" + }, + "./helpers/inheritsLoose.js" + ], + "./helpers/esm/inheritsLoose": "./helpers/esm/inheritsLoose.js", + "./helpers/getPrototypeOf": [ + { + "node": "./helpers/getPrototypeOf.js", + "import": "./helpers/esm/getPrototypeOf.js", + "default": "./helpers/getPrototypeOf.js" + }, + "./helpers/getPrototypeOf.js" + ], + "./helpers/esm/getPrototypeOf": "./helpers/esm/getPrototypeOf.js", + "./helpers/setPrototypeOf": [ + { + "node": "./helpers/setPrototypeOf.js", + "import": "./helpers/esm/setPrototypeOf.js", + "default": "./helpers/setPrototypeOf.js" + }, + "./helpers/setPrototypeOf.js" + ], + "./helpers/esm/setPrototypeOf": "./helpers/esm/setPrototypeOf.js", + "./helpers/isNativeReflectConstruct": [ + { + "node": "./helpers/isNativeReflectConstruct.js", + "import": "./helpers/esm/isNativeReflectConstruct.js", + "default": "./helpers/isNativeReflectConstruct.js" + }, + "./helpers/isNativeReflectConstruct.js" + ], + "./helpers/esm/isNativeReflectConstruct": "./helpers/esm/isNativeReflectConstruct.js", + "./helpers/construct": [ + { + "node": "./helpers/construct.js", + "import": "./helpers/esm/construct.js", + "default": "./helpers/construct.js" + }, + "./helpers/construct.js" + ], + "./helpers/esm/construct": "./helpers/esm/construct.js", + "./helpers/isNativeFunction": [ + { + "node": "./helpers/isNativeFunction.js", + "import": "./helpers/esm/isNativeFunction.js", + "default": "./helpers/isNativeFunction.js" + }, + "./helpers/isNativeFunction.js" + ], + "./helpers/esm/isNativeFunction": "./helpers/esm/isNativeFunction.js", + "./helpers/wrapNativeSuper": [ + { + "node": "./helpers/wrapNativeSuper.js", + "import": "./helpers/esm/wrapNativeSuper.js", + "default": "./helpers/wrapNativeSuper.js" + }, + "./helpers/wrapNativeSuper.js" + ], + "./helpers/esm/wrapNativeSuper": "./helpers/esm/wrapNativeSuper.js", + "./helpers/instanceof": [ + { + "node": "./helpers/instanceof.js", + "import": "./helpers/esm/instanceof.js", + "default": "./helpers/instanceof.js" + }, + "./helpers/instanceof.js" + ], + "./helpers/esm/instanceof": "./helpers/esm/instanceof.js", + "./helpers/interopRequireDefault": [ + { + "node": "./helpers/interopRequireDefault.js", + "import": "./helpers/esm/interopRequireDefault.js", + "default": "./helpers/interopRequireDefault.js" + }, + "./helpers/interopRequireDefault.js" + ], + "./helpers/esm/interopRequireDefault": "./helpers/esm/interopRequireDefault.js", + "./helpers/interopRequireWildcard": [ + { + "node": "./helpers/interopRequireWildcard.js", + "import": "./helpers/esm/interopRequireWildcard.js", + "default": "./helpers/interopRequireWildcard.js" + }, + "./helpers/interopRequireWildcard.js" + ], + "./helpers/esm/interopRequireWildcard": "./helpers/esm/interopRequireWildcard.js", + "./helpers/newArrowCheck": [ + { + "node": "./helpers/newArrowCheck.js", + "import": "./helpers/esm/newArrowCheck.js", + "default": "./helpers/newArrowCheck.js" + }, + "./helpers/newArrowCheck.js" + ], + "./helpers/esm/newArrowCheck": "./helpers/esm/newArrowCheck.js", + "./helpers/objectDestructuringEmpty": [ + { + "node": "./helpers/objectDestructuringEmpty.js", + "import": "./helpers/esm/objectDestructuringEmpty.js", + "default": "./helpers/objectDestructuringEmpty.js" + }, + "./helpers/objectDestructuringEmpty.js" + ], + "./helpers/esm/objectDestructuringEmpty": "./helpers/esm/objectDestructuringEmpty.js", + "./helpers/objectWithoutPropertiesLoose": [ + { + "node": "./helpers/objectWithoutPropertiesLoose.js", + "import": "./helpers/esm/objectWithoutPropertiesLoose.js", + "default": "./helpers/objectWithoutPropertiesLoose.js" + }, + "./helpers/objectWithoutPropertiesLoose.js" + ], + "./helpers/esm/objectWithoutPropertiesLoose": "./helpers/esm/objectWithoutPropertiesLoose.js", + "./helpers/objectWithoutProperties": [ + { + "node": "./helpers/objectWithoutProperties.js", + "import": "./helpers/esm/objectWithoutProperties.js", + "default": "./helpers/objectWithoutProperties.js" + }, + "./helpers/objectWithoutProperties.js" + ], + "./helpers/esm/objectWithoutProperties": "./helpers/esm/objectWithoutProperties.js", + "./helpers/assertThisInitialized": [ + { + "node": "./helpers/assertThisInitialized.js", + "import": "./helpers/esm/assertThisInitialized.js", + "default": "./helpers/assertThisInitialized.js" + }, + "./helpers/assertThisInitialized.js" + ], + "./helpers/esm/assertThisInitialized": "./helpers/esm/assertThisInitialized.js", + "./helpers/possibleConstructorReturn": [ + { + "node": "./helpers/possibleConstructorReturn.js", + "import": "./helpers/esm/possibleConstructorReturn.js", + "default": "./helpers/possibleConstructorReturn.js" + }, + "./helpers/possibleConstructorReturn.js" + ], + "./helpers/esm/possibleConstructorReturn": "./helpers/esm/possibleConstructorReturn.js", + "./helpers/createSuper": [ + { + "node": "./helpers/createSuper.js", + "import": "./helpers/esm/createSuper.js", + "default": "./helpers/createSuper.js" + }, + "./helpers/createSuper.js" + ], + "./helpers/esm/createSuper": "./helpers/esm/createSuper.js", + "./helpers/superPropBase": [ + { + "node": "./helpers/superPropBase.js", + "import": "./helpers/esm/superPropBase.js", + "default": "./helpers/superPropBase.js" + }, + "./helpers/superPropBase.js" + ], + "./helpers/esm/superPropBase": "./helpers/esm/superPropBase.js", + "./helpers/get": [ + { + "node": "./helpers/get.js", + "import": "./helpers/esm/get.js", + "default": "./helpers/get.js" + }, + "./helpers/get.js" + ], + "./helpers/esm/get": "./helpers/esm/get.js", + "./helpers/set": [ + { + "node": "./helpers/set.js", + "import": "./helpers/esm/set.js", + "default": "./helpers/set.js" + }, + "./helpers/set.js" + ], + "./helpers/esm/set": "./helpers/esm/set.js", + "./helpers/taggedTemplateLiteral": [ + { + "node": "./helpers/taggedTemplateLiteral.js", + "import": "./helpers/esm/taggedTemplateLiteral.js", + "default": "./helpers/taggedTemplateLiteral.js" + }, + "./helpers/taggedTemplateLiteral.js" + ], + "./helpers/esm/taggedTemplateLiteral": "./helpers/esm/taggedTemplateLiteral.js", + "./helpers/taggedTemplateLiteralLoose": [ + { + "node": "./helpers/taggedTemplateLiteralLoose.js", + "import": "./helpers/esm/taggedTemplateLiteralLoose.js", + "default": "./helpers/taggedTemplateLiteralLoose.js" + }, + "./helpers/taggedTemplateLiteralLoose.js" + ], + "./helpers/esm/taggedTemplateLiteralLoose": "./helpers/esm/taggedTemplateLiteralLoose.js", + "./helpers/readOnlyError": [ + { + "node": "./helpers/readOnlyError.js", + "import": "./helpers/esm/readOnlyError.js", + "default": "./helpers/readOnlyError.js" + }, + "./helpers/readOnlyError.js" + ], + "./helpers/esm/readOnlyError": "./helpers/esm/readOnlyError.js", + "./helpers/writeOnlyError": [ + { + "node": "./helpers/writeOnlyError.js", + "import": "./helpers/esm/writeOnlyError.js", + "default": "./helpers/writeOnlyError.js" + }, + "./helpers/writeOnlyError.js" + ], + "./helpers/esm/writeOnlyError": "./helpers/esm/writeOnlyError.js", + "./helpers/classNameTDZError": [ + { + "node": "./helpers/classNameTDZError.js", + "import": "./helpers/esm/classNameTDZError.js", + "default": "./helpers/classNameTDZError.js" + }, + "./helpers/classNameTDZError.js" + ], + "./helpers/esm/classNameTDZError": "./helpers/esm/classNameTDZError.js", + "./helpers/temporalUndefined": [ + { + "node": "./helpers/temporalUndefined.js", + "import": "./helpers/esm/temporalUndefined.js", + "default": "./helpers/temporalUndefined.js" + }, + "./helpers/temporalUndefined.js" + ], + "./helpers/esm/temporalUndefined": "./helpers/esm/temporalUndefined.js", + "./helpers/tdz": [ + { + "node": "./helpers/tdz.js", + "import": "./helpers/esm/tdz.js", + "default": "./helpers/tdz.js" + }, + "./helpers/tdz.js" + ], + "./helpers/esm/tdz": "./helpers/esm/tdz.js", + "./helpers/temporalRef": [ + { + "node": "./helpers/temporalRef.js", + "import": "./helpers/esm/temporalRef.js", + "default": "./helpers/temporalRef.js" + }, + "./helpers/temporalRef.js" + ], + "./helpers/esm/temporalRef": "./helpers/esm/temporalRef.js", + "./helpers/slicedToArray": [ + { + "node": "./helpers/slicedToArray.js", + "import": "./helpers/esm/slicedToArray.js", + "default": "./helpers/slicedToArray.js" + }, + "./helpers/slicedToArray.js" + ], + "./helpers/esm/slicedToArray": "./helpers/esm/slicedToArray.js", + "./helpers/slicedToArrayLoose": [ + { + "node": "./helpers/slicedToArrayLoose.js", + "import": "./helpers/esm/slicedToArrayLoose.js", + "default": "./helpers/slicedToArrayLoose.js" + }, + "./helpers/slicedToArrayLoose.js" + ], + "./helpers/esm/slicedToArrayLoose": "./helpers/esm/slicedToArrayLoose.js", + "./helpers/toArray": [ + { + "node": "./helpers/toArray.js", + "import": "./helpers/esm/toArray.js", + "default": "./helpers/toArray.js" + }, + "./helpers/toArray.js" + ], + "./helpers/esm/toArray": "./helpers/esm/toArray.js", + "./helpers/toConsumableArray": [ + { + "node": "./helpers/toConsumableArray.js", + "import": "./helpers/esm/toConsumableArray.js", + "default": "./helpers/toConsumableArray.js" + }, + "./helpers/toConsumableArray.js" + ], + "./helpers/esm/toConsumableArray": "./helpers/esm/toConsumableArray.js", + "./helpers/arrayWithoutHoles": [ + { + "node": "./helpers/arrayWithoutHoles.js", + "import": "./helpers/esm/arrayWithoutHoles.js", + "default": "./helpers/arrayWithoutHoles.js" + }, + "./helpers/arrayWithoutHoles.js" + ], + "./helpers/esm/arrayWithoutHoles": "./helpers/esm/arrayWithoutHoles.js", + "./helpers/arrayWithHoles": [ + { + "node": "./helpers/arrayWithHoles.js", + "import": "./helpers/esm/arrayWithHoles.js", + "default": "./helpers/arrayWithHoles.js" + }, + "./helpers/arrayWithHoles.js" + ], + "./helpers/esm/arrayWithHoles": "./helpers/esm/arrayWithHoles.js", + "./helpers/maybeArrayLike": [ + { + "node": "./helpers/maybeArrayLike.js", + "import": "./helpers/esm/maybeArrayLike.js", + "default": "./helpers/maybeArrayLike.js" + }, + "./helpers/maybeArrayLike.js" + ], + "./helpers/esm/maybeArrayLike": "./helpers/esm/maybeArrayLike.js", + "./helpers/iterableToArray": [ + { + "node": "./helpers/iterableToArray.js", + "import": "./helpers/esm/iterableToArray.js", + "default": "./helpers/iterableToArray.js" + }, + "./helpers/iterableToArray.js" + ], + "./helpers/esm/iterableToArray": "./helpers/esm/iterableToArray.js", + "./helpers/iterableToArrayLimit": [ + { + "node": "./helpers/iterableToArrayLimit.js", + "import": "./helpers/esm/iterableToArrayLimit.js", + "default": "./helpers/iterableToArrayLimit.js" + }, + "./helpers/iterableToArrayLimit.js" + ], + "./helpers/esm/iterableToArrayLimit": "./helpers/esm/iterableToArrayLimit.js", + "./helpers/iterableToArrayLimitLoose": [ + { + "node": "./helpers/iterableToArrayLimitLoose.js", + "import": "./helpers/esm/iterableToArrayLimitLoose.js", + "default": "./helpers/iterableToArrayLimitLoose.js" + }, + "./helpers/iterableToArrayLimitLoose.js" + ], + "./helpers/esm/iterableToArrayLimitLoose": "./helpers/esm/iterableToArrayLimitLoose.js", + "./helpers/unsupportedIterableToArray": [ + { + "node": "./helpers/unsupportedIterableToArray.js", + "import": "./helpers/esm/unsupportedIterableToArray.js", + "default": "./helpers/unsupportedIterableToArray.js" + }, + "./helpers/unsupportedIterableToArray.js" + ], + "./helpers/esm/unsupportedIterableToArray": "./helpers/esm/unsupportedIterableToArray.js", + "./helpers/arrayLikeToArray": [ + { + "node": "./helpers/arrayLikeToArray.js", + "import": "./helpers/esm/arrayLikeToArray.js", + "default": "./helpers/arrayLikeToArray.js" + }, + "./helpers/arrayLikeToArray.js" + ], + "./helpers/esm/arrayLikeToArray": "./helpers/esm/arrayLikeToArray.js", + "./helpers/nonIterableSpread": [ + { + "node": "./helpers/nonIterableSpread.js", + "import": "./helpers/esm/nonIterableSpread.js", + "default": "./helpers/nonIterableSpread.js" + }, + "./helpers/nonIterableSpread.js" + ], + "./helpers/esm/nonIterableSpread": "./helpers/esm/nonIterableSpread.js", + "./helpers/nonIterableRest": [ + { + "node": "./helpers/nonIterableRest.js", + "import": "./helpers/esm/nonIterableRest.js", + "default": "./helpers/nonIterableRest.js" + }, + "./helpers/nonIterableRest.js" + ], + "./helpers/esm/nonIterableRest": "./helpers/esm/nonIterableRest.js", + "./helpers/createForOfIteratorHelper": [ + { + "node": "./helpers/createForOfIteratorHelper.js", + "import": "./helpers/esm/createForOfIteratorHelper.js", + "default": "./helpers/createForOfIteratorHelper.js" + }, + "./helpers/createForOfIteratorHelper.js" + ], + "./helpers/esm/createForOfIteratorHelper": "./helpers/esm/createForOfIteratorHelper.js", + "./helpers/createForOfIteratorHelperLoose": [ + { + "node": "./helpers/createForOfIteratorHelperLoose.js", + "import": "./helpers/esm/createForOfIteratorHelperLoose.js", + "default": "./helpers/createForOfIteratorHelperLoose.js" + }, + "./helpers/createForOfIteratorHelperLoose.js" + ], + "./helpers/esm/createForOfIteratorHelperLoose": "./helpers/esm/createForOfIteratorHelperLoose.js", + "./helpers/skipFirstGeneratorNext": [ + { + "node": "./helpers/skipFirstGeneratorNext.js", + "import": "./helpers/esm/skipFirstGeneratorNext.js", + "default": "./helpers/skipFirstGeneratorNext.js" + }, + "./helpers/skipFirstGeneratorNext.js" + ], + "./helpers/esm/skipFirstGeneratorNext": "./helpers/esm/skipFirstGeneratorNext.js", + "./helpers/toPrimitive": [ + { + "node": "./helpers/toPrimitive.js", + "import": "./helpers/esm/toPrimitive.js", + "default": "./helpers/toPrimitive.js" + }, + "./helpers/toPrimitive.js" + ], + "./helpers/esm/toPrimitive": "./helpers/esm/toPrimitive.js", + "./helpers/toPropertyKey": [ + { + "node": "./helpers/toPropertyKey.js", + "import": "./helpers/esm/toPropertyKey.js", + "default": "./helpers/toPropertyKey.js" + }, + "./helpers/toPropertyKey.js" + ], + "./helpers/esm/toPropertyKey": "./helpers/esm/toPropertyKey.js", + "./helpers/initializerWarningHelper": [ + { + "node": "./helpers/initializerWarningHelper.js", + "import": "./helpers/esm/initializerWarningHelper.js", + "default": "./helpers/initializerWarningHelper.js" + }, + "./helpers/initializerWarningHelper.js" + ], + "./helpers/esm/initializerWarningHelper": "./helpers/esm/initializerWarningHelper.js", + "./helpers/initializerDefineProperty": [ + { + "node": "./helpers/initializerDefineProperty.js", + "import": "./helpers/esm/initializerDefineProperty.js", + "default": "./helpers/initializerDefineProperty.js" + }, + "./helpers/initializerDefineProperty.js" + ], + "./helpers/esm/initializerDefineProperty": "./helpers/esm/initializerDefineProperty.js", + "./helpers/applyDecoratedDescriptor": [ + { + "node": "./helpers/applyDecoratedDescriptor.js", + "import": "./helpers/esm/applyDecoratedDescriptor.js", + "default": "./helpers/applyDecoratedDescriptor.js" + }, + "./helpers/applyDecoratedDescriptor.js" + ], + "./helpers/esm/applyDecoratedDescriptor": "./helpers/esm/applyDecoratedDescriptor.js", + "./helpers/classPrivateFieldLooseKey": [ + { + "node": "./helpers/classPrivateFieldLooseKey.js", + "import": "./helpers/esm/classPrivateFieldLooseKey.js", + "default": "./helpers/classPrivateFieldLooseKey.js" + }, + "./helpers/classPrivateFieldLooseKey.js" + ], + "./helpers/esm/classPrivateFieldLooseKey": "./helpers/esm/classPrivateFieldLooseKey.js", + "./helpers/classPrivateFieldLooseBase": [ + { + "node": "./helpers/classPrivateFieldLooseBase.js", + "import": "./helpers/esm/classPrivateFieldLooseBase.js", + "default": "./helpers/classPrivateFieldLooseBase.js" + }, + "./helpers/classPrivateFieldLooseBase.js" + ], + "./helpers/esm/classPrivateFieldLooseBase": "./helpers/esm/classPrivateFieldLooseBase.js", + "./helpers/classPrivateFieldGet": [ + { + "node": "./helpers/classPrivateFieldGet.js", + "import": "./helpers/esm/classPrivateFieldGet.js", + "default": "./helpers/classPrivateFieldGet.js" + }, + "./helpers/classPrivateFieldGet.js" + ], + "./helpers/esm/classPrivateFieldGet": "./helpers/esm/classPrivateFieldGet.js", + "./helpers/classPrivateFieldSet": [ + { + "node": "./helpers/classPrivateFieldSet.js", + "import": "./helpers/esm/classPrivateFieldSet.js", + "default": "./helpers/classPrivateFieldSet.js" + }, + "./helpers/classPrivateFieldSet.js" + ], + "./helpers/esm/classPrivateFieldSet": "./helpers/esm/classPrivateFieldSet.js", + "./helpers/classPrivateFieldDestructureSet": [ + { + "node": "./helpers/classPrivateFieldDestructureSet.js", + "import": "./helpers/esm/classPrivateFieldDestructureSet.js", + "default": "./helpers/classPrivateFieldDestructureSet.js" + }, + "./helpers/classPrivateFieldDestructureSet.js" + ], + "./helpers/esm/classPrivateFieldDestructureSet": "./helpers/esm/classPrivateFieldDestructureSet.js", + "./helpers/classExtractFieldDescriptor": [ + { + "node": "./helpers/classExtractFieldDescriptor.js", + "import": "./helpers/esm/classExtractFieldDescriptor.js", + "default": "./helpers/classExtractFieldDescriptor.js" + }, + "./helpers/classExtractFieldDescriptor.js" + ], + "./helpers/esm/classExtractFieldDescriptor": "./helpers/esm/classExtractFieldDescriptor.js", + "./helpers/classStaticPrivateFieldSpecGet": [ + { + "node": "./helpers/classStaticPrivateFieldSpecGet.js", + "import": "./helpers/esm/classStaticPrivateFieldSpecGet.js", + "default": "./helpers/classStaticPrivateFieldSpecGet.js" + }, + "./helpers/classStaticPrivateFieldSpecGet.js" + ], + "./helpers/esm/classStaticPrivateFieldSpecGet": "./helpers/esm/classStaticPrivateFieldSpecGet.js", + "./helpers/classStaticPrivateFieldSpecSet": [ + { + "node": "./helpers/classStaticPrivateFieldSpecSet.js", + "import": "./helpers/esm/classStaticPrivateFieldSpecSet.js", + "default": "./helpers/classStaticPrivateFieldSpecSet.js" + }, + "./helpers/classStaticPrivateFieldSpecSet.js" + ], + "./helpers/esm/classStaticPrivateFieldSpecSet": "./helpers/esm/classStaticPrivateFieldSpecSet.js", + "./helpers/classStaticPrivateMethodGet": [ + { + "node": "./helpers/classStaticPrivateMethodGet.js", + "import": "./helpers/esm/classStaticPrivateMethodGet.js", + "default": "./helpers/classStaticPrivateMethodGet.js" + }, + "./helpers/classStaticPrivateMethodGet.js" + ], + "./helpers/esm/classStaticPrivateMethodGet": "./helpers/esm/classStaticPrivateMethodGet.js", + "./helpers/classStaticPrivateMethodSet": [ + { + "node": "./helpers/classStaticPrivateMethodSet.js", + "import": "./helpers/esm/classStaticPrivateMethodSet.js", + "default": "./helpers/classStaticPrivateMethodSet.js" + }, + "./helpers/classStaticPrivateMethodSet.js" + ], + "./helpers/esm/classStaticPrivateMethodSet": "./helpers/esm/classStaticPrivateMethodSet.js", + "./helpers/classApplyDescriptorGet": [ + { + "node": "./helpers/classApplyDescriptorGet.js", + "import": "./helpers/esm/classApplyDescriptorGet.js", + "default": "./helpers/classApplyDescriptorGet.js" + }, + "./helpers/classApplyDescriptorGet.js" + ], + "./helpers/esm/classApplyDescriptorGet": "./helpers/esm/classApplyDescriptorGet.js", + "./helpers/classApplyDescriptorSet": [ + { + "node": "./helpers/classApplyDescriptorSet.js", + "import": "./helpers/esm/classApplyDescriptorSet.js", + "default": "./helpers/classApplyDescriptorSet.js" + }, + "./helpers/classApplyDescriptorSet.js" + ], + "./helpers/esm/classApplyDescriptorSet": "./helpers/esm/classApplyDescriptorSet.js", + "./helpers/classApplyDescriptorDestructureSet": [ + { + "node": "./helpers/classApplyDescriptorDestructureSet.js", + "import": "./helpers/esm/classApplyDescriptorDestructureSet.js", + "default": "./helpers/classApplyDescriptorDestructureSet.js" + }, + "./helpers/classApplyDescriptorDestructureSet.js" + ], + "./helpers/esm/classApplyDescriptorDestructureSet": "./helpers/esm/classApplyDescriptorDestructureSet.js", + "./helpers/classStaticPrivateFieldDestructureSet": [ + { + "node": "./helpers/classStaticPrivateFieldDestructureSet.js", + "import": "./helpers/esm/classStaticPrivateFieldDestructureSet.js", + "default": "./helpers/classStaticPrivateFieldDestructureSet.js" + }, + "./helpers/classStaticPrivateFieldDestructureSet.js" + ], + "./helpers/esm/classStaticPrivateFieldDestructureSet": "./helpers/esm/classStaticPrivateFieldDestructureSet.js", + "./helpers/classCheckPrivateStaticAccess": [ + { + "node": "./helpers/classCheckPrivateStaticAccess.js", + "import": "./helpers/esm/classCheckPrivateStaticAccess.js", + "default": "./helpers/classCheckPrivateStaticAccess.js" + }, + "./helpers/classCheckPrivateStaticAccess.js" + ], + "./helpers/esm/classCheckPrivateStaticAccess": "./helpers/esm/classCheckPrivateStaticAccess.js", + "./helpers/classCheckPrivateStaticFieldDescriptor": [ + { + "node": "./helpers/classCheckPrivateStaticFieldDescriptor.js", + "import": "./helpers/esm/classCheckPrivateStaticFieldDescriptor.js", + "default": "./helpers/classCheckPrivateStaticFieldDescriptor.js" + }, + "./helpers/classCheckPrivateStaticFieldDescriptor.js" + ], + "./helpers/esm/classCheckPrivateStaticFieldDescriptor": "./helpers/esm/classCheckPrivateStaticFieldDescriptor.js", + "./helpers/decorate": [ + { + "node": "./helpers/decorate.js", + "import": "./helpers/esm/decorate.js", + "default": "./helpers/decorate.js" + }, + "./helpers/decorate.js" + ], + "./helpers/esm/decorate": "./helpers/esm/decorate.js", + "./helpers/classPrivateMethodGet": [ + { + "node": "./helpers/classPrivateMethodGet.js", + "import": "./helpers/esm/classPrivateMethodGet.js", + "default": "./helpers/classPrivateMethodGet.js" + }, + "./helpers/classPrivateMethodGet.js" + ], + "./helpers/esm/classPrivateMethodGet": "./helpers/esm/classPrivateMethodGet.js", + "./helpers/checkPrivateRedeclaration": [ + { + "node": "./helpers/checkPrivateRedeclaration.js", + "import": "./helpers/esm/checkPrivateRedeclaration.js", + "default": "./helpers/checkPrivateRedeclaration.js" + }, + "./helpers/checkPrivateRedeclaration.js" + ], + "./helpers/esm/checkPrivateRedeclaration": "./helpers/esm/checkPrivateRedeclaration.js", + "./helpers/classPrivateFieldInitSpec": [ + { + "node": "./helpers/classPrivateFieldInitSpec.js", + "import": "./helpers/esm/classPrivateFieldInitSpec.js", + "default": "./helpers/classPrivateFieldInitSpec.js" + }, + "./helpers/classPrivateFieldInitSpec.js" + ], + "./helpers/esm/classPrivateFieldInitSpec": "./helpers/esm/classPrivateFieldInitSpec.js", + "./helpers/classPrivateMethodInitSpec": [ + { + "node": "./helpers/classPrivateMethodInitSpec.js", + "import": "./helpers/esm/classPrivateMethodInitSpec.js", + "default": "./helpers/classPrivateMethodInitSpec.js" + }, + "./helpers/classPrivateMethodInitSpec.js" + ], + "./helpers/esm/classPrivateMethodInitSpec": "./helpers/esm/classPrivateMethodInitSpec.js", + "./helpers/classPrivateMethodSet": [ + { + "node": "./helpers/classPrivateMethodSet.js", + "import": "./helpers/esm/classPrivateMethodSet.js", + "default": "./helpers/classPrivateMethodSet.js" + }, + "./helpers/classPrivateMethodSet.js" + ], + "./helpers/esm/classPrivateMethodSet": "./helpers/esm/classPrivateMethodSet.js", + "./helpers/identity": [ + { + "node": "./helpers/identity.js", + "import": "./helpers/esm/identity.js", + "default": "./helpers/identity.js" + }, + "./helpers/identity.js" + ], + "./helpers/esm/identity": "./helpers/esm/identity.js", + "./package": "./package.json", + "./package.json": "./package.json", + "./regenerator": "./regenerator/index.js", + "./regenerator/*.js": "./regenerator/*.js", + "./regenerator/": "./regenerator/" + }, + "engines": { + "node": ">=6.9.0" + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/regenerator/index.js b/node_modules/@babel/runtime/regenerator/index.js new file mode 100644 index 0000000..9fd4158 --- /dev/null +++ b/node_modules/@babel/runtime/regenerator/index.js @@ -0,0 +1 @@ +module.exports = require("regenerator-runtime"); diff --git a/node_modules/complex.js/.travis.yml b/node_modules/complex.js/.travis.yml new file mode 100644 index 0000000..4632143 --- /dev/null +++ b/node_modules/complex.js/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "stable" +script: npm test diff --git a/node_modules/complex.js/LICENSE b/node_modules/complex.js/LICENSE new file mode 100644 index 0000000..cbed088 --- /dev/null +++ b/node_modules/complex.js/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Robert Eisele + +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. diff --git a/node_modules/complex.js/README.md b/node_modules/complex.js/README.md new file mode 100644 index 0000000..994ee5b --- /dev/null +++ b/node_modules/complex.js/README.md @@ -0,0 +1,343 @@ +# Complex.js - ℂ in JavaScript + +[![NPM Package](https://nodei.co/npm-dl/complex.js.png?months=6&height=1)](https://npmjs.org/package/complex.js) + +[![Build Status](https://travis-ci.org/infusion/Complex.js.svg?branch=master)](https://travis-ci.org/infusion/Complex.js) +[![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT) + +Complex.js is a well tested JavaScript library to work with [complex number arithmetic](https://www.xarg.org/book/analysis/complex-numbers/) in JavaScript. It implements every elementary complex number manipulation function and the API is intentionally similar to [Fraction.js](https://github.com/infusion/Fraction.js). Furthermore, it's the basis of [Polynomial.js](https://github.com/infusion/Polynomial.js) and [Math.js](https://github.com/josdejong/mathjs). + + +Examples +=== + +```js +let Complex = require('complex.js'); + +let c = new Complex("99.3+8i"); +c.mul({re: 3, im: 9}).div(4.9).sub(3, 2); +``` + +A classical use case for complex numbers is solving quadratic equations `ax² + bx + c = 0` for all `a, b, c ∈ ℝ`: + +```js + +function quadraticRoot(a, b, c) { + let sqrt = Complex(b * b - 4 * a * c).sqrt() + let x1 = Complex(-b).add(sqrt).div(2 * a) + let x2 = Complex(-b).sub(sqrt).div(2 * a) + return {x1, x2} +} + +// quadraticRoot(1, 4, 5) -> -2 ± i +``` + +Parser +=== + +Any function (see below) as well as the constructor of the *Complex* class parses its input like this. + +You can pass either Objects, Doubles or Strings. + +Objects +--- +```javascript +new Complex({re: real, im: imaginary}); +new Complex({arg: angle, abs: radius}); +new Complex({phi: angle, r: radius}); +new Complex([real, imaginary]); // Vector/Array syntax +``` +If there are other attributes on the passed object, they're not getting preserved and have to be merged manually. + +Doubles +--- +```javascript +new Complex(55.4); +``` + +Strings +--- +```javascript +new Complex("123.45"); +new Complex("15+3i"); +new Complex("i"); +``` + +Two arguments +--- +```javascript +new Complex(3, 2); // 3+2i +``` + +Attributes +=== + +Every complex number object exposes its real and imaginary part as attribute `re` and `im`: + +```javascript +let c = new Complex(3, 2); + +console.log("Real part:", c.re); // 3 +console.log("Imaginary part:", c.im); // 2 +``` + +Functions +=== + +Complex sign() +--- +Returns the complex sign, defined as the complex number normalized by it's absolute value + +Complex add(n) +--- +Adds another complex number + +Complex sub(n) +--- +Subtracts another complex number + +Complex mul(n) +--- +Multiplies the number with another complex number + +Complex div(n) +--- +Divides the number by another complex number + +Complex pow(exp) +--- +Returns the number raised to the complex exponent (Note: `Complex.ZERO.pow(0) = Complex.ONE` by convention) + +Complex sqrt() +--- +Returns the complex square root of the number + +Complex exp(n) +--- +Returns `e^n` with complex exponent `n`. + +Complex log() +--- +Returns the natural logarithm (base `E`) of the actual complex number + +_Note:_ The logarithm to a different base can be calculated with `z.log().div(Math.log(base))`. + +double abs() +--- +Calculates the magnitude of the complex number + +double arg() +--- +Calculates the angle of the complex number + +Complex inverse() +--- +Calculates the multiplicative inverse of the complex number (1 / z) + +Complex conjugate() +--- +Calculates the conjugate of the complex number (multiplies the imaginary part with -1) + +Complex neg() +--- +Negates the number (multiplies both the real and imaginary part with -1) in order to get the additive inverse + +Complex floor([places=0]) +--- +Floors the complex number parts towards zero + +Complex ceil([places=0]) +--- +Ceils the complex number parts off zero + +Complex round([places=0]) +--- +Rounds the complex number parts + +boolean equals(n) +--- +Checks if both numbers are exactly the same, if both numbers are infinite they +are considered **not** equal. + +boolean isNaN() +--- +Checks if the given number is not a number + +boolean isFinite() +--- +Checks if the given number is finite + +Complex clone() +--- +Returns a new Complex instance with the same real and imaginary properties + +Array toVector() +--- +Returns a Vector of the actual complex number with two components + +String toString() +--- +Returns a string representation of the actual number. As of v1.9.0 the output is a bit more human readable + +```javascript +new Complex(1, 2).toString(); // 1 + 2i +new Complex(0, 1).toString(); // i +new Complex(9, 0).toString(); // 9 +new Complex(1, 1).toString(); // 1 + i +``` + +double valueOf() +--- +Returns the real part of the number if imaginary part is zero. Otherwise `null` + + +Trigonometric functions +=== +The following trigonometric functions are defined on Complex.js: + +| Trig | Arcus | Hyperbolic | Area-Hyperbolic | +|------|-------|------------|------------------| +| sin() | asin() | sinh() | asinh() | +| cos() | acos() | cosh() | acosh() | +| tan() | atan() | tanh() | atanh() | +| cot() | acot() | coth() | acoth() | +| sec() | asec() | sech() | asech() | +| csc() | acsc() | csch() | acsch() | + + +Geometric Equivalence +=== + +Complex numbers can also be seen as a vector in the 2D space. Here is a simple overview of basic operations and how to implement them with complex.js: + +New vector +--- +```js +let v1 = new Complex(1, 0); +let v2 = new Complex(1, 1); +``` + +Scale vector +--- +```js +scale(v1, factor):= v1.mul(factor) +``` + +Vector norm +--- +```js +norm(v):= v.abs() +``` + +Translate vector +--- +```js +translate(v1, v2):= v1.add(v2) +``` + +Rotate vector around center +--- +```js +rotate(v, angle):= v.mul({abs: 1, arg: angle}) +``` + +Rotate vector around a point +--- +```js +rotate(v, p, angle):= v.sub(p).mul({abs: 1, arg: angle}).add(p) +``` + +Distance to another vector +--- +```js +distance(v1, v2):= v1.sub(v2).abs() +``` + +Constants +=== + +Complex.ZERO +--- +A complex zero value (south pole on the Riemann Sphere) + +Complex.ONE +--- +A complex one instance + +Complex.INFINITY +--- +A complex infinity value (north pole on the Riemann Sphere) + +Complex.NAN +--- +A complex NaN value (not on the Riemann Sphere) + +Complex.I +--- +An imaginary number i instance + +Complex.PI +--- +A complex PI instance + +Complex.E +--- +A complex euler number instance + +Complex.EPSILON +--- +A small epsilon value used for `equals()` comparison in order to circumvent double imprecision. + + +Installation +=== +Installing complex.js is as easy as cloning this repo or use one of the following commands: + +```bash +bower install complex.js +``` +or + +```bash +npm install complex.js +``` + +Using Complex.js with the browser +=== +```html + + +``` + +Using Complex.js with require.js +=== +```html + + +``` + +Coding Style +=== +As every library I publish, complex.js is also built to be as small as possible after compressing it with Google Closure Compiler in advanced mode. Thus the coding style orientates a little on maxing-out the compression rate. Please make sure you keep this style if you plan to extend the library. + + +Testing +=== +If you plan to enhance the library, make sure you add test cases and all the previous tests are passing. You can test the library with + +```bash +npm test +``` + + +Copyright and licensing +=== +Copyright (c) 2015-2022, [Robert Eisele](https://www.xarg.org/) +Dual licensed under the MIT or GPL Version 2 licenses. diff --git a/node_modules/complex.js/bower.json b/node_modules/complex.js/bower.json new file mode 100644 index 0000000..bd28a6a --- /dev/null +++ b/node_modules/complex.js/bower.json @@ -0,0 +1,31 @@ +{ + "name": "complex.js", + "main": "complex.js", + "version": "2.1.1", + "homepage": "https://github.com/infusion/Complex.js", + "description": "A complex number library", + "keywords": [ + "math", "complex", "number", "calculus", "parser" + ], + "moduleType": [ + "amd", + "globals", + "node" + ], + "authors": [ + "Robert Eisele (http://www.xarg.org/)" + ], + "license": [ + "MIT", + "GPL" + ], + "repository": { + "type": "git", + "url": "git://github.com/infusion/Complex.js.git" + }, + "ignore": [ + "tests", + ".travis.yml", + "package.json" + ] +} diff --git a/node_modules/complex.js/complex.d.ts b/node_modules/complex.js/complex.d.ts new file mode 100644 index 0000000..37003f1 --- /dev/null +++ b/node_modules/complex.js/complex.d.ts @@ -0,0 +1,323 @@ +type AValue = + | Complex + | { im: number; re: number } + | { abs: number; arg: number } + | { r: number; phi: number } + | [number, number] + | string + | number + | null + | undefined; +type BValue = number | undefined; + +export function Complex(a: AValue, b?: BValue): Complex; + +export default Complex; + +/** + * + * This class allows the manipulation of complex numbers. + * You can pass a complex number in different formats. Either as object, double, string or two integer parameters. + * + * Object form + * { re: , im: } + * { arg: , abs: } + * { phi: , r: } + * + * Array / Vector form + * [ real, imaginary ] + * + * Double form + * 99.3 - Single double value + * + * String form + * '23.1337' - Simple real number + * '15+3i' - a simple complex number + * '3-i' - a simple complex number + * + * Example: + * + * var c = new Complex('99.3+8i'); + * c.mul({r: 3, i: 9}).div(4.9).sub(3, 2); + * + */ +export class Complex { + re: number; + im: number; + + constructor(a: AValue, b?: BValue); + + /** + * Calculates the sign of a complex number, which is a normalized complex + * + */ + sign(): Complex; + /** + * Adds two complex numbers + * + */ + add(a: AValue, b?: BValue): Complex; + /** + * Subtracts two complex numbers + * + */ + sub(a: AValue, b?: BValue): Complex; + /** + * Multiplies two complex numbers + * + */ + mul(a: AValue, b?: BValue): Complex; + /** + * Divides two complex numbers + * + */ + div(a: AValue, b?: BValue): Complex; + /** + * Calculate the power of two complex numbers + * + */ + pow(a: AValue, b?: BValue): Complex; + /** + * Calculate the complex square root + * + */ + sqrt(): Complex; + /** + * Calculate the complex exponent + * + */ + exp(): Complex; + /** + * Calculate the complex exponent and subtracts one. + * + * This may be more accurate than `Complex(x).exp().sub(1)` if + * `x` is small. + * + */ + expm1(): Complex; + /** + * Calculate the natural log + * + */ + log(): Complex; + /** + * Calculate the magnitude of the complex number + * + */ + abs(): number; + /** + * Calculate the angle of the complex number + * + */ + arg(): number; + /** + * Calculate the sine of the complex number + * + */ + sin(): Complex; + /** + * Calculate the cosine + * + */ + cos(): Complex; + /** + * Calculate the tangent + * + */ + tan(): Complex; + /** + * Calculate the cotangent + * + */ + cot(): Complex; + /** + * Calculate the secant + * + */ + sec(): Complex; + /** + * Calculate the cosecans + * + */ + csc(): Complex; + /** + * Calculate the complex arcus sinus + * + */ + asin(): Complex; + /** + * Calculate the complex arcus cosinus + * + */ + acos(): Complex; + /** + * Calculate the complex arcus tangent + * + */ + atan(): Complex; + /** + * Calculate the complex arcus cotangent + * + */ + acot(): Complex; + /** + * Calculate the complex arcus secant + * + */ + asec(): Complex; + /** + * Calculate the complex arcus cosecans + * + */ + acsc(): Complex; + /** + * Calculate the complex sinh + * + */ + sinh(): Complex; + /** + * Calculate the complex cosh + * + */ + cosh(): Complex; + /** + * Calculate the complex tanh + * + */ + tanh(): Complex; + /** + * Calculate the complex coth + * + */ + coth(): Complex; + /** + * Calculate the complex coth + * + */ + csch(): Complex; + /** + * Calculate the complex sech + * + */ + sech(): Complex; + /** + * Calculate the complex asinh + * + */ + asinh(): Complex; + /** + * Calculate the complex acosh + * + */ + acosh(): Complex; + /** + * Calculate the complex atanh + * + */ + atanh(): Complex; + /** + * Calculate the complex acoth + * + */ + acoth(): Complex; + /** + * Calculate the complex acsch + * + */ + acsch(): Complex; + /** + * Calculate the complex asech + * + */ + asech(): Complex; + /** + * Calculate the complex inverse 1/z + * + */ + inverse(): Complex; + /** + * Returns the complex conjugate + * + */ + conjugate(): Complex; + /** + * Gets the negated complex number + * + */ + neg(): Complex; + /** + * Ceils the actual complex number + * + */ + ceil(places: number): Complex; + /** + * Floors the actual complex number + * + */ + floor(places: number): Complex; + /** + * Ceils the actual complex number + * + */ + round(places: number): Complex; + /** + * Compares two complex numbers + * + * **Note:** new Complex(Infinity).equals(Infinity) === false + * + */ + equals(a: AValue, b?: BValue): boolean; + /** + * Clones the actual object + * + */ + clone(): Complex; + /** + * Gets a string of the actual complex number + * + */ + toString(): string; + /** + * Returns the actual number as a vector + * + */ + toVector(): number[]; + /** + * Returns the actual real value of the current object + * + * @returns {number|null} + */ + valueOf(): number | null; + /** + * Determines whether a complex number is not on the Riemann sphere. + * + */ + isNaN(): boolean; + /** + * Determines whether or not a complex number is at the zero pole of the + * Riemann sphere. + * + */ + isZero(): boolean; + /** + * Determines whether a complex number is not at the infinity pole of the + * Riemann sphere. + * + */ + isFinite(): boolean; + /** + * Determines whether or not a complex number is at the infinity pole of the + * Riemann sphere. + * + */ + isInfinite(): boolean; + + static ZERO: Complex; + static ONE: Complex; + static I: Complex; + static PI: Complex; + static E: Complex; + static INFINITY: Complex; + static NAN: Complex; + static EPSILON: number; +} diff --git a/node_modules/complex.js/complex.js b/node_modules/complex.js/complex.js new file mode 100644 index 0000000..308e753 --- /dev/null +++ b/node_modules/complex.js/complex.js @@ -0,0 +1,1424 @@ +/** + * @license Complex.js v2.1.1 12/05/2020 + * + * Copyright (c) 2020, Robert Eisele (robert@xarg.org) + * Dual licensed under the MIT or GPL Version 2 licenses. + **/ + +/** + * + * This class allows the manipulation of complex numbers. + * You can pass a complex number in different formats. Either as object, double, string or two integer parameters. + * + * Object form + * { re: , im: } + * { arg: , abs: } + * { phi: , r: } + * + * Array / Vector form + * [ real, imaginary ] + * + * Double form + * 99.3 - Single double value + * + * String form + * '23.1337' - Simple real number + * '15+3i' - a simple complex number + * '3-i' - a simple complex number + * + * Example: + * + * var c = new Complex('99.3+8i'); + * c.mul({r: 3, i: 9}).div(4.9).sub(3, 2); + * + */ + +(function(root) { + + 'use strict'; + + var cosh = Math.cosh || function(x) { + return Math.abs(x) < 1e-9 ? 1 - x : (Math.exp(x) + Math.exp(-x)) * 0.5; + }; + + var sinh = Math.sinh || function(x) { + return Math.abs(x) < 1e-9 ? x : (Math.exp(x) - Math.exp(-x)) * 0.5; + }; + + /** + * Calculates cos(x) - 1 using Taylor series if x is small (-¼π ≤ x ≤ ¼π). + * + * @param {number} x + * @returns {number} cos(x) - 1 + */ + var cosm1 = function(x) { + + var b = Math.PI / 4; + if (-b > x || x > b) { + return Math.cos(x) - 1.0; + } + + /* Calculate horner form of polynomial of taylor series in Q + var fac = 1, alt = 1, pol = {}; + for (var i = 0; i <= 16; i++) { + fac*= i || 1; + if (i % 2 == 0) { + pol[i] = new Fraction(1, alt * fac); + alt = -alt; + } + } + console.log(new Polynomial(pol).toHorner()); // (((((((1/20922789888000x^2-1/87178291200)x^2+1/479001600)x^2-1/3628800)x^2+1/40320)x^2-1/720)x^2+1/24)x^2-1/2)x^2+1 + */ + + var xx = x * x; + return xx * ( + xx * ( + xx * ( + xx * ( + xx * ( + xx * ( + xx * ( + xx / 20922789888000 + - 1 / 87178291200) + + 1 / 479001600) + - 1 / 3628800) + + 1 / 40320) + - 1 / 720) + + 1 / 24) + - 1 / 2); + }; + + var hypot = function(x, y) { + + var a = Math.abs(x); + var b = Math.abs(y); + + if (a < 3000 && b < 3000) { + return Math.sqrt(a * a + b * b); + } + + if (a < b) { + a = b; + b = x / y; + } else { + b = y / x; + } + return a * Math.sqrt(1 + b * b); + }; + + var parser_exit = function() { + throw SyntaxError('Invalid Param'); + }; + + /** + * Calculates log(sqrt(a^2+b^2)) in a way to avoid overflows + * + * @param {number} a + * @param {number} b + * @returns {number} + */ + function logHypot(a, b) { + + var _a = Math.abs(a); + var _b = Math.abs(b); + + if (a === 0) { + return Math.log(_b); + } + + if (b === 0) { + return Math.log(_a); + } + + if (_a < 3000 && _b < 3000) { + return Math.log(a * a + b * b) * 0.5; + } + + /* I got 4 ideas to compute this property without overflow: + * + * Testing 1000000 times with random samples for a,b ∈ [1, 1000000000] against a big decimal library to get an error estimate + * + * 1. Only eliminate the square root: (OVERALL ERROR: 3.9122483030951116e-11) + + Math.log(a * a + b * b) / 2 + + * + * + * 2. Try to use the non-overflowing pythagoras: (OVERALL ERROR: 8.889760039210159e-10) + + var fn = function(a, b) { + a = Math.abs(a); + b = Math.abs(b); + var t = Math.min(a, b); + a = Math.max(a, b); + t = t / a; + + return Math.log(a) + Math.log(1 + t * t) / 2; + }; + + * 3. Abuse the identity cos(atan(y/x) = x / sqrt(x^2+y^2): (OVERALL ERROR: 3.4780178737037204e-10) + + Math.log(a / Math.cos(Math.atan2(b, a))) + + * 4. Use 3. and apply log rules: (OVERALL ERROR: 1.2014087502620896e-9) + + Math.log(a) - Math.log(Math.cos(Math.atan2(b, a))) + + */ + + a = a / 2; + b = b / 2; + + return 0.5 * Math.log(a * a + b * b) + Math.LN2; + } + + var parse = function(a, b) { + + var z = { 're': 0, 'im': 0 }; + + if (a === undefined || a === null) { + z['re'] = + z['im'] = 0; + } else if (b !== undefined) { + z['re'] = a; + z['im'] = b; + } else + switch (typeof a) { + + case 'object': + + if ('im' in a && 're' in a) { + z['re'] = a['re']; + z['im'] = a['im']; + } else if ('abs' in a && 'arg' in a) { + if (!Number.isFinite(a['abs']) && Number.isFinite(a['arg'])) { + return Complex['INFINITY']; + } + z['re'] = a['abs'] * Math.cos(a['arg']); + z['im'] = a['abs'] * Math.sin(a['arg']); + } else if ('r' in a && 'phi' in a) { + if (!Number.isFinite(a['r']) && Number.isFinite(a['phi'])) { + return Complex['INFINITY']; + } + z['re'] = a['r'] * Math.cos(a['phi']); + z['im'] = a['r'] * Math.sin(a['phi']); + } else if (a.length === 2) { // Quick array check + z['re'] = a[0]; + z['im'] = a[1]; + } else { + parser_exit(); + } + break; + + case 'string': + + z['im'] = /* void */ + z['re'] = 0; + + var tokens = a.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g); + var plus = 1; + var minus = 0; + + if (tokens === null) { + parser_exit(); + } + + for (var i = 0; i < tokens.length; i++) { + + var c = tokens[i]; + + if (c === ' ' || c === '\t' || c === '\n') { + /* void */ + } else if (c === '+') { + plus++; + } else if (c === '-') { + minus++; + } else if (c === 'i' || c === 'I') { + + if (plus + minus === 0) { + parser_exit(); + } + + if (tokens[i + 1] !== ' ' && !isNaN(tokens[i + 1])) { + z['im'] += parseFloat((minus % 2 ? '-' : '') + tokens[i + 1]); + i++; + } else { + z['im'] += parseFloat((minus % 2 ? '-' : '') + '1'); + } + plus = minus = 0; + + } else { + + if (plus + minus === 0 || isNaN(c)) { + parser_exit(); + } + + if (tokens[i + 1] === 'i' || tokens[i + 1] === 'I') { + z['im'] += parseFloat((minus % 2 ? '-' : '') + c); + i++; + } else { + z['re'] += parseFloat((minus % 2 ? '-' : '') + c); + } + plus = minus = 0; + } + } + + // Still something on the stack + if (plus + minus > 0) { + parser_exit(); + } + break; + + case 'number': + z['im'] = 0; + z['re'] = a; + break; + + default: + parser_exit(); + } + + if (isNaN(z['re']) || isNaN(z['im'])) { + // If a calculation is NaN, we treat it as NaN and don't throw + //parser_exit(); + } + + return z; + }; + + /** + * @constructor + * @returns {Complex} + */ + function Complex(a, b) { + + if (!(this instanceof Complex)) { + return new Complex(a, b); + } + + var z = parse(a, b); + + this['re'] = z['re']; + this['im'] = z['im']; + } + + Complex.prototype = { + + 're': 0, + 'im': 0, + + /** + * Calculates the sign of a complex number, which is a normalized complex + * + * @returns {Complex} + */ + 'sign': function() { + + var abs = this['abs'](); + + return new Complex( + this['re'] / abs, + this['im'] / abs); + }, + + /** + * Adds two complex numbers + * + * @returns {Complex} + */ + 'add': function(a, b) { + + var z = new Complex(a, b); + + // Infinity + Infinity = NaN + if (this['isInfinite']() && z['isInfinite']()) { + return Complex['NAN']; + } + + // Infinity + z = Infinity { where z != Infinity } + if (this['isInfinite']() || z['isInfinite']()) { + return Complex['INFINITY']; + } + + return new Complex( + this['re'] + z['re'], + this['im'] + z['im']); + }, + + /** + * Subtracts two complex numbers + * + * @returns {Complex} + */ + 'sub': function(a, b) { + + var z = new Complex(a, b); + + // Infinity - Infinity = NaN + if (this['isInfinite']() && z['isInfinite']()) { + return Complex['NAN']; + } + + // Infinity - z = Infinity { where z != Infinity } + if (this['isInfinite']() || z['isInfinite']()) { + return Complex['INFINITY']; + } + + return new Complex( + this['re'] - z['re'], + this['im'] - z['im']); + }, + + /** + * Multiplies two complex numbers + * + * @returns {Complex} + */ + 'mul': function(a, b) { + + var z = new Complex(a, b); + + // Infinity * 0 = NaN + if ((this['isInfinite']() && z['isZero']()) || (this['isZero']() && z['isInfinite']())) { + return Complex['NAN']; + } + + // Infinity * z = Infinity { where z != 0 } + if (this['isInfinite']() || z['isInfinite']()) { + return Complex['INFINITY']; + } + + // Short circuit for real values + if (z['im'] === 0 && this['im'] === 0) { + return new Complex(this['re'] * z['re'], 0); + } + + return new Complex( + this['re'] * z['re'] - this['im'] * z['im'], + this['re'] * z['im'] + this['im'] * z['re']); + }, + + /** + * Divides two complex numbers + * + * @returns {Complex} + */ + 'div': function(a, b) { + + var z = new Complex(a, b); + + // 0 / 0 = NaN and Infinity / Infinity = NaN + if ((this['isZero']() && z['isZero']()) || (this['isInfinite']() && z['isInfinite']())) { + return Complex['NAN']; + } + + // Infinity / 0 = Infinity + if (this['isInfinite']() || z['isZero']()) { + return Complex['INFINITY']; + } + + // 0 / Infinity = 0 + if (this['isZero']() || z['isInfinite']()) { + return Complex['ZERO']; + } + + a = this['re']; + b = this['im']; + + var c = z['re']; + var d = z['im']; + var t, x; + + if (0 === d) { + // Divisor is real + return new Complex(a / c, b / c); + } + + if (Math.abs(c) < Math.abs(d)) { + + x = c / d; + t = c * x + d; + + return new Complex( + (a * x + b) / t, + (b * x - a) / t); + + } else { + + x = d / c; + t = d * x + c; + + return new Complex( + (a + b * x) / t, + (b - a * x) / t); + } + }, + + /** + * Calculate the power of two complex numbers + * + * @returns {Complex} + */ + 'pow': function(a, b) { + + var z = new Complex(a, b); + + a = this['re']; + b = this['im']; + + if (z['isZero']()) { + return Complex['ONE']; + } + + // If the exponent is real + if (z['im'] === 0) { + + if (b === 0 && a > 0) { + + return new Complex(Math.pow(a, z['re']), 0); + + } else if (a === 0) { // If base is fully imaginary + + switch ((z['re'] % 4 + 4) % 4) { + case 0: + return new Complex(Math.pow(b, z['re']), 0); + case 1: + return new Complex(0, Math.pow(b, z['re'])); + case 2: + return new Complex(-Math.pow(b, z['re']), 0); + case 3: + return new Complex(0, -Math.pow(b, z['re'])); + } + } + } + + /* I couldn't find a good formula, so here is a derivation and optimization + * + * z_1^z_2 = (a + bi)^(c + di) + * = exp((c + di) * log(a + bi) + * = pow(a^2 + b^2, (c + di) / 2) * exp(i(c + di)atan2(b, a)) + * =>... + * Re = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * cos(d * log(a^2 + b^2) / 2 + c * atan2(b, a)) + * Im = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * sin(d * log(a^2 + b^2) / 2 + c * atan2(b, a)) + * + * =>... + * Re = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * cos(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a)) + * Im = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * sin(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a)) + * + * => + * Re = exp(c * logsq2 - d * arg(z_1)) * cos(d * logsq2 + c * arg(z_1)) + * Im = exp(c * logsq2 - d * arg(z_1)) * sin(d * logsq2 + c * arg(z_1)) + * + */ + + if (a === 0 && b === 0 && z['re'] > 0 && z['im'] >= 0) { + return Complex['ZERO']; + } + + var arg = Math.atan2(b, a); + var loh = logHypot(a, b); + + a = Math.exp(z['re'] * loh - z['im'] * arg); + b = z['im'] * loh + z['re'] * arg; + return new Complex( + a * Math.cos(b), + a * Math.sin(b)); + }, + + /** + * Calculate the complex square root + * + * @returns {Complex} + */ + 'sqrt': function() { + + var a = this['re']; + var b = this['im']; + var r = this['abs'](); + + var re, im; + + if (a >= 0) { + + if (b === 0) { + return new Complex(Math.sqrt(a), 0); + } + + re = 0.5 * Math.sqrt(2.0 * (r + a)); + } else { + re = Math.abs(b) / Math.sqrt(2 * (r - a)); + } + + if (a <= 0) { + im = 0.5 * Math.sqrt(2.0 * (r - a)); + } else { + im = Math.abs(b) / Math.sqrt(2 * (r + a)); + } + + return new Complex(re, b < 0 ? -im : im); + }, + + /** + * Calculate the complex exponent + * + * @returns {Complex} + */ + 'exp': function() { + + var tmp = Math.exp(this['re']); + + if (this['im'] === 0) { + //return new Complex(tmp, 0); + } + return new Complex( + tmp * Math.cos(this['im']), + tmp * Math.sin(this['im'])); + }, + + /** + * Calculate the complex exponent and subtracts one. + * + * This may be more accurate than `Complex(x).exp().sub(1)` if + * `x` is small. + * + * @returns {Complex} + */ + 'expm1': function() { + + /** + * exp(a + i*b) - 1 + = exp(a) * (cos(b) + j*sin(b)) - 1 + = expm1(a)*cos(b) + cosm1(b) + j*exp(a)*sin(b) + */ + + var a = this['re']; + var b = this['im']; + + return new Complex( + Math.expm1(a) * Math.cos(b) + cosm1(b), + Math.exp(a) * Math.sin(b)); + }, + + /** + * Calculate the natural log + * + * @returns {Complex} + */ + 'log': function() { + + var a = this['re']; + var b = this['im']; + + if (b === 0 && a > 0) { + //return new Complex(Math.log(a), 0); + } + + return new Complex( + logHypot(a, b), + Math.atan2(b, a)); + }, + + /** + * Calculate the magnitude of the complex number + * + * @returns {number} + */ + 'abs': function() { + + return hypot(this['re'], this['im']); + }, + + /** + * Calculate the angle of the complex number + * + * @returns {number} + */ + 'arg': function() { + + return Math.atan2(this['im'], this['re']); + }, + + /** + * Calculate the sine of the complex number + * + * @returns {Complex} + */ + 'sin': function() { + + // sin(z) = ( e^iz - e^-iz ) / 2i + // = sin(a)cosh(b) + i cos(a)sinh(b) + + var a = this['re']; + var b = this['im']; + + return new Complex( + Math.sin(a) * cosh(b), + Math.cos(a) * sinh(b)); + }, + + /** + * Calculate the cosine + * + * @returns {Complex} + */ + 'cos': function() { + + // cos(z) = ( e^iz + e^-iz ) / 2 + // = cos(a)cosh(b) - i sin(a)sinh(b) + + var a = this['re']; + var b = this['im']; + + return new Complex( + Math.cos(a) * cosh(b), + -Math.sin(a) * sinh(b)); + }, + + /** + * Calculate the tangent + * + * @returns {Complex} + */ + 'tan': function() { + + // tan(z) = sin(z) / cos(z) + // = ( e^iz - e^-iz ) / ( i( e^iz + e^-iz ) ) + // = ( e^2iz - 1 ) / i( e^2iz + 1 ) + // = ( sin(2a) + i sinh(2b) ) / ( cos(2a) + cosh(2b) ) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = Math.cos(a) + cosh(b); + + return new Complex( + Math.sin(a) / d, + sinh(b) / d); + }, + + /** + * Calculate the cotangent + * + * @returns {Complex} + */ + 'cot': function() { + + // cot(c) = i(e^(ci) + e^(-ci)) / (e^(ci) - e^(-ci)) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = Math.cos(a) - cosh(b); + + return new Complex( + -Math.sin(a) / d, + sinh(b) / d); + }, + + /** + * Calculate the secant + * + * @returns {Complex} + */ + 'sec': function() { + + // sec(c) = 2 / (e^(ci) + e^(-ci)) + + var a = this['re']; + var b = this['im']; + var d = 0.5 * cosh(2 * b) + 0.5 * Math.cos(2 * a); + + return new Complex( + Math.cos(a) * cosh(b) / d, + Math.sin(a) * sinh(b) / d); + }, + + /** + * Calculate the cosecans + * + * @returns {Complex} + */ + 'csc': function() { + + // csc(c) = 2i / (e^(ci) - e^(-ci)) + + var a = this['re']; + var b = this['im']; + var d = 0.5 * cosh(2 * b) - 0.5 * Math.cos(2 * a); + + return new Complex( + Math.sin(a) * cosh(b) / d, + -Math.cos(a) * sinh(b) / d); + }, + + /** + * Calculate the complex arcus sinus + * + * @returns {Complex} + */ + 'asin': function() { + + // asin(c) = -i * log(ci + sqrt(1 - c^2)) + + var a = this['re']; + var b = this['im']; + + var t1 = new Complex( + b * b - a * a + 1, + -2 * a * b)['sqrt'](); + + var t2 = new Complex( + t1['re'] - b, + t1['im'] + a)['log'](); + + return new Complex(t2['im'], -t2['re']); + }, + + /** + * Calculate the complex arcus cosinus + * + * @returns {Complex} + */ + 'acos': function() { + + // acos(c) = i * log(c - i * sqrt(1 - c^2)) + + var a = this['re']; + var b = this['im']; + + var t1 = new Complex( + b * b - a * a + 1, + -2 * a * b)['sqrt'](); + + var t2 = new Complex( + t1['re'] - b, + t1['im'] + a)['log'](); + + return new Complex(Math.PI / 2 - t2['im'], t2['re']); + }, + + /** + * Calculate the complex arcus tangent + * + * @returns {Complex} + */ + 'atan': function() { + + // atan(c) = i / 2 log((i + x) / (i - x)) + + var a = this['re']; + var b = this['im']; + + if (a === 0) { + + if (b === 1) { + return new Complex(0, Infinity); + } + + if (b === -1) { + return new Complex(0, -Infinity); + } + } + + var d = a * a + (1.0 - b) * (1.0 - b); + + var t1 = new Complex( + (1 - b * b - a * a) / d, + -2 * a / d).log(); + + return new Complex(-0.5 * t1['im'], 0.5 * t1['re']); + }, + + /** + * Calculate the complex arcus cotangent + * + * @returns {Complex} + */ + 'acot': function() { + + // acot(c) = i / 2 log((c - i) / (c + i)) + + var a = this['re']; + var b = this['im']; + + if (b === 0) { + return new Complex(Math.atan2(1, a), 0); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).atan() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).atan(); + }, + + /** + * Calculate the complex arcus secant + * + * @returns {Complex} + */ + 'asec': function() { + + // asec(c) = -i * log(1 / c + sqrt(1 - i / c^2)) + + var a = this['re']; + var b = this['im']; + + if (a === 0 && b === 0) { + return new Complex(0, Infinity); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).acos() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).acos(); + }, + + /** + * Calculate the complex arcus cosecans + * + * @returns {Complex} + */ + 'acsc': function() { + + // acsc(c) = -i * log(i / c + sqrt(1 - 1 / c^2)) + + var a = this['re']; + var b = this['im']; + + if (a === 0 && b === 0) { + return new Complex(Math.PI / 2, Infinity); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).asin() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).asin(); + }, + + /** + * Calculate the complex sinh + * + * @returns {Complex} + */ + 'sinh': function() { + + // sinh(c) = (e^c - e^-c) / 2 + + var a = this['re']; + var b = this['im']; + + return new Complex( + sinh(a) * Math.cos(b), + cosh(a) * Math.sin(b)); + }, + + /** + * Calculate the complex cosh + * + * @returns {Complex} + */ + 'cosh': function() { + + // cosh(c) = (e^c + e^-c) / 2 + + var a = this['re']; + var b = this['im']; + + return new Complex( + cosh(a) * Math.cos(b), + sinh(a) * Math.sin(b)); + }, + + /** + * Calculate the complex tanh + * + * @returns {Complex} + */ + 'tanh': function() { + + // tanh(c) = (e^c - e^-c) / (e^c + e^-c) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = cosh(a) + Math.cos(b); + + return new Complex( + sinh(a) / d, + Math.sin(b) / d); + }, + + /** + * Calculate the complex coth + * + * @returns {Complex} + */ + 'coth': function() { + + // coth(c) = (e^c + e^-c) / (e^c - e^-c) + + var a = 2 * this['re']; + var b = 2 * this['im']; + var d = cosh(a) - Math.cos(b); + + return new Complex( + sinh(a) / d, + -Math.sin(b) / d); + }, + + /** + * Calculate the complex coth + * + * @returns {Complex} + */ + 'csch': function() { + + // csch(c) = 2 / (e^c - e^-c) + + var a = this['re']; + var b = this['im']; + var d = Math.cos(2 * b) - cosh(2 * a); + + return new Complex( + -2 * sinh(a) * Math.cos(b) / d, + 2 * cosh(a) * Math.sin(b) / d); + }, + + /** + * Calculate the complex sech + * + * @returns {Complex} + */ + 'sech': function() { + + // sech(c) = 2 / (e^c + e^-c) + + var a = this['re']; + var b = this['im']; + var d = Math.cos(2 * b) + cosh(2 * a); + + return new Complex( + 2 * cosh(a) * Math.cos(b) / d, + -2 * sinh(a) * Math.sin(b) / d); + }, + + /** + * Calculate the complex asinh + * + * @returns {Complex} + */ + 'asinh': function() { + + // asinh(c) = log(c + sqrt(c^2 + 1)) + + var tmp = this['im']; + this['im'] = -this['re']; + this['re'] = tmp; + var res = this['asin'](); + + this['re'] = -this['im']; + this['im'] = tmp; + tmp = res['re']; + + res['re'] = -res['im']; + res['im'] = tmp; + return res; + }, + + /** + * Calculate the complex acosh + * + * @returns {Complex} + */ + 'acosh': function() { + + // acosh(c) = log(c + sqrt(c^2 - 1)) + + var res = this['acos'](); + if (res['im'] <= 0) { + var tmp = res['re']; + res['re'] = -res['im']; + res['im'] = tmp; + } else { + var tmp = res['im']; + res['im'] = -res['re']; + res['re'] = tmp; + } + return res; + }, + + /** + * Calculate the complex atanh + * + * @returns {Complex} + */ + 'atanh': function() { + + // atanh(c) = log((1+c) / (1-c)) / 2 + + var a = this['re']; + var b = this['im']; + + var noIM = a > 1 && b === 0; + var oneMinus = 1 - a; + var onePlus = 1 + a; + var d = oneMinus * oneMinus + b * b; + + var x = (d !== 0) + ? new Complex( + (onePlus * oneMinus - b * b) / d, + (b * oneMinus + onePlus * b) / d) + : new Complex( + (a !== -1) ? (a / 0) : 0, + (b !== 0) ? (b / 0) : 0); + + var temp = x['re']; + x['re'] = logHypot(x['re'], x['im']) / 2; + x['im'] = Math.atan2(x['im'], temp) / 2; + if (noIM) { + x['im'] = -x['im']; + } + return x; + }, + + /** + * Calculate the complex acoth + * + * @returns {Complex} + */ + 'acoth': function() { + + // acoth(c) = log((c+1) / (c-1)) / 2 + + var a = this['re']; + var b = this['im']; + + if (a === 0 && b === 0) { + return new Complex(0, Math.PI / 2); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).atanh() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).atanh(); + }, + + /** + * Calculate the complex acsch + * + * @returns {Complex} + */ + 'acsch': function() { + + // acsch(c) = log((1+sqrt(1+c^2))/c) + + var a = this['re']; + var b = this['im']; + + if (b === 0) { + + return new Complex( + (a !== 0) + ? Math.log(a + Math.sqrt(a * a + 1)) + : Infinity, 0); + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).asinh() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).asinh(); + }, + + /** + * Calculate the complex asech + * + * @returns {Complex} + */ + 'asech': function() { + + // asech(c) = log((1+sqrt(1-c^2))/c) + + var a = this['re']; + var b = this['im']; + + if (this['isZero']()) { + return Complex['INFINITY']; + } + + var d = a * a + b * b; + return (d !== 0) + ? new Complex( + a / d, + -b / d).acosh() + : new Complex( + (a !== 0) ? a / 0 : 0, + (b !== 0) ? -b / 0 : 0).acosh(); + }, + + /** + * Calculate the complex inverse 1/z + * + * @returns {Complex} + */ + 'inverse': function() { + + // 1 / 0 = Infinity and 1 / Infinity = 0 + if (this['isZero']()) { + return Complex['INFINITY']; + } + + if (this['isInfinite']()) { + return Complex['ZERO']; + } + + var a = this['re']; + var b = this['im']; + + var d = a * a + b * b; + + return new Complex(a / d, -b / d); + }, + + /** + * Returns the complex conjugate + * + * @returns {Complex} + */ + 'conjugate': function() { + + return new Complex(this['re'], -this['im']); + }, + + /** + * Gets the negated complex number + * + * @returns {Complex} + */ + 'neg': function() { + + return new Complex(-this['re'], -this['im']); + }, + + /** + * Ceils the actual complex number + * + * @returns {Complex} + */ + 'ceil': function(places) { + + places = Math.pow(10, places || 0); + + return new Complex( + Math.ceil(this['re'] * places) / places, + Math.ceil(this['im'] * places) / places); + }, + + /** + * Floors the actual complex number + * + * @returns {Complex} + */ + 'floor': function(places) { + + places = Math.pow(10, places || 0); + + return new Complex( + Math.floor(this['re'] * places) / places, + Math.floor(this['im'] * places) / places); + }, + + /** + * Ceils the actual complex number + * + * @returns {Complex} + */ + 'round': function(places) { + + places = Math.pow(10, places || 0); + + return new Complex( + Math.round(this['re'] * places) / places, + Math.round(this['im'] * places) / places); + }, + + /** + * Compares two complex numbers + * + * **Note:** new Complex(Infinity).equals(Infinity) === false + * + * @returns {boolean} + */ + 'equals': function(a, b) { + + var z = new Complex(a, b); + + return Math.abs(z['re'] - this['re']) <= Complex['EPSILON'] && + Math.abs(z['im'] - this['im']) <= Complex['EPSILON']; + }, + + /** + * Clones the actual object + * + * @returns {Complex} + */ + 'clone': function() { + + return new Complex(this['re'], this['im']); + }, + + /** + * Gets a string of the actual complex number + * + * @returns {string} + */ + 'toString': function() { + + var a = this['re']; + var b = this['im']; + var ret = ""; + + if (this['isNaN']()) { + return 'NaN'; + } + + if (this['isInfinite']()) { + return 'Infinity'; + } + + if (Math.abs(a) < Complex['EPSILON']) { + a = 0; + } + + if (Math.abs(b) < Complex['EPSILON']) { + b = 0; + } + + // If is real number + if (b === 0) { + return ret + a; + } + + if (a !== 0) { + ret += a; + ret += " "; + if (b < 0) { + b = -b; + ret += "-"; + } else { + ret += "+"; + } + ret += " "; + } else if (b < 0) { + b = -b; + ret += "-"; + } + + if (1 !== b) { // b is the absolute imaginary part + ret += b; + } + return ret + "i"; + }, + + /** + * Returns the actual number as a vector + * + * @returns {Array} + */ + 'toVector': function() { + + return [this['re'], this['im']]; + }, + + /** + * Returns the actual real value of the current object + * + * @returns {number|null} + */ + 'valueOf': function() { + + if (this['im'] === 0) { + return this['re']; + } + return null; + }, + + /** + * Determines whether a complex number is not on the Riemann sphere. + * + * @returns {boolean} + */ + 'isNaN': function() { + return isNaN(this['re']) || isNaN(this['im']); + }, + + /** + * Determines whether or not a complex number is at the zero pole of the + * Riemann sphere. + * + * @returns {boolean} + */ + 'isZero': function() { + return this['im'] === 0 && this['re'] === 0; + }, + + /** + * Determines whether a complex number is not at the infinity pole of the + * Riemann sphere. + * + * @returns {boolean} + */ + 'isFinite': function() { + return isFinite(this['re']) && isFinite(this['im']); + }, + + /** + * Determines whether or not a complex number is at the infinity pole of the + * Riemann sphere. + * + * @returns {boolean} + */ + 'isInfinite': function() { + return !(this['isNaN']() || this['isFinite']()); + } + }; + + Complex['ZERO'] = new Complex(0, 0); + Complex['ONE'] = new Complex(1, 0); + Complex['I'] = new Complex(0, 1); + Complex['PI'] = new Complex(Math.PI, 0); + Complex['E'] = new Complex(Math.E, 0); + Complex['INFINITY'] = new Complex(Infinity, Infinity); + Complex['NAN'] = new Complex(NaN, NaN); + Complex['EPSILON'] = 1e-15; + + if (typeof define === 'function' && define['amd']) { + define([], function() { + return Complex; + }); + } else if (typeof exports === 'object') { + Object.defineProperty(Complex, "__esModule", { 'value': true }); + Complex['default'] = Complex; + Complex['Complex'] = Complex; + module['exports'] = Complex; + } else { + root['Complex'] = Complex; + } + +})(this); diff --git a/node_modules/complex.js/complex.min.js b/node_modules/complex.js/complex.min.js new file mode 100644 index 0000000..a9443f0 --- /dev/null +++ b/node_modules/complex.js/complex.min.js @@ -0,0 +1,24 @@ +/* +Complex.js v2.1.1 12/05/2020 + +Copyright (c) 2022, Robert Eisele (robert@xarg.org) +Dual licensed under the MIT or GPL Version 2 licenses. +*/ +(function(q){function n(){throw SyntaxError("Invalid Param");}function p(a,b){var c=Math.abs(a),e=Math.abs(b);if(0===a)return Math.log(e);if(0===b)return Math.log(c);if(3E3>c&&3E3>e)return.5*Math.log(a*a+b*b);a/=2;b/=2;return.5*Math.log(a*a+b*b)+Math.LN2}function d(a,b){if(!(this instanceof d))return new d(a,b);var c={re:0,im:0};if(void 0===a||null===a)c.re=c.im=0;else if(void 0!==b)c.re=a,c.im=b;else switch(typeof a){case "object":"im"in a&&"re"in a?(c.re=a.re,c.im=a.im):"abs"in a&&"arg"in a?!Number.isFinite(a.abs)&& +Number.isFinite(a.arg)?c=d.INFINITY:(c.re=a.abs*Math.cos(a.arg),c.im=a.abs*Math.sin(a.arg)):"r"in a&&"phi"in a?!Number.isFinite(a.r)&&Number.isFinite(a.phi)?c=d.INFINITY:(c.re=a.r*Math.cos(a.phi),c.im=a.r*Math.sin(a.phi)):2===a.length?(c.re=a[0],c.im=a[1]):n();break;case "string":c.im=c.re=0;var e=a.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g),f=1,h=0;null===e&&n();for(var l=0;lMath.abs(a)?1-a:.5*(Math.exp(a)+Math.exp(-a))},k=Math.sinh||function(a){return 1E-9>Math.abs(a)?a:.5*(Math.exp(a)-Math.exp(-a))};d.prototype= +{re:0,im:0,sign:function(){var a=this.abs();return new d(this.re/a,this.im/a)},add:function(a,b){var c=new d(a,b);return this.isInfinite()&&c.isInfinite()?d.NAN:this.isInfinite()||c.isInfinite()?d.INFINITY:new d(this.re+c.re,this.im+c.im)},sub:function(a,b){var c=new d(a,b);return this.isInfinite()&&c.isInfinite()?d.NAN:this.isInfinite()||c.isInfinite()?d.INFINITY:new d(this.re-c.re,this.im-c.im)},mul:function(a,b){var c=new d(a,b);return this.isInfinite()&&c.isZero()||this.isZero()&&c.isInfinite()? +d.NAN:this.isInfinite()||c.isInfinite()?d.INFINITY:0===c.im&&0===this.im?new d(this.re*c.re,0):new d(this.re*c.re-this.im*c.im,this.re*c.im+this.im*c.re)},div:function(a,b){var c=new d(a,b);if(this.isZero()&&c.isZero()||this.isInfinite()&&c.isInfinite())return d.NAN;if(this.isInfinite()||c.isZero())return d.INFINITY;if(this.isZero()||c.isInfinite())return d.ZERO;a=this.re;b=this.im;var e=c.re,f=c.im;if(0===f)return new d(a/e,b/e);if(Math.abs(e)=a?.5*Math.sqrt(2*(c-a)):Math.abs(b)/Math.sqrt(2*(c+a));return new d(e,0>b?-a:a)},exp:function(){var a=Math.exp(this.re);return new d(a*Math.cos(this.im),a*Math.sin(this.im))},expm1:function(){var a=this.re,b=this.im,c=Math.expm1(a)*Math.cos(b);var e=Math.PI/4;-e>b||b>e?e=Math.cos(b)- +1:(e=b*b,e*=e*(e*(e*(e*(e*(e*(e/20922789888E3-1/87178291200)+1/479001600)-1/3628800)+1/40320)-1/720)+1/24)-.5);return new d(c+e,Math.exp(a)*Math.sin(b))},log:function(){var a=this.re,b=this.im;return new d(p(a,b),Math.atan2(b,a))},abs:function(){var a=this.re;var b=this.im,c=Math.abs(a),e=Math.abs(b);3E3>c&&3E3>e?a=Math.sqrt(c*c+e*e):(c=a.im){var b=a.re;a.re=-a.im;a.im=b}else b=a.im,a.im=-a.re,a.re=b;return a},atanh:function(){var a=this.re,b=this.im,c=1b?(b=-b,c+="-"):c+="+",c+=" "):0>b&&(b=-b,c+="-");1!==b&&(c+=b);return c+"i"},toVector:function(){return[this.re,this.im]},valueOf:function(){return 0===this.im?this.re:null},isNaN:function(){return isNaN(this.re)||isNaN(this.im)},isZero:function(){return 0===this.im&&0===this.re},isFinite:function(){return isFinite(this.re)&&isFinite(this.im)},isInfinite:function(){return!(this.isNaN()||this.isFinite())}}; +d.ZERO=new d(0,0);d.ONE=new d(1,0);d.I=new d(0,1);d.PI=new d(Math.PI,0);d.E=new d(Math.E,0);d.INFINITY=new d(Infinity,Infinity);d.NAN=new d(NaN,NaN);d.EPSILON=1E-15;"function"===typeof define&&define.amd?define([],function(){return d}):"object"===typeof exports?(Object.defineProperty(d,"__esModule",{value:!0}),d["default"]=d,d.Complex=d,module.exports=d):q.Complex=d})(this); \ No newline at end of file diff --git a/node_modules/complex.js/examples/gamma.js b/node_modules/complex.js/examples/gamma.js new file mode 100644 index 0000000..c9cfd6d --- /dev/null +++ b/node_modules/complex.js/examples/gamma.js @@ -0,0 +1,31 @@ +/* + * A gamma function implementation based on Lanczos Approximation + * https://en.wikipedia.org/wiki/Lanczos_approximation + */ + +var Complex = require('../complex'); + +var P = [Complex(0.99999999999980993), + Complex(676.5203681218851), Complex(-1259.1392167224028), Complex(771.32342877765313), + Complex(-176.61502916214059), Complex(12.507343278686905), Complex(-0.13857109526572012), + Complex(9.9843695780195716e-6), Complex(1.5056327351493116e-7)]; + +var SQRT2PI = Complex(Math.sqrt(2 * Math.PI)); + +function gamma(z) { + + z = z.sub(1); + + var x = P[0]; + var t = z.add(7.5); + for (var i = 1; i < P.length; i++) { + x = x.add(P[i].div(z.add(i))); + } + return SQRT2PI.mul(t.pow(z.add(0.5))).mul(t.neg().exp()).mul(x); +} + +var fac = 1; +for (var i = 1; i <= 10; i++) { + console.log(fac, gamma(Complex(i))); + fac *= i; +} diff --git a/node_modules/complex.js/package.json b/node_modules/complex.js/package.json new file mode 100644 index 0000000..455a652 --- /dev/null +++ b/node_modules/complex.js/package.json @@ -0,0 +1,43 @@ +{ + "name": "complex.js", + "homepage": "https://github.com/infusion/Complex.js", + "bugs": "https://github.com/infusion/Complex.js/issues", + "title": "complex.js", + "version": "2.1.1", + "description": "A complex numbers library", + "keywords": [ + "complex numbers", + "math", + "complex", + "number", + "calculus", + "parser", + "arithmetic" + ], + "author": "Robert Eisele (http://www.xarg.org/)", + "main": "complex", + "types": "complex.d.ts", + "private": false, + "directories": { + "example": "examples" + }, + "readmeFilename": "README.md", + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/infusion/Complex.js.git" + }, + "funding": { + "type": "patreon", + "url": "https://www.patreon.com/infusion" + }, + "engines": { + "node": "*" + }, + "scripts": { + "test": "mocha tests/*.js" + }, + "devDependencies": { + "mocha": "*" + } +} diff --git a/node_modules/complex.js/tests/complex.test.js b/node_modules/complex.js/tests/complex.test.js new file mode 100644 index 0000000..c5da22d --- /dev/null +++ b/node_modules/complex.js/tests/complex.test.js @@ -0,0 +1,1066 @@ +var assert = require("assert"); + +var Complex = require("../complex.js"); + +var functionTests = [{ + set: Complex.I, + fn: "mul", + param: Complex(Math.PI).exp(), + expect: "23.140692632779267i" +}, { + set: new Complex(1, 4), + fn: "mul", + param: 3, + expect: "3 + 12i" +}, { + set: "4 + 3i", + fn: "add", + param: "-3 - 2i", + expect: "1 + i" +}, { + set: "3i", + fn: "add", + param: "-2i", + expect: "i" +}, { + set: "4", + fn: "add", + param: "-3", + expect: "1" +}, { + set: 9, + fn: "sqrt", + expect: "3" +}, { + set: -9, + fn: "sqrt", + expect: "3i" +}, { + set: "-36", + fn: "sqrt", + expect: "6i" +}, { + set: "36i", + fn: "sqrt", + expect: "4.242640687119285 + 4.242640687119285i" +}, { + set: Infinity, + fn: "mul", + param: "i", + expect: "Infinity" +}, { + set: "-36i", + fn: "sqrt", + expect: "4.242640687119285 - 4.242640687119285i" +}, { + set: "4 + 2i", + fn: "div", + param: "0", + expect: "Infinity" +}, { + set: "0", + fn: "div", + param: Infinity, + expect: "0" +}, { + set: -Infinity, + fn: "div", + param: 0, + expect: "Infinity" +}, { + set: Infinity, + fn: "div", + param: Infinity, + expect: "NaN" +}, { + set: 0, + fn: "div", + param: 0, + expect: "NaN" +}, { + set: "4 + 2i", + fn: "div", + param: "1 + i", + expect: "3 - i" +}, { + set: "25", + fn: "div", + param: "3 - 4i", + expect: "3 + 4i" +}, { + set: "3 - 2i", + fn: "div", + param: "i", + expect: "-2 - 3i" +}, { + set: "4i", + fn: "mul", + param: "-5i", + expect: "20" +}, { + set: "3 - 6i", + fn: "mul", + param: "i", + expect: "6 + 3i" +}, { + set: Infinity, + fn: "mul", + param: 0, + expect: "NaN" +}, { + set: "3 + 4i", + fn: "add", + param: "5 - 7i", + expect: "8 - 3i" +}, { + set: Infinity, + fn: "add", + param: Infinity, + expect: "NaN" +}, { + set: -Infinity, + fn: "sub", + param: -Infinity, + expect: "NaN" +}, { + set: "6i", + fn: "div", + param: "3 - 12i", + expect: "-0.47058823529411764 + 0.11764705882352941i" +}, { + set: "36 + 36i", + fn: "sqrt", + expect: "6.59210468080686 + 2.730539163373364i" +}, { + set: "36 - 36i", + fn: "sqrt", + expect: "6.59210468080686 - 2.730539163373364i" +}, { + set: "-36 + 36i", + fn: "sqrt", + expect: "2.730539163373364 + 6.59210468080686i" +}, { + set: "-36 - 36i", + fn: "sqrt", + expect: "2.730539163373364 - 6.59210468080686i" +}, { + set: "0", + fn: "sqrt", + expect: "0" +}, { + set: Math.E, + fn: "log", + expect: "1" +}, { + set: 0, + fn: "log", + expect: "Infinity" +}, { + set: Infinity, + fn: "mul", + param: 3, + expect: "Infinity" +}, { + set: "-1", + fn: "log", + expect: Math.PI + "i" +}, { + set: "i", + fn: "log", + expect: (Math.PI / 2) + "i" +}, { + set: "3 + 2i", + fn: "log", + expect: Math.log(13) / 2 + " + " + Math.atan2(2, 3) + "i" +}, { + set: "3 - 2i", + fn: "log", + expect: Math.log(13) / 2 + " - " + Math.atan2(2, 3) + "i" +}, { + set: 1, + fn: "exp", + expect: "" + Math.E +}, { + set: "i", + fn: "exp", + expect: Math.cos(1) + " + " + Math.sin(1) + "i" +}, { + set: "i", + fn: "mul", + param: "i", + expect: "-1" +}, { + set: "3 + 2i", + fn: "exp", + expect: "-8.358532650935372 + 18.263727040666765i" +}, { + set: "3 - 2i", + fn: "exp", + expect: "-8.358532650935372 - 18.263727040666765i" +}, { + set: "3 - 2i", + fn: "expm1", + expect: "-9.358532650935372 - 18.263727040666765i" +}, { + set: "0", + fn: "expm1", + expect: "0" +}, { + set: "1e-6", + fn: "expm1", + expect: "0.0000010000005000001665" +}, { + set: "1e-5 + 5i", + fn: "expm1", + expect: "-0.716334977900736 - 0.9589338639538314i" +}, { + set: "1.2e-7 - 2e-6i", + fn: "expm1", + expect: "1.1999800719976027e-7 - 0.000002000000239998681i" +}, { + set: "3", + fn: "pow", + param: "3", + expect: "27" +}, { + set: -2, + fn: "pow", + param: 1.5, + expect: "-2.82842712474619i" +}, { + set: -8, + fn: "pow", + param: 1 / 3, + expect: "1 + 1.732050807568877i" +}, { + set: -25, + fn: "sqrt", + expect: "5i" +}, { + set: -25, + fn: "pow", + param: 0.5, + expect: "5i" +}, { + set: "0", + fn: "pow", + param: "1+i", + expect: "0" +}, { + set: "i", + fn: "pow", + param: "0", + expect: "1" +}, { + set: "87", + fn: "pow", + param: "3", + expect: "658503" +}, { + set: "i", + fn: "pow", + param: "1", + expect: "i" +}, { + set: "i", + fn: "pow", + param: "2", + expect: "-1" +}, { + set: "i", + fn: "pow", + param: "3", + expect: "-i" +}, { + set: "i", + fn: "pow", + param: "4", + expect: "1" +}, { + set: "i", + fn: "pow", + param: "5", + expect: "i" +}, { + set: 7, + fn: "pow", + param: 2, + expect: '49' +}, { + set: 0, + fn: "pow", + param: 2, + expect: '0' +}, { + set: "3i", + fn: "pow", + param: "3i", + expect: "-0.008876640735623678 - 0.0013801328997494863i" +}, { + set: { re: 3, im: 4 }, + fn: "abs", + expect: "5" +}, { + set: { re: 10, im: 24 }, + fn: "abs", + expect: "26" +}, { + set: "+++++--+1 + 4i", + fn: "mul", + param: "3 + 2i", + expect: "-5 + 14i" +}, { + set: "4 + 16i", + fn: "div", + param: "4.0000", + expect: "1 + 4i" +}, { + set: { re: -7.1, im: 2.5 }, + fn: "neg", + expect: "7.1 - 2.5i" +}, { + set: { re: 1, im: 1 }, + fn: "div", + param: { re: 3, im: 4 }, + expect: 7 / 25 + " - " + 1 / 25 + "i" +}, { + set: new Complex(-7.1, 2.5), + fn: "neg", + expect: "7.1 - 2.5i" +}, { + set: { re: 1, im: 1 }, + fn: "arg", + expect: "" + Math.PI / 4 +}, { + set: { re: -1, im: -1 }, + fn: "arg", + expect: "" + -3 * Math.PI / 4 +}, { + set: { re: 0, im: 1 }, + fn: "arg", + expect: "" + Math.PI / 2 +}, { + set: { re: 1, im: 0.5 * Math.sqrt(4 / 3) }, + fn: "arg", + expect: "" + Math.PI / 6 +}, { + set: "3 + 4i", + fn: "conjugate", + expect: "3 - 4i" +}, { + set: { re: 99, im: 50 }, + fn: "conjugate", + expect: "99 - 50i" +}, { + set: { re: 0, im: 0 }, + fn: "conjugate", + expect: "0" +}, { + set: { re: 1, im: 23 }, + fn: "conjugate", + expect: "1 - 23i" +}, { + set: "2 + 8i", + fn: "div", + param: new Complex(1, 2), + expect: "3.6 + 0.8i" +}, { + set: "2 + 8i", + fn: "div", + param: "2 + 8i", + expect: "1" +}, { + set: -Infinity, + fn: "div", + param: 3, + expect: "Infinity" +}, { + set: "3+4i", + fn: "add", + param: "5 - i", + expect: "8 + 3i" +}, { + set: { re: 1, im: 2 }, + fn: "add", + param: "4 + 6i", + expect: "5 + 8i" +}, { + set: { re: 5, im: 8 }, + fn: "sub", + param: "4 + 6i", + expect: "1 + 2i" +}, { + set: "3 + 4i", + fn: "sub", + param: "2 - 5i", + expect: "1 + 9i" +}, { + set: "1 + 2i", + fn: "pow", + param: "2", + expect: "-2.999999999999999 + 4.000000000000001i" +}, { + set: "1 + 2i", + fn: "pow", + param: "1 + 2i", + expect: "-0.22251715680177267 + 0.10070913113607541i" +}, { + set: { re: 1, im: 2 }, + fn: "pow", + param: new Complex(3, 4), + expect: "0.1290095940744669 + 0.03392409290517001i" +}, { + fn: "abs", + set: new Complex(3, 4), + expect: "5" +}, { + param: 2, + fn: "pow", + set: new Complex(1, 2), + expect: "-2.999999999999999 + 4.000000000000001i" +}, { + set: "i", + fn: "pow", + param: 7, + expect: "-i" +}, { + set: "2+3i", + fn: "mul", + param: "4+5i", + expect: "-7 + 22i" +}, { + set: "3 + 4i", + fn: "mul", + param: "2 - 5i", + expect: "26 - 7i" +}, { + set: "i", + fn: "pow", + param: 4, + expect: "1" +}, { + set: "i", + fn: "pow", + param: 5, + expect: "i" +}, { + set: "0-0i", + fn: "pow", + param: 2, + expect: "0" +}, { + set: "0-0i", + fn: "pow", + param: 0, + expect: "1" +}, { + set: "1 + 4i", + fn: "sqrt", + expect: "1.600485180440241 + 1.2496210676876531i" +}, { + set: { re: -3, im: 4 }, + fn: "sqrt", + expect: "1 + 2i" +}, { + set: { re: 3, im: -4 }, + fn: "sqrt", + expect: "2 - i" +}, { + set: { re: -3, im: -4 }, + fn: "sqrt", + expect: "1 - 2i" +}, { + set: [-2, 0], + fn: "pow", + param: 2, + expect: "4" +}, { + set: { abs: 1, arg: 0 }, + fn: "equals", + param: { re: 1, im: 0 }, + expect: "true" +}, { + set: -Complex.E.pow(2), + fn: "log", + expect: "2 + 3.141592653589793i" +}, { + set: "4 + 3i", + fn: "log", + expect: "1.6094379124341003 + 0.6435011087932844i" +}, { + set: "4 + 3i", + fn: "exp", + expect: "-54.051758861078156 + 7.704891372731154i" +}, { + set: "1-2i", + fn: "sqrt", + expect: "1.272019649514069 - 0.7861513777574233i" +}, { + set: { re: 1, im: 2 }, + fn: "sin", + expect: "3.165778513216168 + 1.9596010414216063i" +}, { + set: "i", + fn: "cos", + expect: "1.5430806348152437" +}, { + set: "i", + fn: "acos", + expect: "1.5707963267948966 - 0.8813735870195428i" +}, { + set: { re: 1, im: 2 }, + fn: "cos", + expect: "2.0327230070196656 - 3.0518977991518i" +}, { + set: { re: 1, im: 2 }, + fn: "tan", + expect: "0.03381282607989669 + 1.0147936161466335i" +}, { + set: { re: 1, im: 3 }, + fn: "sinh", + expect: "-1.1634403637032504 + 0.21775955162215221i" +}, { + set: { re: 1, im: 3 }, + fn: "cosh", + expect: "-1.5276382501165433 + 0.1658444019189788i" +}, { + set: { re: 1, im: 3 }, + fn: "tanh", + expect: "0.7680176472869112 - 0.059168539566050726i" +}, { + set: { re: 1, im: 3 }, + fn: "inverse", + expect: "0.1 - 0.3i" +}, { + set: "3+4i", + fn: "inverse", + expect: "0.12 - 0.16i" // 3/25 - (4/25)i +}, { + set: { re: 0.5, im: -0.5 }, + fn: "inverse", + expect: "1 + i" +}, { + set: "1 + i", + fn: "inverse", + expect: "0.5 - 0.5i" +}, { + set: "0", + fn: "inverse", + expect: "Infinity" +}, { + set: Infinity, + fn: "inverse", + expect: "0" +}, { + set: Complex['EPSILON'], + fn: "equals", + param: 1e-16, + expect: "true" +}, { + set: 0, + fn: "equals", + param: "5i", + expect: "false" +}, { + set: 5, + fn: "equals", + param: "5i", + expect: "false" +}, { + set: 5, + fn: "equals", + param: 5, + expect: "true" +}, { + set: "10i", + fn: "equals", + param: "10i", + expect: "true" +}, { + set: "2 + 3i", + fn: "equals", + param: "2 + 3i", + expect: "true" +}, { + set: "2 + 3i", + fn: "equals", + param: "5i", + expect: "false" +}, { + set: "2 + 3i", + fn: "round", + param: "0", + expect: "2 + 3i" +}, { + set: "2.5 + 3.5i", + fn: "round", + param: "1", + expect: "2.5 + 3.5i" +}, { + set: "2.5 + 3.5i", + fn: "sign", + param: null, + expect: "0.5812381937190965 + 0.813733471206735i" +}, { + set: "10 + 24i", + fn: "sign", + param: null, + expect: "0.38461538461538464 + 0.9230769230769231i" +}, { + set: "1e3i", + fn: "add", + param: "3e-3 + 1e2i", + expect: "0.003 + 1100i" +}, { + set: "3.14-4i", + fn: "coth", + expect: "0.9994481238383576 + 0.0037048958915019857i" +}, { + set: "8i-31", + fn: "cot", + expect: "1.6636768291213935e-7 - 1.0000001515864902i" +}, { + set: Complex(1, 1).sub(0, 1), // Distance + fn: "abs", + expect: "1" +}, { + set: Complex(1, 1), // Rotate around center + fn: "mul", + param: { abs: 1, arg: Math.PI / 2 }, + expect: "-0.9999999999999999 + i" +}, { + set: Complex(1, 1).sub(0, 1).mul({ abs: 1, arg: Math.PI / 2 }), // Rotate around another point + fn: "add", + param: "i", + expect: "2i" +}, { + set: Complex(0, 10000000000), + fn: "log", + param: null, + expect: "23.025850929940457 + 1.5707963267948966i" +}, { + set: Complex(0, 1000000000000000), + fn: "log", + param: null, + expect: "34.538776394910684 + 1.5707963267948966i" +}, { + set: Complex(0, 100000000000000000), + fn: "log", + param: null, + expect: "39.14394658089878 + 1.5707963267948966i" +}, { + set: Complex(0, 10000000000000000000), + fn: "log", + param: null, + expect: "43.74911676688687 + 1.5707963267948966i" +}, { + set: Complex(0, 1e+30), + fn: "log", + param: null, + expect: "69.07755278982137 + 1.5707963267948966i" +}, { + set: Complex(1, 10000000000), + fn: "log", + param: null, + expect: "23.025850929940454 + 1.5707963266948965i" +}, { + set: Complex(1, 1000000000000000), + fn: "log", + param: null, + expect: "34.538776394910684 + 1.5707963267948957i" +}, { + set: Complex(1, 100000000000000000), + fn: "log", + param: null, + expect: "39.14394658089878 + 1.5707963267948966i" +}, { + set: Complex(1, 10000000000000000000), + fn: "log", + param: null, + expect: "43.74911676688687 + 1.5707963267948966i" +}, { + set: Complex(1, 1e+30), + fn: "log", + param: null, + expect: "69.07755278982137 + 1.5707963267948966i" +}, { + set: Complex(-1, 10000000000), + fn: "log", + param: null, + expect: "23.025850929940454 + 1.5707963268948968i" +}, { + set: Complex(-1, 1000000000000000), + fn: "log", + param: null, + expect: "34.538776394910684 + 1.5707963267948977i" +}, { + set: Complex(-1, 100000000000000000), + fn: "log", + param: null, + expect: "39.14394658089878 + 1.5707963267948968i" +}, { + set: Complex(-1, 10000000000000000000), + fn: "log", + param: null, + expect: "43.74911676688687 + 1.5707963267948966i" +}, { + set: Complex(-1, 1e+30), + fn: "log", + param: null, + expect: "69.07755278982137 + 1.5707963267948966i" +}]; + +var constructorTests = [{ + set: null, + expect: "0" +}, { + set: undefined, + expect: "0" +}, { + set: "foo", + error: "SyntaxError: Invalid Param" +}, { + set: {}, + error: "SyntaxError: Invalid Param" +}, { + set: " + i", + expect: "i" +}, { + set: "3+4i", + expect: "3 + 4i" +}, { + set: "i", + expect: "i" +}, { + set: "3", + expect: "3" +}, { + set: [9, 8], + expect: "9 + 8i" +}, { + set: "2.3", + expect: "2.3" +}, { + set: "2.3", + expect: "2.3" +}, { + set: "0", + expect: "0" +}, { + set: "-0", + expect: "0" +}, { + set: { re: -0, im: 0 }, + expect: "0" +}, { + set: { re: 0, im: -0 }, + expect: "0" +}, { + set: Infinity, + expect: "Infinity" +}, { + set: -Infinity, + expect: "Infinity" +}, { + set: { re: Infinity, im: 0 }, + expect: "Infinity" +}, { + set: { re: -Infinity, im: 0 }, + expect: "Infinity" +}, { + set: { re: 0, im: Infinity }, + expect: "Infinity" +}, { + set: { re: 0, im: -Infinity }, + expect: "Infinity" +}, { + set: " + 7 - i + 3i - + + + + 43 + 2i - i4 + - 33 + 65 - 1 ", + expect: "-5" +}, { + set: " + 7 - i + 3i - + + + + 43 + 2i - i4 + - 33 + 65 - 1 + ", + error: "SyntaxError: Invalid Param" +}, { + set: "-3x + 4", + error: "SyntaxError: Invalid Param" +}, { + set: "- + 7", + expect: "-7" +}, { + set: "4 5i", + error: "SyntaxError: Invalid Param" +}, { + set: "-", + error: "SyntaxError: Invalid Param" +}, { + set: "2.2e-1-3.2e-1i", + expect: "0.22 - 0.32i" +}, { + set: "2.2.", + error: "SyntaxError: Invalid Param" +}, { + set: { r: 0, phi: 4 }, + expect: "0" +}, { + set: { r: 1, phi: 1 }, + expect: "0.5403023058681398 + 0.8414709848078965i" +}, { + set: { r: Infinity, phi: 0 }, + expect: "Infinity" +}, { + set: { r: Infinity, phi: 2 }, + expect: "Infinity" +}, { + set: { r: Infinity, phi: Infinity }, + expect: "NaN" +}, { + set: { r: Infinity, phi: NaN }, + expect: "NaN" +} +]; + +for (let i = 0, len = constructorTests.length; i < len; ++i) { + if (constructorTests[i].set != null && constructorTests[i].set.hasOwnProperty('r')) { + constructorTests.push({ + set: { + abs: constructorTests[i].set.r, + arg: constructorTests[i].set.phi, + }, + expect: constructorTests[i].expect + }) + } +} + + +function stringify(value) { + return JSON.stringify(value, function replacer(key, val) { + if (typeof val === "number") { + return val.toString(); + } + return val; + }) +} + +function describeTest(test) { + var ctor = "new Complex(" + (test.set !== undefined ? stringify(test.set) : "") + ")"; + + var fnCall = test.fn == null + ? "" + : "." + test.fn + "(" + (test.param !== undefined ? stringify(test.param) : "") + ")"; + + var expectedResult = test.expect == null + ? "" + : " === " + stringify(test.expect); + + var error = test.error == null + ? "" + : " should throw " + test.error; + + return ctor + fnCall + expectedResult + error; +} + +describe("Complex functions", function () { + + for (var i = 0; i < functionTests.length; i++) { + + (function (test) { + + it(describeTest(test), function () { + if (test.error) { + try { + new Complex(test.set)[test.fn](test.param); + } catch (e) { + assert.strictEqual(e.toString(), test.error.toString()); + } + } else { + assert.strictEqual(new Complex(test.set)[test.fn](test.param).toString(), test.expect); + } + }); + })(functionTests[i]); + } +}); + +describe("Complex constructor", function () { + + for (var i = 0; i < constructorTests.length; i++) { + + (function (test) { + it(describeTest(test), function () { + if (test.error) { + try { + new Complex(test.set); + } catch (e) { + assert.strictEqual(e.toString(), test.error.toString()); + } + } else { + assert.strictEqual(new Complex(test.set).toString(), test.expect); + } + }); + })(constructorTests[i]); + } +}); + +describe("Complex Details", function () { + + it("should work with different params", function () { + assert.strictEqual(Complex(1, -1).toString(), "1 - i"); + assert.strictEqual(Complex(0, 0).toString(), "0"); + assert.strictEqual(Complex(0, 2).toString(), "2i"); + assert.strictEqual(Complex.I.toString(), "i"); + assert.strictEqual(Complex(0, -2).toString(), "-2i"); + assert.strictEqual(Complex({ re: 0, im: -2 }).toString(), "-2i"); + }); + + it("Complex Combinations", function () { + + var zero = Complex(0, 0), one = Complex(1, 1), two = Complex(2, 2); + + assert.strictEqual(zero.toString(), "0"); + assert.strictEqual(one.toString(), "1 + i"); + assert(one.neg().equals(Complex(-1, -1))); + assert(one.conjugate().equals(Complex(1, -1))); + assert.strictEqual(one.abs(), Math.SQRT2); + assert.strictEqual(one.arg(), Math.PI / 4); + assert.strictEqual(one.add(one).toString(), two.toString()); + assert.strictEqual(one.sub(one).toString(), zero.toString()); + assert.strictEqual(one.mul(2).toString(), two.toString()); + assert.strictEqual(one.mul(one).toString(), Complex(0, 2).toString()); + assert.strictEqual(one.div(2).toString(), "0.5 + 0.5i"); + assert.strictEqual(one.div(one).toString(), "1"); + assert.strictEqual(one.div(0).toString(), "Infinity"); + assert.strictEqual(one.exp().toString(), "1.4686939399158851 + 2.2873552871788423i"); + assert.strictEqual(one.log().toString(), "0.34657359027997264 + 0.7853981633974483i"); + assert.strictEqual(one.pow(one).toString(), "0.2739572538301211 + 0.5837007587586147i"); + assert.strictEqual(one.pow(zero).toString(), "1"); + assert.strictEqual(one.sqrt().toString(), "1.09868411346781 + 0.45508986056222733i"); + assert.strictEqual(one.sin().toString(), "1.2984575814159773 + 0.6349639147847361i"); + assert.strictEqual(one.cos().toString(), "0.8337300251311491 - 0.9888977057628651i"); + assert.strictEqual(one.tan().toString(), "0.27175258531951174 + 1.0839233273386948i"); + assert.strictEqual(one.asin().toString(), "0.6662394324925153 + 1.0612750619050355i"); + assert.strictEqual(one.acos().toString(), "0.9045568943023813 - 1.0612750619050355i"); + assert.strictEqual(one.atan().toString(), "1.0172219678978514 + 0.40235947810852507i"); + + assert.strictEqual(Complex(3, 4).abs(), 5); + + assert.strictEqual(Complex("5i + 3").log().exp().toString(), "3 + 5i") + assert.strictEqual(Complex("-2i - 1").log().exp().toString(), "-1 - 2i") + }); + + it("should calculate distributed conjugate", function () { + + var c1 = Complex(7, 3); + var c2 = Complex(1, 2); + + var r1 = c1.add(c2).conjugate(); + var r2 = c1.conjugate().add(c2.conjugate()); + + assert.strictEqual(r1.toString(), r2.toString()); + }); + + it("should be raised to power of 6", function () { + var c1 = Complex(2, 2); + + var t = c1.pow(6); + + assert.strictEqual(t.toString(), "-9.405287417451663e-14 - 511.9999999999995i"); + }); + + it("should handle inverse trig fns", function () { + + var values = [ + new Complex(2.3, 1.4), + new Complex(-2.3, 1.4), + new Complex(-2.3, -1.4), + new Complex(2.3, -1.4)]; + + var fns = ['sin', 'cos', 'tan']; + + for (var i = 0; i < values.length; i++) { + + for (var j = 0; j < 3; j++) { + + var a = values[i]['a' + fns[j]]()[fns[j]](); + + var res = values[i]; + + assert(Math.abs(a.re - res.re) < 1e-12 && Math.abs(a.im - res.im) < 1e-12); + } + } + }); + + it('should handle get real part', function () { + assert.strictEqual(Complex({ abs: 1, arg: Math.PI / 4 }).re, Math.SQRT2 / 2); + }); + + it('should handle get complex part', function () { + assert.strictEqual(Complex({ abs: 1, arg: Math.PI / 4 }).im, 0.7071067811865475); + }); + + it('should handle sum', function () { + assert.strictEqual(Complex({ abs: 1, arg: 0 }).add({ abs: 1, arg: Math.PI / 2 }).abs(), Math.SQRT2); + assert.strictEqual(Complex({ abs: 1, arg: 0 }).add({ abs: 1, arg: Math.PI / 2 }).arg(), Math.PI / 4); + }); + + it('should handle conjugate', function () { + assert.strictEqual(Complex({ abs: 1, arg: Math.PI / 4 }).conjugate().toString(), Complex({ abs: 1, arg: -Math.PI / 4 }).toString()); + }); + + it('should handle substract', function () { + assert.strictEqual(Complex({ abs: 1, arg: 0 }).sub({ abs: 1, arg: Math.PI / 2 }).abs().toString(), "1.414213562373095"); + assert.strictEqual(Complex({ abs: 1, arg: 0 }).sub({ abs: 1, arg: Math.PI / 2 }).arg().toString(), "-0.7853981633974484"); + }); + + it('should handle arg for the first quadrant', function () { + assert.strictEqual(Complex({ re: 1, im: 1 }).arg(), Math.PI / 4); + }); + + it('should handle arg for the second quadrant', function () { + assert.strictEqual(Complex({ re: -1, im: 1 }).arg(), 3 * Math.PI / 4); + }); + + it('should handle arg for the third quadrant', function () { + assert.strictEqual(Complex({ re: -1, im: -1 }).arg(), -3 * Math.PI / 4); + }); + + it('should handle arg for the fourth quadrant', function () { + assert.strictEqual(Complex({ re: 1, im: -1 }).arg(), -Math.PI / 4); + }); + + it('should handle arg for the fourth and first quadrant', function () { + assert.strictEqual(Complex({ re: 1, im: 0 }).arg(), 0); + }); + + it('should handle arg for first and second quadrant', function () { + assert.strictEqual(Complex({ re: 0, im: 1 }).arg(), Math.PI / 2); + }); + + it('should handle arg for the second and third quadrant', function () { + assert.strictEqual(Complex({ re: -1, im: 0 }).arg(), Math.PI); + }); + + it('should handle arg for the third and fourth quadrant', function () { + assert.strictEqual(Complex({ re: 0, im: -1 }).arg(), -Math.PI / 2); + }); + + it("should eat its own dog food", function () { + + var a = Complex(1, -5).toString(); + var b = Complex(a).toString(); + var c = Complex(b).mul(a); + + assert.strictEqual(c.toString(), '-24 - 10i'); + }); + + it("should calculate the absolute value of i", function () { + + var a = Complex("i").sign().inverse().mul("i"); + + assert.strictEqual(a.toString(), '1'); + }); + + it('should take the natural logarithm', function () { + var n = Complex(Math.E * Math.E).log().div("i").mul(-Math.PI * 2, 1); + + assert.strictEqual(n.toString(), '2 + ' + 4 * Math.PI + "i"); + }); + +}); diff --git a/node_modules/decimal.js/CHANGELOG.md b/node_modules/decimal.js/CHANGELOG.md new file mode 100644 index 0000000..cb4f59f --- /dev/null +++ b/node_modules/decimal.js/CHANGELOG.md @@ -0,0 +1,231 @@ +#### 10.3.1 +* 25/06/2021 +* Remove minified versions. Refresh *README*. + +#### 10.3.0 +* 22/06/2021 +* Support underscores as separators. +* #101 Add `Decimal.clamp` method. +* #161 Fix Decimal instances deemed plain objects. +* #100 Add `Decimal.sum` method. +* #146 `Symbol.for` to `Symbol['for']` for IE8. +* #132 Fix possible infinite loop when `minE` is very low. +* #180 Accept Decimals of different origin. +* Update Typescript definitions. +* Update minification examples in *README*. +* Add minified versions for both *decimal.js* and *decimal.mjs*. +* Add *files* field to *package.json*, and remove build script. + +#### 10.2.1 +* 28/09/2020 +* Correct `sqrt` initial estimate. + +#### 10.2.0 +* 08/05/2019 +* #128 Workaround V8 `Math.pow` change. +* #93 Accept `+` prefix when parsing string values. +* #129 Fix typo. + +#### 10.1.1 +* 27/02/2019 +* Check `Symbol` properly. + +#### 10.1.0 +* 26/02/2019 +* #122 Add custom `util.inspect()` function. +* Add `Symbol.toStringTag`. +* #121 Constructor: add range check for arguments of type number and Decimal. +* Remove premable from uglifyjs build script. +* Move *decimal.min.js.map* to root directory. + +#### 10.0.2 +* 13/12/2018 +* #114 Remove soureMappingURL from *decimal.min.js*. +* Remove *bower.json*. + +#### 10.0.1 +* 24/05/2018 +* Add `browser` field to *package.json*. + +#### 10.0.0 +* 10/03/2018 +* #88 `toNearest` to return the nearest multiple in the direction of the rounding mode. +* #82 #91 `const` to `var`. +* Add trigonometric precision limit explanantion to documentation. +* Put global ts definitions in separate file (see *bignumber.js* #143). + +#### 9.0.1 +* 15/12/2017 +* #80 Typings: correct return type. + +#### 9.0.0 +* 14/12/2017 +* #78 Typings: remove `toFormat`. + +#### 8.0.0 +* 10/12/2017 +* Correct typings: `toFraction` returns `Decimal[]`. +* Type-checking: add `Decimal.isDecimal` method. +* Enable configuration reset with `defaults: true`. +* Add named export, Decimal, to *decimal.mjs*. + +#### 7.5.1 +* 03/12/2017 +* Remove typo. + +#### 7.5.0 +* 03/12/2017 +* Use TypeScript declarations outside modules. + +#### 7.4.0 +* 25/11/2017 +* Add TypeScript typings. + +#### 7.3.0 +* 26/09/2017 +* Rename *decimal.es6.js* to *decimal.mjs*. +* Amend *.travis.yml*. + +#### 7.2.4 +* 09/09/2017 +* Update docs regarding `global.crypto`. +* Fix `import` issues. + +#### 7.2.3 +* 27/06/2017 +* Bugfix: #58 `pow` sometimes throws when result is `Infinity`. + +#### 7.2.2 +* 25/06/2017 +* Bugfix: #57 Powers of -1 for integers over `Number.MAX_SAFE_INTEGER`. + +#### 7.2.1 +* 04/05/2017 +* Fix *README* badges. + +#### 7.2.0 +* 09/04/2017 +* Add *decimal.es6.js* + +#### 7.1.2 +* 05/04/2017 +* `Decimal.default` to `Decimal['default']` IE8 issue + +#### 7.1.1 +* 10/01/2017 +* Remove duplicated for-loop +* Minor refactoring + +#### 7.1.0 +* 09/11/2016 +* Support ES6 imports. + +#### 7.0.0 +* 09/11/2016 +* Remove `require('crypto')` - leave it to the user +* Default `Decimal.crypto` to `false` +* Add `Decimal.set` as `Decimal.config` alias + +#### 6.0.0 +* 30/06/2016 +* Removed base-88 serialization format +* Amended `toJSON` and removed `Decimal.fromJSON` accordingly + +#### 5.0.8 +* 09/03/2016 +* Add newline to single test results +* Correct year + +#### 5.0.7 +* 29/02/2016 +* Add decimal.js-light link +* Remove outdated example from docs + +#### 5.0.6 +* 22/02/2016 +* Add bower.json + +#### 5.0.5 +* 20/02/2016 +* Bugfix: #26 wrong precision applied + +#### 5.0.4 +* 14/02/2016 +* Bugfix: #26 clone + +#### 5.0.3 +* 06/02/2016 +* Refactor tests + +#### 5.0.2 +* 05/02/2016 +* Added immutability tests +* Minor *decimal.js* clean-up + +#### 5.0.1 +* 28/01/2016 +* Bugfix: #20 cos mutates value +* Add pi info to docs + +#### 5.0.0 +* 25/01/2016 +* Added trigonometric functions and `cubeRoot` method +* Added most of JavaScript's `Math` object methods as Decimal methods +* Added `toBinary`, `toHexadecimal` and `toOctal` methods +* Added `isPositive` method +* Removed the 15 significant digit limit for numbers +* `toFraction` now returns an array of two Decimals, not two strings +* String values containing whitespace or a plus sign are no longer accepted +* `valueOf` now returns `'-0'` for minus zero +* `comparedTo` now returns `NaN` not `null` for comparisons with `NaN` +* `Decimal.max` and `Decimal.min` no longer accept an array +* The Decimal constructor and `toString` no longer accept a base argument +* Binary, hexadecimal and octal prefixes are now recognised for string values +* Removed `Decimal.errors` configuration property +* Removed `toFormat` method +* Removed `Decimal.ONE` +* Renamed `exponential` method to `naturalExponential` +* Renamed `Decimal.constructor` method to `Decimal.clone` +* Simplified error handling and amended error messages +* Refactored the test suite +* `Decimal.crypto` is now `undefined` by default, and the `crypto` object will be used if available +* Major internal refactoring +* Removed *bower.json* + +#### 4.0.2 +* 20/02/2015 Add bower.json. Add source map. Amend travis CI. Amend doc/comments + +#### 4.0.1 +* 11/12/2014 Assign correct constructor when duplicating a Decimal + +#### 4.0.0 +* 10/11/2014 `toFormat` amended to use `Decimal.format` object for more flexible configuration + +#### 3.0.1 +* 8/06/2014 Surround crypto require in try catch. See issue #5 + +#### 3.0.0 +* 4/06/2014 `random` simplified. Major internal changes mean the properties of a Decimal must now be considered read-only + +#### 2.1.0 +* 4/06/2014 Amend UMD + +#### 2.0.3 +* 8/05/2014 Fix NaN toNumber + +#### 2.0.2 +* 30/04/2014 Correct doc links + +#### 2.0.1 +* 10/04/2014 Update npmignore + +#### 2.0.0 +* 10/04/2014 Add `toSignificantDigits` +* Remove `toInteger` +* No arguments to `ceil`, `floor`, `round` and `trunc` + +#### 1.0.1 +* 07/04/2014 Minor documentation clean-up + +#### 1.0.0 +* 02/04/2014 Initial release diff --git a/node_modules/decimal.js/LICENCE.md b/node_modules/decimal.js/LICENCE.md new file mode 100644 index 0000000..ead2f60 --- /dev/null +++ b/node_modules/decimal.js/LICENCE.md @@ -0,0 +1,23 @@ +The MIT Licence. + +Copyright (c) 2021 Michael Mclaughlin + +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. + diff --git a/node_modules/decimal.js/README.md b/node_modules/decimal.js/README.md new file mode 100644 index 0000000..3bc5c94 --- /dev/null +++ b/node_modules/decimal.js/README.md @@ -0,0 +1,246 @@ +![decimal.js](https://raw.githubusercontent.com/MikeMcl/decimal.js/gh-pages/decimaljs.png) + +An arbitrary-precision Decimal type for JavaScript. + +[![npm version](https://img.shields.io/npm/v/decimal.js.svg)](https://www.npmjs.com/package/decimal.js) +[![npm downloads](https://img.shields.io/npm/dw/decimal.js)](https://www.npmjs.com/package/decimal.js) +[![Build Status](https://travis-ci.org/MikeMcl/decimal.js.svg)](https://travis-ci.org/MikeMcl/decimal.js) +[![CDNJS](https://img.shields.io/cdnjs/v/decimal.js.svg)](https://cdnjs.com/libraries/decimal.js) + +
+ +## Features + + - Integers and floats + - Simple but full-featured API + - Replicates many of the methods of JavaScript's `Number.prototype` and `Math` objects + - Also handles hexadecimal, binary and octal values + - Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal + - No dependencies + - Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only + - Comprehensive [documentation](https://mikemcl.github.io/decimal.js/) and test set + - Used under the hood by [math.js](https://github.com/josdejong/mathjs) + - Includes a TypeScript declaration file: *decimal.d.ts* + +![API](https://raw.githubusercontent.com/MikeMcl/decimal.js/gh-pages/API.png) + +The library is similar to [bignumber.js](https://github.com/MikeMcl/bignumber.js/), but here +precision is specified in terms of significant digits rather than decimal places, and all +calculations are rounded to the precision (similar to Python's decimal module) rather than just +those involving division. + +This library also adds the trigonometric functions, among others, and supports non-integer powers, +which makes it a significantly larger library than *bignumber.js* and the even smaller +[big.js](https://github.com/MikeMcl/big.js/). + +For a lighter version of this library without the trigonometric functions see +[decimal.js-light](https://github.com/MikeMcl/decimal.js-light/). + +## Load + +The library is the single JavaScript file *decimal.js* or ES module *decimal.mjs*. + +Browser: + +```html + + + +``` + +[Node.js](https://nodejs.org): + +```bash +npm install decimal.js +``` +```js +const Decimal = require('decimal.js'); + +import Decimal from 'decimal.js'; + +import {Decimal} from 'decimal.js'; +``` + +## Use + +*In all examples below, semicolons and `toString` calls are not shown. +If a commented-out value is in quotes it means `toString` has been called on the preceding expression.* + +The library exports a single constructor function, `Decimal`, which expects a single argument that is a number, string or Decimal instance. + +```js +x = new Decimal(123.4567) +y = new Decimal('123456.7e-3') +z = new Decimal(x) +x.equals(y) && y.equals(z) && x.equals(z) // true +``` + +If using values with more than a few digits, it is recommended to pass strings rather than numbers to avoid a potential loss of precision. + +```js +// Precision loss from using numeric literals with more than 15 significant digits. +new Decimal(1.0000000000000001) // '1' +new Decimal(88259496234518.57) // '88259496234518.56' +new Decimal(99999999999999999999) // '100000000000000000000' + +// Precision loss from using numeric literals outside the range of Number values. +new Decimal(2e+308) // 'Infinity' +new Decimal(1e-324) // '0' + +// Precision loss from the unexpected result of arithmetic with Number values. +new Decimal(0.7 + 0.1) // '0.7999999999999999' +``` + +As with JavaScript numbers, strings can contain underscores as separators to improve readability. + +```js +x = new Decimal('2_147_483_647') +``` + +String values in binary, hexadecimal or octal notation are also accepted if the appropriate prefix is included. + +```js +x = new Decimal('0xff.f') // '255.9375' +y = new Decimal('0b10101100') // '172' +z = x.plus(y) // '427.9375' + +z.toBinary() // '0b110101011.1111' +z.toBinary(13) // '0b1.101010111111p+8' + +// Using binary exponential notation to create a Decimal with the value of `Number.MAX_VALUE`. +x = new Decimal('0b1.1111111111111111111111111111111111111111111111111111p+1023') +// '1.7976931348623157081e+308' +``` + +Decimal instances are immutable in the sense that they are not changed by their methods. + +```js +0.3 - 0.1 // 0.19999999999999998 +x = new Decimal(0.3) +x.minus(0.1) // '0.2' +x // '0.3' +``` + +The methods that return a Decimal can be chained. + +```js +x.dividedBy(y).plus(z).times(9).floor() +x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').ceil() +``` + +Many method names have a shorter alias. + +```js +x.squareRoot().dividedBy(y).toPower(3).equals(x.sqrt().div(y).pow(3)) // true +x.comparedTo(y.modulo(z).negated() === x.cmp(y.mod(z).neg()) // true +``` + +Most of the methods of JavaScript's `Number.prototype` and `Math` objects are replicated. + +```js +x = new Decimal(255.5) +x.toExponential(5) // '2.55500e+2' +x.toFixed(5) // '255.50000' +x.toPrecision(5) // '255.50' + +Decimal.sqrt('6.98372465832e+9823') // '8.3568682281821340204e+4911' +Decimal.pow(2, 0.0979843) // '1.0702770511687781839' + +// Using `toFixed()` to avoid exponential notation: +x = new Decimal('0.0000001') +x.toString() // '1e-7' +x.toFixed() // '0.0000001' +``` + +And there are `isNaN` and `isFinite` methods, as `NaN` and `Infinity` are valid `Decimal` values. + +```js +x = new Decimal(NaN) // 'NaN' +y = new Decimal(Infinity) // 'Infinity' +x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true +``` + +There is also a `toFraction` method with an optional *maximum denominator* argument. + +```js +z = new Decimal(355) +pi = z.dividedBy(113) // '3.1415929204' +pi.toFraction() // [ '7853982301', '2500000000' ] +pi.toFraction(1000) // [ '355', '113' ] +``` + +All calculations are rounded according to the number of significant digits and rounding mode specified +by the `precision` and `rounding` properties of the Decimal constructor. + +For advanced usage, multiple Decimal constructors can be created, each with their own independent +configuration which applies to all Decimal numbers created from it. + +```js +// Set the precision and rounding of the default Decimal constructor +Decimal.set({ precision: 5, rounding: 4 }) + +// Create another Decimal constructor, optionally passing in a configuration object +Dec = Decimal.clone({ precision: 9, rounding: 1 }) + +x = new Decimal(5) +y = new Dec(5) + +x.div(3) // '1.6667' +y.div(3) // '1.66666666' +``` + +The value of a Decimal is stored in a floating point format in terms of its digits, exponent and sign, but these properties should be considered read-only. + +```js +x = new Decimal(-12345.67); +x.d // [ 12345, 6700000 ] digits (base 10000000) +x.e // 4 exponent (base 10) +x.s // -1 sign +``` + +For further information see the [API](http://mikemcl.github.io/decimal.js/) reference in the *doc* directory. + +## Test + +To run the tests using Node.js from the root directory: + +```bash +npm test +``` + +Each separate test module can also be executed individually, for example: + +```bash +node test/modules/toFraction +``` + +To run the tests in a browser, open *test/test.html*. + +## Minify + +Two minification examples: + +Using [uglify-js](https://github.com/mishoo/UglifyJS) to minify the *decimal.js* file: + +```bash +npm install uglify-js -g +uglifyjs decimal.js --source-map url=decimal.min.js.map -c -m -o decimal.min.js +``` + +Using [terser](https://github.com/terser/terser) to minify the ES module version, *decimal.mjs*: + +```bash +npm install terser -g +terser decimal.mjs --source-map url=decimal.min.mjs.map -c -m --toplevel -o decimal.min.mjs +``` + +```js +import Decimal from './decimal.min.mjs'; +``` + +## Licence + +[The MIT Licence (Expat).](LICENCE.md) diff --git a/node_modules/decimal.js/decimal.d.ts b/node_modules/decimal.js/decimal.d.ts new file mode 100644 index 0000000..4539dbe --- /dev/null +++ b/node_modules/decimal.js/decimal.d.ts @@ -0,0 +1,300 @@ +// Type definitions for decimal.js >=7.0.0 +// Project: https://github.com/MikeMcl/decimal.js +// Definitions by: Michael Mclaughlin +// Definitions: https://github.com/MikeMcl/decimal.js +// +// Documentation: http://mikemcl.github.io/decimal.js/ +// +// Exports: +// +// class Decimal (default export) +// type Decimal.Constructor +// type Decimal.Instance +// type Decimal.Modulo +// type Decimal.Rounding +// type Decimal.Value +// interface Decimal.Config +// +// Example (alternative syntax commented-out): +// +// import {Decimal} from "decimal.js" +// //import Decimal from "decimal.js" +// +// let r: Decimal.Rounding = Decimal.ROUND_UP; +// let c: Decimal.Configuration = {precision: 4, rounding: r}; +// Decimal.set(c); +// let v: Decimal.Value = '12345.6789'; +// let d: Decimal = new Decimal(v); +// //let d: Decimal.Instance = new Decimal(v); +// +// The use of compiler option `--strictNullChecks` is recommended. + +export default Decimal; + +export namespace Decimal { + export type Constructor = typeof Decimal; + export type Instance = Decimal; + export type Rounding = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + export type Modulo = Rounding | 9; + export type Value = string | number | Decimal; + + // http://mikemcl.github.io/decimal.js/#constructor-properties + export interface Config { + precision?: number; + rounding?: Rounding; + toExpNeg?: number; + toExpPos?: number; + minE?: number; + maxE?: number; + crypto?: boolean; + modulo?: Modulo; + defaults?: boolean; + } +} + +export declare class Decimal { + readonly d: number[]; + readonly e: number; + readonly s: number; + private readonly toStringTag: string; + + constructor(n: Decimal.Value); + + absoluteValue(): Decimal; + abs(): Decimal; + + ceil(): Decimal; + + clampedTo(min: Decimal.Value, max: Decimal.Value): Decimal; + clamp(min: Decimal.Value, max: Decimal.Value): Decimal; + + comparedTo(n: Decimal.Value): number; + cmp(n: Decimal.Value): number; + + cosine(): Decimal; + cos(): Decimal; + + cubeRoot(): Decimal; + cbrt(): Decimal; + + decimalPlaces(): number; + dp(): number; + + dividedBy(n: Decimal.Value): Decimal; + div(n: Decimal.Value): Decimal; + + dividedToIntegerBy(n: Decimal.Value): Decimal; + divToInt(n: Decimal.Value): Decimal; + + equals(n: Decimal.Value): boolean; + eq(n: Decimal.Value): boolean; + + floor(): Decimal; + + greaterThan(n: Decimal.Value): boolean; + gt(n: Decimal.Value): boolean; + + greaterThanOrEqualTo(n: Decimal.Value): boolean; + gte(n: Decimal.Value): boolean; + + hyperbolicCosine(): Decimal; + cosh(): Decimal; + + hyperbolicSine(): Decimal; + sinh(): Decimal; + + hyperbolicTangent(): Decimal; + tanh(): Decimal; + + inverseCosine(): Decimal; + acos(): Decimal; + + inverseHyperbolicCosine(): Decimal; + acosh(): Decimal; + + inverseHyperbolicSine(): Decimal; + asinh(): Decimal; + + inverseHyperbolicTangent(): Decimal; + atanh(): Decimal; + + inverseSine(): Decimal; + asin(): Decimal; + + inverseTangent(): Decimal; + atan(): Decimal; + + isFinite(): boolean; + + isInteger(): boolean; + isInt(): boolean; + + isNaN(): boolean; + + isNegative(): boolean; + isNeg(): boolean; + + isPositive(): boolean; + isPos(): boolean; + + isZero(): boolean; + + lessThan(n: Decimal.Value): boolean; + lt(n: Decimal.Value): boolean; + + lessThanOrEqualTo(n: Decimal.Value): boolean; + lte(n: Decimal.Value): boolean; + + logarithm(n?: Decimal.Value): Decimal; + log(n?: Decimal.Value): Decimal; + + minus(n: Decimal.Value): Decimal; + sub(n: Decimal.Value): Decimal; + + modulo(n: Decimal.Value): Decimal; + mod(n: Decimal.Value): Decimal; + + naturalExponential(): Decimal; + exp(): Decimal; + + naturalLogarithm(): Decimal; + ln(): Decimal; + + negated(): Decimal; + neg(): Decimal; + + plus(n: Decimal.Value): Decimal; + add(n: Decimal.Value): Decimal; + + precision(includeZeros?: boolean): number; + sd(includeZeros?: boolean): number; + + round(): Decimal; + + sine() : Decimal; + sin() : Decimal; + + squareRoot(): Decimal; + sqrt(): Decimal; + + tangent() : Decimal; + tan() : Decimal; + + times(n: Decimal.Value): Decimal; + mul(n: Decimal.Value) : Decimal; + + toBinary(significantDigits?: number): string; + toBinary(significantDigits: number, rounding: Decimal.Rounding): string; + + toDecimalPlaces(decimalPlaces?: number): Decimal; + toDecimalPlaces(decimalPlaces: number, rounding: Decimal.Rounding): Decimal; + toDP(decimalPlaces?: number): Decimal; + toDP(decimalPlaces: number, rounding: Decimal.Rounding): Decimal; + + toExponential(decimalPlaces?: number): string; + toExponential(decimalPlaces: number, rounding: Decimal.Rounding): string; + + toFixed(decimalPlaces?: number): string; + toFixed(decimalPlaces: number, rounding: Decimal.Rounding): string; + + toFraction(max_denominator?: Decimal.Value): Decimal[]; + + toHexadecimal(significantDigits?: number): string; + toHexadecimal(significantDigits: number, rounding: Decimal.Rounding): string; + toHex(significantDigits?: number): string; + toHex(significantDigits: number, rounding?: Decimal.Rounding): string; + + toJSON(): string; + + toNearest(n: Decimal.Value, rounding?: Decimal.Rounding): Decimal; + + toNumber(): number; + + toOctal(significantDigits?: number): string; + toOctal(significantDigits: number, rounding: Decimal.Rounding): string; + + toPower(n: Decimal.Value): Decimal; + pow(n: Decimal.Value): Decimal; + + toPrecision(significantDigits?: number): string; + toPrecision(significantDigits: number, rounding: Decimal.Rounding): string; + + toSignificantDigits(significantDigits?: number): Decimal; + toSignificantDigits(significantDigits: number, rounding: Decimal.Rounding): Decimal; + toSD(significantDigits?: number): Decimal; + toSD(significantDigits: number, rounding: Decimal.Rounding): Decimal; + + toString(): string; + + truncated(): Decimal; + trunc(): Decimal; + + valueOf(): string; + + static abs(n: Decimal.Value): Decimal; + static acos(n: Decimal.Value): Decimal; + static acosh(n: Decimal.Value): Decimal; + static add(x: Decimal.Value, y: Decimal.Value): Decimal; + static asin(n: Decimal.Value): Decimal; + static asinh(n: Decimal.Value): Decimal; + static atan(n: Decimal.Value): Decimal; + static atanh(n: Decimal.Value): Decimal; + static atan2(y: Decimal.Value, x: Decimal.Value): Decimal; + static cbrt(n: Decimal.Value): Decimal; + static ceil(n: Decimal.Value): Decimal; + static clamp(n: Decimal.Value, min: Decimal.Value, max: Decimal.Value): Decimal; + static clone(object?: Decimal.Config): Decimal.Constructor; + static config(object: Decimal.Config): Decimal.Constructor; + static cos(n: Decimal.Value): Decimal; + static cosh(n: Decimal.Value): Decimal; + static div(x: Decimal.Value, y: Decimal.Value): Decimal; + static exp(n: Decimal.Value): Decimal; + static floor(n: Decimal.Value): Decimal; + static hypot(...n: Decimal.Value[]): Decimal; + static isDecimal(object: any): boolean + static ln(n: Decimal.Value): Decimal; + static log(n: Decimal.Value, base?: Decimal.Value): Decimal; + static log2(n: Decimal.Value): Decimal; + static log10(n: Decimal.Value): Decimal; + static max(...n: Decimal.Value[]): Decimal; + static min(...n: Decimal.Value[]): Decimal; + static mod(x: Decimal.Value, y: Decimal.Value): Decimal; + static mul(x: Decimal.Value, y: Decimal.Value): Decimal; + static noConflict(): Decimal.Constructor; // Browser only + static pow(base: Decimal.Value, exponent: Decimal.Value): Decimal; + static random(significantDigits?: number): Decimal; + static round(n: Decimal.Value): Decimal; + static set(object: Decimal.Config): Decimal.Constructor; + static sign(n: Decimal.Value): Decimal; + static sin(n: Decimal.Value): Decimal; + static sinh(n: Decimal.Value): Decimal; + static sqrt(n: Decimal.Value): Decimal; + static sub(x: Decimal.Value, y: Decimal.Value): Decimal; + static sum(...n: Decimal.Value[]): Decimal; + static tan(n: Decimal.Value): Decimal; + static tanh(n: Decimal.Value): Decimal; + static trunc(n: Decimal.Value): Decimal; + + static readonly default?: Decimal.Constructor; + static readonly Decimal?: Decimal.Constructor; + + static readonly precision: number; + static readonly rounding: Decimal.Rounding; + static readonly toExpNeg: number; + static readonly toExpPos: number; + static readonly minE: number; + static readonly maxE: number; + static readonly crypto: boolean; + static readonly modulo: Decimal.Modulo; + + static readonly ROUND_UP: 0; + static readonly ROUND_DOWN: 1; + static readonly ROUND_CEIL: 2; + static readonly ROUND_FLOOR: 3; + static readonly ROUND_HALF_UP: 4; + static readonly ROUND_HALF_DOWN: 5; + static readonly ROUND_HALF_EVEN: 6; + static readonly ROUND_HALF_CEIL: 7; + static readonly ROUND_HALF_FLOOR: 8; + static readonly EUCLID: 9; +} diff --git a/node_modules/decimal.js/decimal.js b/node_modules/decimal.js/decimal.js new file mode 100644 index 0000000..7290d8c --- /dev/null +++ b/node_modules/decimal.js/decimal.js @@ -0,0 +1,4934 @@ +;(function (globalScope) { + 'use strict'; + + + /* + * decimal.js v10.3.1 + * An arbitrary-precision Decimal type for JavaScript. + * https://github.com/MikeMcl/decimal.js + * Copyright (c) 2021 Michael Mclaughlin + * MIT Licence + */ + + + // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ // + + + // The maximum exponent magnitude. + // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`. + var EXP_LIMIT = 9e15, // 0 to 9e15 + + // The limit on the value of `precision`, and on the value of the first argument to + // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`. + MAX_DIGITS = 1e9, // 0 to 1e9 + + // Base conversion alphabet. + NUMERALS = '0123456789abcdef', + + // The natural logarithm of 10 (1025 digits). + LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058', + + // Pi (1025 digits). + PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789', + + + // The initial configuration properties of the Decimal constructor. + DEFAULTS = { + + // These values must be integers within the stated ranges (inclusive). + // Most of these values can be changed at run-time using the `Decimal.config` method. + + // The maximum number of significant digits of the result of a calculation or base conversion. + // E.g. `Decimal.config({ precision: 20 });` + precision: 20, // 1 to MAX_DIGITS + + // The rounding mode used when rounding to `precision`. + // + // ROUND_UP 0 Away from zero. + // ROUND_DOWN 1 Towards zero. + // ROUND_CEIL 2 Towards +Infinity. + // ROUND_FLOOR 3 Towards -Infinity. + // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + // + // E.g. + // `Decimal.rounding = 4;` + // `Decimal.rounding = Decimal.ROUND_HALF_UP;` + rounding: 4, // 0 to 8 + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend (JavaScript %). + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 The IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive. + // + // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian + // division (9) are commonly used for the modulus operation. The other rounding modes can also + // be used, but they may not give useful results. + modulo: 1, // 0 to 9 + + // The exponent value at and beneath which `toString` returns exponential notation. + // JavaScript numbers: -7 + toExpNeg: -7, // 0 to -EXP_LIMIT + + // The exponent value at and above which `toString` returns exponential notation. + // JavaScript numbers: 21 + toExpPos: 21, // 0 to EXP_LIMIT + + // The minimum exponent value, beneath which underflow to zero occurs. + // JavaScript numbers: -324 (5e-324) + minE: -EXP_LIMIT, // -1 to -EXP_LIMIT + + // The maximum exponent value, above which overflow to Infinity occurs. + // JavaScript numbers: 308 (1.7976931348623157e+308) + maxE: EXP_LIMIT, // 1 to EXP_LIMIT + + // Whether to use cryptographically-secure random number generation, if available. + crypto: false // true/false + }, + + + // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- // + + + Decimal, inexact, noConflict, quadrant, + external = true, + + decimalError = '[DecimalError] ', + invalidArgument = decimalError + 'Invalid argument: ', + precisionLimitExceeded = decimalError + 'Precision limit exceeded', + cryptoUnavailable = decimalError + 'crypto unavailable', + tag = '[object Decimal]', + + mathfloor = Math.floor, + mathpow = Math.pow, + + isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i, + isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i, + isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i, + isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, + + BASE = 1e7, + LOG_BASE = 7, + MAX_SAFE_INTEGER = 9007199254740991, + + LN10_PRECISION = LN10.length - 1, + PI_PRECISION = PI.length - 1, + + // Decimal.prototype object + P = { toStringTag: tag }; + + + // Decimal prototype methods + + + /* + * absoluteValue abs + * ceil + * clampedTo clamp + * comparedTo cmp + * cosine cos + * cubeRoot cbrt + * decimalPlaces dp + * dividedBy div + * dividedToIntegerBy divToInt + * equals eq + * floor + * greaterThan gt + * greaterThanOrEqualTo gte + * hyperbolicCosine cosh + * hyperbolicSine sinh + * hyperbolicTangent tanh + * inverseCosine acos + * inverseHyperbolicCosine acosh + * inverseHyperbolicSine asinh + * inverseHyperbolicTangent atanh + * inverseSine asin + * inverseTangent atan + * isFinite + * isInteger isInt + * isNaN + * isNegative isNeg + * isPositive isPos + * isZero + * lessThan lt + * lessThanOrEqualTo lte + * logarithm log + * [maximum] [max] + * [minimum] [min] + * minus sub + * modulo mod + * naturalExponential exp + * naturalLogarithm ln + * negated neg + * plus add + * precision sd + * round + * sine sin + * squareRoot sqrt + * tangent tan + * times mul + * toBinary + * toDecimalPlaces toDP + * toExponential + * toFixed + * toFraction + * toHexadecimal toHex + * toNearest + * toNumber + * toOctal + * toPower pow + * toPrecision + * toSignificantDigits toSD + * toString + * truncated trunc + * valueOf toJSON + */ + + + /* + * Return a new Decimal whose value is the absolute value of this Decimal. + * + */ + P.absoluteValue = P.abs = function () { + var x = new this.constructor(this); + if (x.s < 0) x.s = 1; + return finalise(x); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of positive Infinity. + * + */ + P.ceil = function () { + return finalise(new this.constructor(this), this.e + 1, 2); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal clamped to the range + * delineated by `min` and `max`. + * + * min {number|string|Decimal} + * max {number|string|Decimal} + * + */ + P.clampedTo = P.clamp = function (min, max) { + var k, + x = this, + Ctor = x.constructor; + min = new Ctor(min); + max = new Ctor(max); + if (!min.s || !max.s) return new Ctor(NaN); + if (min.gt(max)) throw Error(invalidArgument + max); + k = x.cmp(min); + return k < 0 ? min : x.cmp(max) > 0 ? max : new Ctor(x); + }; + + + /* + * Return + * 1 if the value of this Decimal is greater than the value of `y`, + * -1 if the value of this Decimal is less than the value of `y`, + * 0 if they have the same value, + * NaN if the value of either Decimal is NaN. + * + */ + P.comparedTo = P.cmp = function (y) { + var i, j, xdL, ydL, + x = this, + xd = x.d, + yd = (y = new x.constructor(y)).d, + xs = x.s, + ys = y.s; + + // Either NaN or ±Infinity? + if (!xd || !yd) { + return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; + } + + // Either zero? + if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; + + // Signs differ? + if (xs !== ys) return xs; + + // Compare exponents. + if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; + + xdL = xd.length; + ydL = yd.length; + + // Compare digit by digit. + for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { + if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; + } + + // Compare lengths. + return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; + }; + + + /* + * Return a new Decimal whose value is the cosine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * cos(0) = 1 + * cos(-0) = 1 + * cos(Infinity) = NaN + * cos(-Infinity) = NaN + * cos(NaN) = NaN + * + */ + P.cosine = P.cos = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.d) return new Ctor(NaN); + + // cos(0) = cos(-0) = 1 + if (!x.d[0]) return new Ctor(1); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; + + x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); + }; + + + /* + * + * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * cbrt(0) = 0 + * cbrt(-0) = -0 + * cbrt(1) = 1 + * cbrt(-1) = -1 + * cbrt(N) = N + * cbrt(-I) = -I + * cbrt(I) = I + * + * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3)) + * + */ + P.cubeRoot = P.cbrt = function () { + var e, m, n, r, rep, s, sd, t, t3, t3plusx, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + external = false; + + // Initial estimate. + s = x.s * mathpow(x.s * x, 1 / 3); + + // Math.cbrt underflow/overflow? + // Pass x to Math.pow as integer, then adjust the exponent of the result. + if (!s || Math.abs(s) == 1 / 0) { + n = digitsToString(x.d); + e = x.e; + + // Adjust n exponent so it is a multiple of 3 away from x exponent. + if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); + s = mathpow(n, 1 / 3); + + // Rarely, e may be one less than the result exponent value. + e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + r.s = x.s; + } else { + r = new Ctor(s.toString()); + } + + sd = (e = Ctor.precision) + 3; + + // Halley's method. + // TODO? Compare Newton's method. + for (;;) { + t = r; + t3 = t.times(t).times(t); + t3plusx = t3.plus(x); + r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); + + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 + // , i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); + + if (t.times(t).times(t).eq(x)) { + r = t; + break; + } + } + + sd += 4; + rep = 1; + } else { + + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).times(r).eq(x); + } + + break; + } + } + } + + external = true; + + return finalise(r, e, Ctor.rounding, m); + }; + + + /* + * Return the number of decimal places of the value of this Decimal. + * + */ + P.decimalPlaces = P.dp = function () { + var w, + d = this.d, + n = NaN; + + if (d) { + w = d.length - 1; + n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last word. + w = d[w]; + if (w) for (; w % 10 == 0; w /= 10) n--; + if (n < 0) n = 0; + } + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + */ + P.dividedBy = P.div = function (y) { + return divide(this, new this.constructor(y)); + }; + + + /* + * Return a new Decimal whose value is the integer part of dividing the value of this Decimal + * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`. + * + */ + P.dividedToIntegerBy = P.divToInt = function (y) { + var x = this, + Ctor = x.constructor; + return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); + }; + + + /* + * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. + * + */ + P.equals = P.eq = function (y) { + return this.cmp(y) === 0; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of negative Infinity. + * + */ + P.floor = function () { + return finalise(new this.constructor(this), this.e + 1, 3); + }; + + + /* + * Return true if the value of this Decimal is greater than the value of `y`, otherwise return + * false. + * + */ + P.greaterThan = P.gt = function (y) { + return this.cmp(y) > 0; + }; + + + /* + * Return true if the value of this Decimal is greater than or equal to the value of `y`, + * otherwise return false. + * + */ + P.greaterThanOrEqualTo = P.gte = function (y) { + var k = this.cmp(y); + return k == 1 || k === 0; + }; + + + /* + * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [1, Infinity] + * + * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ... + * + * cosh(0) = 1 + * cosh(-0) = 1 + * cosh(Infinity) = Infinity + * cosh(-Infinity) = Infinity + * cosh(NaN) = NaN + * + * x time taken (ms) result + * 1000 9 9.8503555700852349694e+433 + * 10000 25 4.4034091128314607936e+4342 + * 100000 171 1.4033316802130615897e+43429 + * 1000000 3817 1.5166076984010437725e+434294 + * 10000000 abandoned after 2 minute wait + * + * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x)) + * + */ + P.hyperbolicCosine = P.cosh = function () { + var k, n, pr, rm, len, + x = this, + Ctor = x.constructor, + one = new Ctor(1); + + if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); + if (x.isZero()) return one; + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; + + // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 + // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) + + // Estimate the optimum number of times to use the argument reduction. + // TODO? Estimation reused from cosine() and may not be optimal here. + if (len < 32) { + k = Math.ceil(len / 3); + n = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + n = '2.3283064365386962890625e-10'; + } + + x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); + + // Reverse argument reduction + var cosh2_x, + i = k, + d8 = new Ctor(8); + for (; i--;) { + cosh2_x = x.times(x); + x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); + } + + return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); + }; + + + /* + * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ... + * + * sinh(0) = 0 + * sinh(-0) = -0 + * sinh(Infinity) = Infinity + * sinh(-Infinity) = -Infinity + * sinh(NaN) = NaN + * + * x time taken (ms) + * 10 2 ms + * 100 5 ms + * 1000 14 ms + * 10000 82 ms + * 100000 886 ms 1.4033316802130615897e+43429 + * 200000 2613 ms + * 300000 5407 ms + * 400000 8824 ms + * 500000 13026 ms 8.7080643612718084129e+217146 + * 1000000 48543 ms + * + * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x)) + * + */ + P.hyperbolicSine = P.sinh = function () { + var k, pr, rm, len, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; + + if (len < 3) { + x = taylorSeries(Ctor, 2, x, x, true); + } else { + + // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) + // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) + // 3 multiplications and 1 addition + + // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) + // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) + // 4 multiplications and 2 additions + + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; + + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x, true); + + // Reverse argument reduction + var sinh2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sinh2_x = x.times(x); + x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); + } + } + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(x, pr, rm, true); + }; + + + /* + * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * tanh(x) = sinh(x) / cosh(x) + * + * tanh(0) = 0 + * tanh(-0) = -0 + * tanh(Infinity) = 1 + * tanh(-Infinity) = -1 + * tanh(NaN) = NaN + * + */ + P.hyperbolicTangent = P.tanh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(x.s); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 7; + Ctor.rounding = 1; + + return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); + }; + + + /* + * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of + * this Decimal. + * + * Domain: [-1, 1] + * Range: [0, pi] + * + * acos(x) = pi/2 - asin(x) + * + * acos(0) = pi/2 + * acos(-0) = pi/2 + * acos(1) = 0 + * acos(-1) = pi + * acos(1/2) = pi/3 + * acos(-1/2) = 2*pi/3 + * acos(|x| > 1) = NaN + * acos(NaN) = NaN + * + */ + P.inverseCosine = P.acos = function () { + var halfPi, + x = this, + Ctor = x.constructor, + k = x.abs().cmp(1), + pr = Ctor.precision, + rm = Ctor.rounding; + + if (k !== -1) { + return k === 0 + // |x| is 1 + ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) + // |x| > 1 or x is NaN + : new Ctor(NaN); + } + + if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); + + // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 + + Ctor.precision = pr + 6; + Ctor.rounding = 1; + + x = x.asin(); + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return halfPi.minus(x); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the + * value of this Decimal. + * + * Domain: [1, Infinity] + * Range: [0, Infinity] + * + * acosh(x) = ln(x + sqrt(x^2 - 1)) + * + * acosh(x < 1) = NaN + * acosh(NaN) = NaN + * acosh(Infinity) = Infinity + * acosh(-Infinity) = NaN + * acosh(0) = NaN + * acosh(-0) = NaN + * acosh(1) = 0 + * acosh(-1) = NaN + * + */ + P.inverseHyperbolicCosine = P.acosh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); + if (!x.isFinite()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; + Ctor.rounding = 1; + external = false; + + x = x.times(x).minus(1).sqrt().plus(x); + + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.ln(); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * asinh(x) = ln(x + sqrt(x^2 + 1)) + * + * asinh(NaN) = NaN + * asinh(Infinity) = Infinity + * asinh(-Infinity) = -Infinity + * asinh(0) = 0 + * asinh(-0) = -0 + * + */ + P.inverseHyperbolicSine = P.asinh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; + Ctor.rounding = 1; + external = false; + + x = x.times(x).plus(1).sqrt().plus(x); + + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.ln(); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the + * value of this Decimal. + * + * Domain: [-1, 1] + * Range: [-Infinity, Infinity] + * + * atanh(x) = 0.5 * ln((1 + x) / (1 - x)) + * + * atanh(|x| > 1) = NaN + * atanh(NaN) = NaN + * atanh(Infinity) = NaN + * atanh(-Infinity) = NaN + * atanh(0) = 0 + * atanh(-0) = -0 + * atanh(1) = Infinity + * atanh(-1) = -Infinity + * + */ + P.inverseHyperbolicTangent = P.atanh = function () { + var pr, rm, wpr, xsd, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); + + pr = Ctor.precision; + rm = Ctor.rounding; + xsd = x.sd(); + + if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); + + Ctor.precision = wpr = xsd - x.e; + + x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); + + Ctor.precision = pr + 4; + Ctor.rounding = 1; + + x = x.ln(); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.times(0.5); + }; + + + /* + * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2))) + * + * asin(0) = 0 + * asin(-0) = -0 + * asin(1/2) = pi/6 + * asin(-1/2) = -pi/6 + * asin(1) = pi/2 + * asin(-1) = -pi/2 + * asin(|x| > 1) = NaN + * asin(NaN) = NaN + * + * TODO? Compare performance of Taylor series. + * + */ + P.inverseSine = P.asin = function () { + var halfPi, k, + pr, rm, + x = this, + Ctor = x.constructor; + + if (x.isZero()) return new Ctor(x); + + k = x.abs().cmp(1); + pr = Ctor.precision; + rm = Ctor.rounding; + + if (k !== -1) { + + // |x| is 1 + if (k === 0) { + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); + halfPi.s = x.s; + return halfPi; + } + + // |x| > 1 or x is NaN + return new Ctor(NaN); + } + + // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 + + Ctor.precision = pr + 6; + Ctor.rounding = 1; + + x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.times(2); + }; + + + /* + * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + * + * atan(0) = 0 + * atan(-0) = -0 + * atan(1) = pi/4 + * atan(-1) = -pi/4 + * atan(Infinity) = pi/2 + * atan(-Infinity) = -pi/2 + * atan(NaN) = NaN + * + */ + P.inverseTangent = P.atan = function () { + var i, j, k, n, px, t, r, wpr, x2, + x = this, + Ctor = x.constructor, + pr = Ctor.precision, + rm = Ctor.rounding; + + if (!x.isFinite()) { + if (!x.s) return new Ctor(NaN); + if (pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.5); + r.s = x.s; + return r; + } + } else if (x.isZero()) { + return new Ctor(x); + } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.25); + r.s = x.s; + return r; + } + + Ctor.precision = wpr = pr + 10; + Ctor.rounding = 1; + + // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); + + // Argument reduction + // Ensure |x| < 0.42 + // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) + + k = Math.min(28, wpr / LOG_BASE + 2 | 0); + + for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); + + external = false; + + j = Math.ceil(wpr / LOG_BASE); + n = 1; + x2 = x.times(x); + r = new Ctor(x); + px = x; + + // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + for (; i !== -1;) { + px = px.times(x2); + t = r.minus(px.div(n += 2)); + + px = px.times(x2); + r = t.plus(px.div(n += 2)); + + if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); + } + + if (k) r = r.times(2 << (k - 1)); + + external = true; + + return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); + }; + + + /* + * Return true if the value of this Decimal is a finite number, otherwise return false. + * + */ + P.isFinite = function () { + return !!this.d; + }; + + + /* + * Return true if the value of this Decimal is an integer, otherwise return false. + * + */ + P.isInteger = P.isInt = function () { + return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; + }; + + + /* + * Return true if the value of this Decimal is NaN, otherwise return false. + * + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this Decimal is negative, otherwise return false. + * + */ + P.isNegative = P.isNeg = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this Decimal is positive, otherwise return false. + * + */ + P.isPositive = P.isPos = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this Decimal is 0 or -0, otherwise return false. + * + */ + P.isZero = function () { + return !!this.d && this.d[0] === 0; + }; + + + /* + * Return true if the value of this Decimal is less than `y`, otherwise return false. + * + */ + P.lessThan = P.lt = function (y) { + return this.cmp(y) < 0; + }; + + + /* + * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. + * + */ + P.lessThanOrEqualTo = P.lte = function (y) { + return this.cmp(y) < 1; + }; + + + /* + * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * If no base is specified, return log[10](arg). + * + * log[base](arg) = ln(arg) / ln(base) + * + * The result will always be correctly rounded if the base of the log is 10, and 'almost always' + * otherwise: + * + * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen + * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error + * between the result and the correctly rounded result will be one ulp (unit in the last place). + * + * log[-b](a) = NaN + * log[0](a) = NaN + * log[1](a) = NaN + * log[NaN](a) = NaN + * log[Infinity](a) = NaN + * log[b](0) = -Infinity + * log[b](-0) = -Infinity + * log[b](-a) = NaN + * log[b](1) = 0 + * log[b](Infinity) = Infinity + * log[b](NaN) = NaN + * + * [base] {number|string|Decimal} The base of the logarithm. + * + */ + P.logarithm = P.log = function (base) { + var isBase10, d, denominator, k, inf, num, sd, r, + arg = this, + Ctor = arg.constructor, + pr = Ctor.precision, + rm = Ctor.rounding, + guard = 5; + + // Default base is 10. + if (base == null) { + base = new Ctor(10); + isBase10 = true; + } else { + base = new Ctor(base); + d = base.d; + + // Return NaN if base is negative, or non-finite, or is 0 or 1. + if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); + + isBase10 = base.eq(10); + } + + d = arg.d; + + // Is arg negative, non-finite, 0 or 1? + if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { + return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); + } + + // The result will have a non-terminating decimal expansion if base is 10 and arg is not an + // integer power of 10. + if (isBase10) { + if (d.length > 1) { + inf = true; + } else { + for (k = d[0]; k % 10 === 0;) k /= 10; + inf = k !== 1; + } + } + + external = false; + sd = pr + guard; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); + + // The result will have 5 rounding digits. + r = divide(num, denominator, sd, 1); + + // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, + // calculate 10 further digits. + // + // If the result is known to have an infinite decimal expansion, repeat this until it is clear + // that the result is above or below the boundary. Otherwise, if after calculating the 10 + // further digits, the last 14 are nines, round up and assume the result is exact. + // Also assume the result is exact if the last 14 are zero. + // + // Example of a result that will be incorrectly rounded: + // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... + // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it + // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so + // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal + // place is still 2.6. + if (checkRoundingDigits(r.d, k = pr, rm)) { + + do { + sd += 10; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); + r = divide(num, denominator, sd, 1); + + if (!inf) { + + // Check for 14 nines from the 2nd rounding digit, as the first may be 4. + if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } + + break; + } + } while (checkRoundingDigits(r.d, k += 10, rm)); + } + + external = true; + + return finalise(r, pr, rm); + }; + + + /* + * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * + P.max = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'lt'); + }; + */ + + + /* + * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * + P.min = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'gt'); + }; + */ + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.minus = P.sub = function (y) { + var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // If either is not finite... + if (!x.d || !y.d) { + + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); + + // Return y negated if x is finite and y is ±Infinity. + else if (x.d) y.s = -y.s; + + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with different signs. + // Return NaN if both are ±Infinity with the same sign. + else y = new Ctor(y.d || x.s !== y.s ? x : NaN); + + return y; + } + + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.plus(y); + } + + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; + + // If either is zero... + if (!xd[0] || !yd[0]) { + + // Return y negated if x is zero and y is non-zero. + if (yd[0]) y.s = -y.s; + + // Return x if y is zero and x is non-zero. + else if (xd[0]) y = new Ctor(x); + + // Return zero if both are zero. + // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. + else return new Ctor(rm === 3 ? -0 : 0); + + return external ? finalise(y, pr, rm) : y; + } + + // x and y are finite, non-zero numbers with the same sign. + + // Calculate base 1e7 exponents. + e = mathfloor(y.e / LOG_BASE); + xe = mathfloor(x.e / LOG_BASE); + + xd = xd.slice(); + k = xe - e; + + // If base 1e7 exponents differ... + if (k) { + xLTy = k < 0; + + if (xLTy) { + d = xd; + k = -k; + len = yd.length; + } else { + d = yd; + e = xe; + len = xd.length; + } + + // Numbers with massively different exponents would result in a very high number of + // zeros needing to be prepended, but this can be avoided while still ensuring correct + // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. + i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; + + if (k > i) { + k = i; + d.length = 1; + } + + // Prepend zeros to equalise exponents. + d.reverse(); + for (i = k; i--;) d.push(0); + d.reverse(); + + // Base 1e7 exponents equal. + } else { + + // Check digits to determine which is the bigger number. + + i = xd.length; + len = yd.length; + xLTy = i < len; + if (xLTy) len = i; + + for (i = 0; i < len; i++) { + if (xd[i] != yd[i]) { + xLTy = xd[i] < yd[i]; + break; + } + } + + k = 0; + } + + if (xLTy) { + d = xd; + xd = yd; + yd = d; + y.s = -y.s; + } + + len = xd.length; + + // Append zeros to `xd` if shorter. + // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. + for (i = yd.length - len; i > 0; --i) xd[len++] = 0; + + // Subtract yd from xd. + for (i = yd.length; i > k;) { + + if (xd[--i] < yd[i]) { + for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; + --xd[j]; + xd[i] += BASE; + } + + xd[i] -= yd[i]; + } + + // Remove trailing zeros. + for (; xd[--len] === 0;) xd.pop(); + + // Remove leading zeros and adjust exponent accordingly. + for (; xd[0] === 0; xd.shift()) --e; + + // Zero? + if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); + + y.d = xd; + y.e = getBase10Exponent(xd, e); + + return external ? finalise(y, pr, rm) : y; + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * The result depends on the modulo mode. + * + */ + P.modulo = P.mod = function (y) { + var q, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. + if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); + + // Return x if y is ±Infinity or x is ±0. + if (!y.d || x.d && !x.d[0]) { + return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); + } + + // Prevent rounding of intermediate calculations. + external = false; + + if (Ctor.modulo == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // result = x - q * y where 0 <= result < abs(y) + q = divide(x, y.abs(), 0, 3, 1); + q.s *= y.s; + } else { + q = divide(x, y, 0, Ctor.modulo, 1); + } + + q = q.times(y); + + external = true; + + return x.minus(q); + }; + + + /* + * Return a new Decimal whose value is the natural exponential of the value of this Decimal, + * i.e. the base e raised to the power the value of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.naturalExponential = P.exp = function () { + return naturalExponential(this); + }; + + + /* + * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + */ + P.naturalLogarithm = P.ln = function () { + return naturalLogarithm(this); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by + * -1. + * + */ + P.negated = P.neg = function () { + var x = new this.constructor(this); + x.s = -x.s; + return finalise(x); + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.plus = P.add = function (y) { + var carry, d, e, i, k, len, pr, rm, xd, yd, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // If either is not finite... + if (!x.d || !y.d) { + + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); + + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with the same sign. + // Return NaN if both are ±Infinity with different signs. + // Return y if x is finite and y is ±Infinity. + else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); + + return y; + } + + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.minus(y); + } + + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; + + // If either is zero... + if (!xd[0] || !yd[0]) { + + // Return x if y is zero. + // Return y if y is non-zero. + if (!yd[0]) y = new Ctor(x); + + return external ? finalise(y, pr, rm) : y; + } + + // x and y are finite, non-zero numbers with the same sign. + + // Calculate base 1e7 exponents. + k = mathfloor(x.e / LOG_BASE); + e = mathfloor(y.e / LOG_BASE); + + xd = xd.slice(); + i = k - e; + + // If base 1e7 exponents differ... + if (i) { + + if (i < 0) { + d = xd; + i = -i; + len = yd.length; + } else { + d = yd; + e = k; + len = xd.length; + } + + // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. + k = Math.ceil(pr / LOG_BASE); + len = k > len ? k + 1 : len + 1; + + if (i > len) { + i = len; + d.length = 1; + } + + // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. + d.reverse(); + for (; i--;) d.push(0); + d.reverse(); + } + + len = xd.length; + i = yd.length; + + // If yd is longer than xd, swap xd and yd so xd points to the longer array. + if (len - i < 0) { + i = len; + d = yd; + yd = xd; + xd = d; + } + + // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. + for (carry = 0; i;) { + carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; + xd[i] %= BASE; + } + + if (carry) { + xd.unshift(carry); + ++e; + } + + // Remove trailing zeros. + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + for (len = xd.length; xd[--len] == 0;) xd.pop(); + + y.d = xd; + y.e = getBase10Exponent(xd, e); + + return external ? finalise(y, pr, rm) : y; + }; + + + /* + * Return the number of significant digits of the value of this Decimal. + * + * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + * + */ + P.precision = P.sd = function (z) { + var k, + x = this; + + if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); + + if (x.d) { + k = getPrecision(x.d); + if (z && x.e + 1 > k) k = x.e + 1; + } else { + k = NaN; + } + + return k; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using + * rounding mode `rounding`. + * + */ + P.round = function () { + var x = this, + Ctor = x.constructor; + + return finalise(new Ctor(x), x.e + 1, Ctor.rounding); + }; + + + /* + * Return a new Decimal whose value is the sine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * sin(x) = x - x^3/3! + x^5/5! - ... + * + * sin(0) = 0 + * sin(-0) = -0 + * sin(Infinity) = NaN + * sin(-Infinity) = NaN + * sin(NaN) = NaN + * + */ + P.sine = P.sin = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; + + x = sine(Ctor, toLessThanHalfPi(Ctor, x)); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); + }; + + + /* + * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + */ + P.squareRoot = P.sqrt = function () { + var m, n, sd, r, rep, t, + x = this, + d = x.d, + e = x.e, + s = x.s, + Ctor = x.constructor; + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !d || !d[0]) { + return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); + } + + external = false; + + // Initial estimate. + s = Math.sqrt(+x); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = digitsToString(d); + + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(n); + e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + } else { + r = new Ctor(s.toString()); + } + + sd = (e = Ctor.precision) + 3; + + // Newton-Raphson iteration. + for (;;) { + t = r; + r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); + + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or + // 4999, i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + sd += 4; + rep = 1; + } else { + + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + + external = true; + + return finalise(r, e, Ctor.rounding, m); + }; + + + /* + * Return a new Decimal whose value is the tangent of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * tan(0) = 0 + * tan(-0) = -0 + * tan(Infinity) = NaN + * tan(-Infinity) = NaN + * tan(NaN) = NaN + * + */ + P.tangent = P.tan = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 10; + Ctor.rounding = 1; + + x = x.sin(); + x.s = 1; + x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + */ + P.times = P.mul = function (y) { + var carry, e, i, k, r, rL, t, xdL, ydL, + x = this, + Ctor = x.constructor, + xd = x.d, + yd = (y = new Ctor(y)).d; + + y.s *= x.s; + + // If either is NaN, ±Infinity or ±0... + if (!xd || !xd[0] || !yd || !yd[0]) { + + return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd + + // Return NaN if either is NaN. + // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. + ? NaN + + // Return ±Infinity if either is ±Infinity. + // Return ±0 if either is ±0. + : !xd || !yd ? y.s / 0 : y.s * 0); + } + + e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); + xdL = xd.length; + ydL = yd.length; + + // Ensure xd points to the longer array. + if (xdL < ydL) { + r = xd; + xd = yd; + yd = r; + rL = xdL; + xdL = ydL; + ydL = rL; + } + + // Initialise the result array with zeros. + r = []; + rL = xdL + ydL; + for (i = rL; i--;) r.push(0); + + // Multiply! + for (i = ydL; --i >= 0;) { + carry = 0; + for (k = xdL + i; k > i;) { + t = r[k] + yd[i] * xd[k - i - 1] + carry; + r[k--] = t % BASE | 0; + carry = t / BASE | 0; + } + + r[k] = (r[k] + carry) % BASE | 0; + } + + // Remove trailing zeros. + for (; !r[--rL];) r.pop(); + + if (carry) ++e; + else r.shift(); + + y.d = r; + y.e = getBase10Exponent(r, e); + + return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; + }; + + + /* + * Return a string representing the value of this Decimal in base 2, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toBinary = function (sd, rm) { + return toStringBinary(this, 2, sd, rm); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` + * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. + * + * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toDecimalPlaces = P.toDP = function (dp, rm) { + var x = this, + Ctor = x.constructor; + + x = new Ctor(x); + if (dp === void 0) return x; + + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + return finalise(x, dp + x.e + 1, rm); + }; + + + /* + * Return a string representing the value of this Decimal in exponential notation rounded to + * `dp` fixed decimal places using rounding mode `rounding`. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toExponential = function (dp, rm) { + var str, + x = this, + Ctor = x.constructor; + + if (dp === void 0) { + str = finiteToString(x, true); + } else { + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = finalise(new Ctor(x), dp + 1, rm); + str = finiteToString(x, true, dp + 1); + } + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a string representing the value of this Decimal in normal (fixed-point) notation to + * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is + * omitted. + * + * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. + * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. + * (-0).toFixed(3) is '0.000'. + * (-0.5).toFixed(0) is '-0'. + * + */ + P.toFixed = function (dp, rm) { + var str, y, + x = this, + Ctor = x.constructor; + + if (dp === void 0) { + str = finiteToString(x); + } else { + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + y = finalise(new Ctor(x), dp + x.e + 1, rm); + str = finiteToString(y, false, dp + y.e + 1); + } + + // To determine whether to add the minus sign look at the value before it was rounded, + // i.e. look at `x` rather than `y`. + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return an array representing the value of this Decimal as a simple fraction with an integer + * numerator and an integer denominator. + * + * The denominator will be a positive non-zero value less than or equal to the specified maximum + * denominator. If a maximum denominator is not specified, the denominator will be the lowest + * value necessary to represent the number exactly. + * + * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity. + * + */ + P.toFraction = function (maxD) { + var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, + x = this, + xd = x.d, + Ctor = x.constructor; + + if (!xd) return new Ctor(x); + + n1 = d0 = new Ctor(1); + d1 = n0 = new Ctor(0); + + d = new Ctor(d1); + e = d.e = getPrecision(xd) - x.e - 1; + k = e % LOG_BASE; + d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k); + + if (maxD == null) { + + // d is 10**e, the minimum max-denominator needed. + maxD = e > 0 ? d : n1; + } else { + n = new Ctor(maxD); + if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n); + maxD = n.gt(d) ? (e > 0 ? d : n1) : n; + } + + external = false; + n = new Ctor(digitsToString(xd)); + pr = Ctor.precision; + Ctor.precision = e = xd.length * LOG_BASE * 2; + + for (;;) { + q = divide(n, d, 0, 1, 1); + d2 = d0.plus(q.times(d1)); + if (d2.cmp(maxD) == 1) break; + d0 = d1; + d1 = d2; + d2 = n1; + n1 = n0.plus(q.times(d2)); + n0 = d2; + d2 = d; + d = n.minus(q.times(d2)); + n = d2; + } + + d2 = divide(maxD.minus(d0), d1, 0, 1, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + + // Determine which fraction is closer to x, n0/d0 or n1/d1? + r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 + ? [n1, d1] : [n0, d0]; + + Ctor.precision = pr; + external = true; + + return r; + }; + + + /* + * Return a string representing the value of this Decimal in base 16, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toHexadecimal = P.toHex = function (sd, rm) { + return toStringBinary(this, 16, sd, rm); + }; + + + /* + * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding + * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal. + * + * The return value will always have the same sign as this Decimal, unless either this Decimal + * or `y` is NaN, in which case the return value will be also be NaN. + * + * The return value is not affected by the value of `precision`. + * + * y {number|string|Decimal} The magnitude to round to a multiple of. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toNearest() rounding mode not an integer: {rm}' + * 'toNearest() rounding mode out of range: {rm}' + * + */ + P.toNearest = function (y, rm) { + var x = this, + Ctor = x.constructor; + + x = new Ctor(x); + + if (y == null) { + + // If x is not finite, return x. + if (!x.d) return x; + + y = new Ctor(1); + rm = Ctor.rounding; + } else { + y = new Ctor(y); + if (rm === void 0) { + rm = Ctor.rounding; + } else { + checkInt32(rm, 0, 8); + } + + // If x is not finite, return x if y is not NaN, else NaN. + if (!x.d) return y.s ? x : y; + + // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN. + if (!y.d) { + if (y.s) y.s = x.s; + return y; + } + } + + // If y is not zero, calculate the nearest multiple of y to x. + if (y.d[0]) { + external = false; + x = divide(x, y, 0, rm, 1).times(y); + external = true; + finalise(x); + + // If y is zero, return zero with the sign of x. + } else { + y.s = x.s; + x = y; + } + + return x; + }; + + + /* + * Return the value of this Decimal converted to a number primitive. + * Zero keeps its sign. + * + */ + P.toNumber = function () { + return +this; + }; + + + /* + * Return a string representing the value of this Decimal in base 8, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toOctal = function (sd, rm) { + return toStringBinary(this, 8, sd, rm); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded + * to `precision` significant digits using rounding mode `rounding`. + * + * ECMAScript compliant. + * + * pow(x, NaN) = NaN + * pow(x, ±0) = 1 + + * pow(NaN, non-zero) = NaN + * pow(abs(x) > 1, +Infinity) = +Infinity + * pow(abs(x) > 1, -Infinity) = +0 + * pow(abs(x) == 1, ±Infinity) = NaN + * pow(abs(x) < 1, +Infinity) = +0 + * pow(abs(x) < 1, -Infinity) = +Infinity + * pow(+Infinity, y > 0) = +Infinity + * pow(+Infinity, y < 0) = +0 + * pow(-Infinity, odd integer > 0) = -Infinity + * pow(-Infinity, even integer > 0) = +Infinity + * pow(-Infinity, odd integer < 0) = -0 + * pow(-Infinity, even integer < 0) = +0 + * pow(+0, y > 0) = +0 + * pow(+0, y < 0) = +Infinity + * pow(-0, odd integer > 0) = -0 + * pow(-0, even integer > 0) = +0 + * pow(-0, odd integer < 0) = -Infinity + * pow(-0, even integer < 0) = +Infinity + * pow(finite x < 0, finite non-integer) = NaN + * + * For non-integer or very large exponents pow(x, y) is calculated using + * + * x^y = exp(y*ln(x)) + * + * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the + * probability of an incorrectly rounded result + * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14 + * i.e. 1 in 250,000,000,000,000 + * + * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place). + * + * y {number|string|Decimal} The power to which to raise this Decimal. + * + */ + P.toPower = P.pow = function (y) { + var e, k, pr, r, rm, s, + x = this, + Ctor = x.constructor, + yn = +(y = new Ctor(y)); + + // Either ±Infinity, NaN or ±0? + if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); + + x = new Ctor(x); + + if (x.eq(1)) return x; + + pr = Ctor.precision; + rm = Ctor.rounding; + + if (y.eq(1)) return finalise(x, pr, rm); + + // y exponent + e = mathfloor(y.e / LOG_BASE); + + // If y is a small integer use the 'exponentiation by squaring' algorithm. + if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { + r = intPow(Ctor, x, k, pr); + return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); + } + + s = x.s; + + // if x is negative + if (s < 0) { + + // if y is not an integer + if (e < y.d.length - 1) return new Ctor(NaN); + + // Result is positive if x is negative and the last digit of integer y is even. + if ((y.d[e] & 1) == 0) s = 1; + + // if x.eq(-1) + if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) { + x.s = s; + return x; + } + } + + // Estimate result exponent. + // x^y = 10^e, where e = y * log10(x) + // log10(x) = log10(x_significand) + x_exponent + // log10(x_significand) = ln(x_significand) / ln(10) + k = mathpow(+x, yn); + e = k == 0 || !isFinite(k) + ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) + : new Ctor(k + '').e; + + // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. + + // Overflow/underflow? + if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0); + + external = false; + Ctor.rounding = x.s = 1; + + // Estimate the extra guard digits needed to ensure five correct rounding digits from + // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): + // new Decimal(2.32456).pow('2087987436534566.46411') + // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 + k = Math.min(12, (e + '').length); + + // r = x^y = exp(y*ln(x)) + r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); + + // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40) + if (r.d) { + + // Truncate to the required precision plus five rounding digits. + r = finalise(r, pr + 5, 1); + + // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate + // the result. + if (checkRoundingDigits(r.d, pr, rm)) { + e = pr + 10; + + // Truncate to the increased precision plus five rounding digits. + r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); + + // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). + if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } + } + } + + r.s = s; + external = true; + Ctor.rounding = rm; + + return finalise(r, pr, rm); + }; + + + /* + * Return a string representing the value of this Decimal rounded to `sd` significant digits + * using rounding mode `rounding`. + * + * Return exponential notation if `sd` is less than the number of digits necessary to represent + * the integer part of the value in normal notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toPrecision = function (sd, rm) { + var str, + x = this, + Ctor = x.constructor; + + if (sd === void 0) { + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = finalise(new Ctor(x), sd, rm); + str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd); + } + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` + * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if + * omitted. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toSD() digits out of range: {sd}' + * 'toSD() digits not an integer: {sd}' + * 'toSD() rounding mode not an integer: {rm}' + * 'toSD() rounding mode out of range: {rm}' + * + */ + P.toSignificantDigits = P.toSD = function (sd, rm) { + var x = this, + Ctor = x.constructor; + + if (sd === void 0) { + sd = Ctor.precision; + rm = Ctor.rounding; + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } + + return finalise(new Ctor(x), sd, rm); + }; + + + /* + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + P.toString = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal truncated to a whole number. + * + */ + P.truncated = P.trunc = function () { + return finalise(new this.constructor(this), this.e + 1, 1); + }; + + + /* + * Return a string representing the value of this Decimal. + * Unlike `toString`, negative zero will include the minus sign. + * + */ + P.valueOf = P.toJSON = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + + return x.isNeg() ? '-' + str : str; + }; + + + // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. + + + /* + * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower, + * finiteToString, naturalExponential, naturalLogarithm + * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest, + * P.toPrecision, P.toSignificantDigits, toStringBinary, random + * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm + * convertBase toStringBinary, parseOther + * cos P.cos + * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy, + * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction, + * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm, + * taylorSeries, atan2, parseOther + * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh, + * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus, + * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot, + * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed, + * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits, + * P.truncated, divide, getLn10, getPi, naturalExponential, + * naturalLogarithm, ceil, floor, round, trunc + * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf, + * toStringBinary + * getBase10Exponent P.minus, P.plus, P.times, parseOther + * getLn10 P.logarithm, naturalLogarithm + * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2 + * getPrecision P.precision, P.toFraction + * getZeroString digitsToString, finiteToString + * intPow P.toPower, parseOther + * isOdd toLessThanHalfPi + * maxOrMin max, min + * naturalExponential P.naturalExponential, P.toPower + * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm, + * P.toPower, naturalExponential + * nonFiniteToString finiteToString, toStringBinary + * parseDecimal Decimal + * parseOther Decimal + * sin P.sin + * taylorSeries P.cosh, P.sinh, cos, sin + * toLessThanHalfPi P.cos, P.sin + * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal + * truncate intPow + * + * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi, + * naturalLogarithm, config, parseOther, random, Decimal + */ + + + function digitsToString(d) { + var i, k, ws, + indexOfLastWord = d.length - 1, + str = '', + w = d[0]; + + if (indexOfLastWord > 0) { + str += w; + for (i = 1; i < indexOfLastWord; i++) { + ws = d[i] + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + str += ws; + } + + w = d[i]; + ws = w + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + } else if (w === 0) { + return '0'; + } + + // Remove trailing zeros of last w. + for (; w % 10 === 0;) w /= 10; + + return str + w; + } + + + function checkInt32(i, min, max) { + if (i !== ~~i || i < min || i > max) { + throw Error(invalidArgument + i); + } + } + + + /* + * Check 5 rounding digits if `repeating` is null, 4 otherwise. + * `repeating == null` if caller is `log` or `pow`, + * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`. + */ + function checkRoundingDigits(d, i, rm, repeating) { + var di, k, r, rd; + + // Get the length of the first word of the array d. + for (k = d[0]; k >= 10; k /= 10) --i; + + // Is the rounding digit in the first word of d? + if (--i < 0) { + i += LOG_BASE; + di = 0; + } else { + di = Math.ceil((i + 1) / LOG_BASE); + i %= LOG_BASE; + } + + // i is the index (0 - 6) of the rounding digit. + // E.g. if within the word 3487563 the first rounding digit is 5, + // then i = 4, k = 1000, rd = 3487563 % 1000 = 563 + k = mathpow(10, LOG_BASE - i); + rd = d[di] % k | 0; + + if (repeating == null) { + if (i < 3) { + if (i == 0) rd = rd / 100 | 0; + else if (i == 1) rd = rd / 10 | 0; + r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0; + } else { + r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && + (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || + (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0; + } + } else { + if (i < 4) { + if (i == 0) rd = rd / 1000 | 0; + else if (i == 1) rd = rd / 100 | 0; + else if (i == 2) rd = rd / 10 | 0; + r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999; + } else { + r = ((repeating || rm < 4) && rd + 1 == k || + (!repeating && rm > 3) && rd + 1 == k / 2) && + (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1; + } + } + + return r; + } + + + // Convert string of `baseIn` to an array of numbers of `baseOut`. + // Eg. convertBase('255', 10, 16) returns [15, 15]. + // Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. + function convertBase(str, baseIn, baseOut) { + var j, + arr = [0], + arrL, + i = 0, + strL = str.length; + + for (; i < strL;) { + for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn; + arr[0] += NUMERALS.indexOf(str.charAt(i++)); + for (j = 0; j < arr.length; j++) { + if (arr[j] > baseOut - 1) { + if (arr[j + 1] === void 0) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + + /* + * cos(x) = 1 - x^2/2! + x^4/4! - ... + * |x| < pi/2 + * + */ + function cosine(Ctor, x) { + var k, len, y; + + if (x.isZero()) return x; + + // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1 + // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1 + + // Estimate the optimum number of times to use the argument reduction. + len = x.d.length; + if (len < 32) { + k = Math.ceil(len / 3); + y = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + y = '2.3283064365386962890625e-10'; + } + + Ctor.precision += k; + + x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1)); + + // Reverse argument reduction + for (var i = k; i--;) { + var cos2x = x.times(x); + x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1); + } + + Ctor.precision -= k; + + return x; + } + + + /* + * Perform division in the specified base. + */ + var divide = (function () { + + // Assumes non-zero x and k, and hence non-zero result. + function multiplyInteger(x, k, base) { + var temp, + carry = 0, + i = x.length; + + for (x = x.slice(); i--;) { + temp = x[i] * k + carry; + x[i] = temp % base | 0; + carry = temp / base | 0; + } + + if (carry) x.unshift(carry); + + return x; + } + + function compare(a, b, aL, bL) { + var i, r; + + if (aL != bL) { + r = aL > bL ? 1 : -1; + } else { + for (i = r = 0; i < aL; i++) { + if (a[i] != b[i]) { + r = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return r; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1;) a.shift(); + } + + return function (x, y, pr, rm, dp, base) { + var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, + yL, yz, + Ctor = x.constructor, + sign = x.s == y.s ? 1 : -1, + xd = x.d, + yd = y.d; + + // Either NaN, Infinity or 0? + if (!xd || !xd[0] || !yd || !yd[0]) { + + return new Ctor(// Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN : + + // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0. + xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0); + } + + if (base) { + logBase = 1; + e = x.e - y.e; + } else { + base = BASE; + logBase = LOG_BASE; + e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase); + } + + yL = yd.length; + xL = xd.length; + q = new Ctor(sign); + qd = q.d = []; + + // Result exponent may be one less than e. + // The digit array of a Decimal from toStringBinary may have trailing zeros. + for (i = 0; yd[i] == (xd[i] || 0); i++); + + if (yd[i] > (xd[i] || 0)) e--; + + if (pr == null) { + sd = pr = Ctor.precision; + rm = Ctor.rounding; + } else if (dp) { + sd = pr + (x.e - y.e) + 1; + } else { + sd = pr; + } + + if (sd < 0) { + qd.push(1); + more = true; + } else { + + // Convert precision in number of base 10 digits to base 1e7 digits. + sd = sd / logBase + 2 | 0; + i = 0; + + // divisor < 1e7 + if (yL == 1) { + k = 0; + yd = yd[0]; + sd++; + + // k is the carry. + for (; (i < xL || k) && sd--; i++) { + t = k * base + (xd[i] || 0); + qd[i] = t / yd | 0; + k = t % yd | 0; + } + + more = k || i < xL; + + // divisor >= 1e7 + } else { + + // Normalise xd and yd so highest order digit of yd is >= base/2 + k = base / (yd[0] + 1) | 0; + + if (k > 1) { + yd = multiplyInteger(yd, k, base); + xd = multiplyInteger(xd, k, base); + yL = yd.length; + xL = xd.length; + } + + xi = yL; + rem = xd.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL;) rem[remL++] = 0; + + yz = yd.slice(); + yz.unshift(0); + yd0 = yd[0]; + + if (yd[1] >= base / 2) ++yd0; + + do { + k = 0; + + // Compare divisor and remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, k. + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // k will be how many times the divisor goes into the current remainder. + k = rem0 / yd0 | 0; + + // Algorithm: + // 1. product = divisor * trial digit (k) + // 2. if product > remainder: product -= divisor, k-- + // 3. remainder -= product + // 4. if product was < remainder at 2: + // 5. compare new remainder and divisor + // 6. If remainder > divisor: remainder -= divisor, k++ + + if (k > 1) { + if (k >= base) k = base - 1; + + // product = divisor * trial digit. + prod = multiplyInteger(yd, k, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + cmp = compare(prod, rem, prodL, remL); + + // product > remainder. + if (cmp == 1) { + k--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yd, prodL, base); + } + } else { + + // cmp is -1. + // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1 + // to avoid it. If k is 1 there is a need to compare yd and rem again below. + if (k == 0) cmp = k = 1; + prod = yd.slice(); + } + + prodL = prod.length; + if (prodL < remL) prod.unshift(0); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + + // If product was < previous remainder. + if (cmp == -1) { + remL = rem.length; + + // Compare divisor and new remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < new remainder, subtract divisor from remainder. + if (cmp < 1) { + k++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yd, remL, base); + } + } + + remL = rem.length; + } else if (cmp === 0) { + k++; + rem = [0]; + } // if cmp === 1, k will be 0 + + // Add the next digit, k, to the result array. + qd[i++] = k; + + // Update the remainder. + if (cmp && rem[0]) { + rem[remL++] = xd[xi] || 0; + } else { + rem = [xd[xi]]; + remL = 1; + } + + } while ((xi++ < xL || rem[0] !== void 0) && sd--); + + more = rem[0] !== void 0; + } + + // Leading zero? + if (!qd[0]) qd.shift(); + } + + // logBase is 1 when divide is being used for base conversion. + if (logBase == 1) { + q.e = e; + inexact = more; + } else { + + // To calculate q.e, first get the number of digits of qd[0]. + for (i = 1, k = qd[0]; k >= 10; k /= 10) i++; + q.e = i + e * logBase - 1; + + finalise(q, dp ? pr + q.e + 1 : pr, rm, more); + } + + return q; + }; + })(); + + + /* + * Round `x` to `sd` significant digits using rounding mode `rm`. + * Check for over/under-flow. + */ + function finalise(x, sd, rm, isTruncated) { + var digits, i, j, k, rd, roundUp, w, xd, xdi, + Ctor = x.constructor; + + // Don't round if sd is null or undefined. + out: if (sd != null) { + xd = x.d; + + // Infinity/NaN. + if (!xd) return x; + + // rd: the rounding digit, i.e. the digit after the digit that may be rounded up. + // w: the word of xd containing rd, a base 1e7 number. + // xdi: the index of w within xd. + // digits: the number of digits of w. + // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if + // they had leading zeros) + // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero). + + // Get the length of the first word of the digits array xd. + for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++; + i = sd - digits; + + // Is the rounding digit in the first word of xd? + if (i < 0) { + i += LOG_BASE; + j = sd; + w = xd[xdi = 0]; + + // Get the rounding digit at index j of w. + rd = w / mathpow(10, digits - j - 1) % 10 | 0; + } else { + xdi = Math.ceil((i + 1) / LOG_BASE); + k = xd.length; + if (xdi >= k) { + if (isTruncated) { + + // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`. + for (; k++ <= xdi;) xd.push(0); + w = rd = 0; + digits = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + w = k = xd[xdi]; + + // Get the number of digits of w. + for (digits = 1; k >= 10; k /= 10) digits++; + + // Get the index of rd within w. + i %= LOG_BASE; + + // Get the index of rd within w, adjusted for leading zeros. + // The number of leading zeros of w is given by LOG_BASE - digits. + j = i - LOG_BASE + digits; + + // Get the rounding digit at index j of w. + rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0; + } + } + + // Are there any non-zero digits after the rounding digit? + isTruncated = isTruncated || sd < 0 || + xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1)); + + // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right + // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression + // will give 714. + + roundUp = rm < 4 + ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xd[0]) { + xd.length = 0; + if (roundUp) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE); + x.e = -sd || 0; + } else { + + // Zero. + xd[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xd.length = xdi; + k = 1; + xdi--; + } else { + xd.length = xdi + 1; + k = mathpow(10, LOG_BASE - i); + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of w. + xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0; + } + + if (roundUp) { + for (;;) { + + // Is the digit to be rounded up in the first word of xd? + if (xdi == 0) { + + // i will be the length of xd[0] before k is added. + for (i = 1, j = xd[0]; j >= 10; j /= 10) i++; + j = xd[0] += k; + for (k = 1; j >= 10; j /= 10) k++; + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xd[0] == BASE) xd[0] = 1; + } + + break; + } else { + xd[xdi] += k; + if (xd[xdi] != BASE) break; + xd[xdi--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xd.length; xd[--i] === 0;) xd.pop(); + } + + if (external) { + + // Overflow? + if (x.e > Ctor.maxE) { + + // Infinity. + x.d = null; + x.e = NaN; + + // Underflow? + } else if (x.e < Ctor.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + // Ctor.underflow = true; + } // else Ctor.underflow = false; + } + + return x; + } + + + function finiteToString(x, isExp, sd) { + if (!x.isFinite()) return nonFiniteToString(x); + var k, + e = x.e, + str = digitsToString(x.d), + len = str.length; + + if (isExp) { + if (sd && (k = sd - len) > 0) { + str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k); + } else if (len > 1) { + str = str.charAt(0) + '.' + str.slice(1); + } + + str = str + (x.e < 0 ? 'e' : 'e+') + x.e; + } else if (e < 0) { + str = '0.' + getZeroString(-e - 1) + str; + if (sd && (k = sd - len) > 0) str += getZeroString(k); + } else if (e >= len) { + str += getZeroString(e + 1 - len); + if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k); + } else { + if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k); + if (sd && (k = sd - len) > 0) { + if (e + 1 === len) str += '.'; + str += getZeroString(k); + } + } + + return str; + } + + + // Calculate the base 10 exponent from the base 1e7 exponent. + function getBase10Exponent(digits, e) { + var w = digits[0]; + + // Add the number of digits of the first word of the digits array. + for ( e *= LOG_BASE; w >= 10; w /= 10) e++; + return e; + } + + + function getLn10(Ctor, sd, pr) { + if (sd > LN10_PRECISION) { + + // Reset global state in case the exception is caught. + external = true; + if (pr) Ctor.precision = pr; + throw Error(precisionLimitExceeded); + } + return finalise(new Ctor(LN10), sd, 1, true); + } + + + function getPi(Ctor, sd, rm) { + if (sd > PI_PRECISION) throw Error(precisionLimitExceeded); + return finalise(new Ctor(PI), sd, rm, true); + } + + + function getPrecision(digits) { + var w = digits.length - 1, + len = w * LOG_BASE + 1; + + w = digits[w]; + + // If non-zero... + if (w) { + + // Subtract the number of trailing zeros of the last word. + for (; w % 10 == 0; w /= 10) len--; + + // Add the number of digits of the first word. + for (w = digits[0]; w >= 10; w /= 10) len++; + } + + return len; + } + + + function getZeroString(k) { + var zs = ''; + for (; k--;) zs += '0'; + return zs; + } + + + /* + * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an + * integer of type number. + * + * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`. + * + */ + function intPow(Ctor, x, n, pr) { + var isTruncated, + r = new Ctor(1), + + // Max n of 9007199254740991 takes 53 loop iterations. + // Maximum digits array length; leaves [28, 34] guard digits. + k = Math.ceil(pr / LOG_BASE + 4); + + external = false; + + for (;;) { + if (n % 2) { + r = r.times(x); + if (truncate(r.d, k)) isTruncated = true; + } + + n = mathfloor(n / 2); + if (n === 0) { + + // To ensure correct rounding when r.d is truncated, increment the last word if it is zero. + n = r.d.length - 1; + if (isTruncated && r.d[n] === 0) ++r.d[n]; + break; + } + + x = x.times(x); + truncate(x.d, k); + } + + external = true; + + return r; + } + + + function isOdd(n) { + return n.d[n.d.length - 1] & 1; + } + + + /* + * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'. + */ + function maxOrMin(Ctor, args, ltgt) { + var y, + x = new Ctor(args[0]), + i = 0; + + for (; ++i < args.length;) { + y = new Ctor(args[i]); + if (!y.s) { + x = y; + break; + } else if (x[ltgt](y)) { + x = y; + } + } + + return x; + } + + + /* + * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant + * digits. + * + * Taylor/Maclaurin series. + * + * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ... + * + * Argument reduction: + * Repeat x = x / 32, k += 5, until |x| < 0.1 + * exp(x) = exp(x / 2^k)^(2^k) + * + * Previously, the argument was initially reduced by + * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10) + * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was + * found to be slower than just dividing repeatedly by 32 as above. + * + * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000 + * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000 + * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324) + * + * exp(Infinity) = Infinity + * exp(-Infinity) = 0 + * exp(NaN) = NaN + * exp(±0) = 1 + * + * exp(x) is non-terminating for any finite, non-zero x. + * + * The result will always be correctly rounded. + * + */ + function naturalExponential(x, sd) { + var denominator, guard, j, pow, sum, t, wpr, + rep = 0, + i = 0, + k = 0, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; + + // 0/NaN/Infinity? + if (!x.d || !x.d[0] || x.e > 17) { + + return new Ctor(x.d + ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 + : x.s ? x.s < 0 ? 0 : x : 0 / 0); + } + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + t = new Ctor(0.03125); + + // while abs(x) >= 0.1 + while (x.e > -2) { + + // x = x / 2^5 + x = x.times(t); + k += 5; + } + + // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision + // necessary to ensure the first 4 rounding digits are correct. + guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0; + wpr += guard; + denominator = pow = sum = new Ctor(1); + Ctor.precision = wpr; + + for (;;) { + pow = finalise(pow.times(x), wpr, 1); + denominator = denominator.times(++i); + t = sum.plus(divide(pow, denominator, wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + j = k; + while (j--) sum = finalise(sum.times(sum), wpr, 1); + + // Check to see if the first 4 rounding digits are [49]999. + // If so, repeat the summation with a higher precision, otherwise + // e.g. with precision: 18, rounding: 1 + // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123) + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + + if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += 10; + denominator = pow = t = new Ctor(1); + i = 0; + rep++; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } + + sum = t; + } + } + + + /* + * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant + * digits. + * + * ln(-n) = NaN + * ln(0) = -Infinity + * ln(-0) = -Infinity + * ln(1) = 0 + * ln(Infinity) = Infinity + * ln(-Infinity) = NaN + * ln(NaN) = NaN + * + * ln(n) (n != 1) is non-terminating. + * + */ + function naturalLogarithm(y, sd) { + var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2, + n = 1, + guard = 10, + x = y, + xd = x.d, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; + + // Is x negative or Infinity, NaN, 0 or 1? + if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) { + return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x); + } + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + Ctor.precision = wpr += guard; + c = digitsToString(xd); + c0 = c.charAt(0); + + if (Math.abs(e = x.e) < 1.5e15) { + + // Argument reduction. + // The series converges faster the closer the argument is to 1, so using + // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b + // multiply the argument by itself until the leading digits of the significand are 7, 8, 9, + // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can + // later be divided by this number, then separate out the power of 10 using + // ln(a*10^b) = ln(a) + b*ln(10). + + // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14). + //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) { + // max n is 6 (gives 0.7 - 1.3) + while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) { + x = x.times(y); + c = digitsToString(x.d); + c0 = c.charAt(0); + n++; + } + + e = x.e; + + if (c0 > 1) { + x = new Ctor('0.' + c); + e++; + } else { + x = new Ctor(c0 + '.' + c.slice(1)); + } + } else { + + // The argument reduction method above may result in overflow if the argument y is a massive + // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this + // function using ln(x*10^e) = ln(x) + e*ln(10). + t = getLn10(Ctor, wpr + 2, pr).times(e + ''); + x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t); + Ctor.precision = pr; + + return sd == null ? finalise(x, pr, rm, external = true) : x; + } + + // x1 is x reduced to a value near 1. + x1 = x; + + // Taylor series. + // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...) + // where x = (y - 1)/(y + 1) (|x| < 1) + sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = 3; + + for (;;) { + numerator = finalise(numerator.times(x2), wpr, 1); + t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + sum = sum.times(2); + + // Reverse the argument reduction. Check that e is not 0 because, besides preventing an + // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0. + if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + '')); + sum = divide(sum, new Ctor(n), wpr, 1); + + // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has + // been repeated previously) and the first 4 rounding digits 9999? + // If so, restart the summation with a higher precision, otherwise + // e.g. with precision: 12, rounding: 1 + // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463. + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += guard; + t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = rep = 1; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } + + sum = t; + denominator += 2; + } + } + + + // ±Infinity, NaN. + function nonFiniteToString(x) { + // Unsigned. + return String(x.s * x.s / 0); + } + + + /* + * Parse the value of a new Decimal `x` from string `str`. + */ + function parseDecimal(x, str) { + var e, i, len; + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(len - 1) === 48; --len); + str = str.slice(i, len); + + if (str) { + len -= i; + x.e = e = e - i - 1; + x.d = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first word of the digits array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; + + if (i < len) { + if (i) x.d.push(+str.slice(0, i)); + for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE)); + str = str.slice(i); + i = LOG_BASE - str.length; + } else { + i -= len; + } + + for (; i--;) str += '0'; + x.d.push(+str); + + if (external) { + + // Overflow? + if (x.e > x.constructor.maxE) { + + // Infinity. + x.d = null; + x.e = NaN; + + // Underflow? + } else if (x.e < x.constructor.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + // x.constructor.underflow = true; + } // else x.constructor.underflow = false; + } + } else { + + // Zero. + x.e = 0; + x.d = [0]; + } + + return x; + } + + + /* + * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value. + */ + function parseOther(x, str) { + var base, Ctor, divisor, i, isFloat, len, p, xd, xe; + + if (str.indexOf('_') > -1) { + str = str.replace(/(\d)_(?=\d)/g, '$1'); + if (isDecimal.test(str)) return parseDecimal(x, str); + } else if (str === 'Infinity' || str === 'NaN') { + if (!+str) x.s = NaN; + x.e = NaN; + x.d = null; + return x; + } + + if (isHex.test(str)) { + base = 16; + str = str.toLowerCase(); + } else if (isBinary.test(str)) { + base = 2; + } else if (isOctal.test(str)) { + base = 8; + } else { + throw Error(invalidArgument + str); + } + + // Is there a binary exponent part? + i = str.search(/p/i); + + if (i > 0) { + p = +str.slice(i + 1); + str = str.substring(2, i); + } else { + str = str.slice(2); + } + + // Convert `str` as an integer then divide the result by `base` raised to a power such that the + // fraction part will be restored. + i = str.indexOf('.'); + isFloat = i >= 0; + Ctor = x.constructor; + + if (isFloat) { + str = str.replace('.', ''); + len = str.length; + i = len - i; + + // log[10](16) = 1.2041... , log[10](88) = 1.9444.... + divisor = intPow(Ctor, new Ctor(base), i, i * 2); + } + + xd = convertBase(str, base, BASE); + xe = xd.length - 1; + + // Remove trailing zeros. + for (i = xe; xd[i] === 0; --i) xd.pop(); + if (i < 0) return new Ctor(x.s * 0); + x.e = getBase10Exponent(xd, xe); + x.d = xd; + external = false; + + // At what precision to perform the division to ensure exact conversion? + // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount) + // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412 + // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits. + // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount + // Therefore using 4 * the number of digits of str will always be enough. + if (isFloat) x = divide(x, divisor, len * 4); + + // Multiply by the binary exponent part if present. + if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p)); + external = true; + + return x; + } + + + /* + * sin(x) = x - x^3/3! + x^5/5! - ... + * |x| < pi/2 + * + */ + function sine(Ctor, x) { + var k, + len = x.d.length; + + if (len < 3) { + return x.isZero() ? x : taylorSeries(Ctor, 2, x, x); + } + + // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x) + // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5) + // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20)) + + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; + + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x); + + // Reverse argument reduction + var sin2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sin2_x = x.times(x); + x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20)))); + } + + return x; + } + + + // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`. + function taylorSeries(Ctor, n, x, y, isHyperbolic) { + var j, t, u, x2, + i = 1, + pr = Ctor.precision, + k = Math.ceil(pr / LOG_BASE); + + external = false; + x2 = x.times(x); + u = new Ctor(y); + + for (;;) { + t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1); + u = isHyperbolic ? y.plus(t) : y.minus(t); + y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1); + t = u.plus(y); + + if (t.d[k] !== void 0) { + for (j = k; t.d[j] === u.d[j] && j--;); + if (j == -1) break; + } + + j = u; + u = y; + y = t; + t = j; + i++; + } + + external = true; + t.d.length = k + 1; + + return t; + } + + + // Exponent e must be positive and non-zero. + function tinyPow(b, e) { + var n = b; + while (--e) n *= b; + return n; + } + + + // Return the absolute value of `x` reduced to less than or equal to half pi. + function toLessThanHalfPi(Ctor, x) { + var t, + isNeg = x.s < 0, + pi = getPi(Ctor, Ctor.precision, 1), + halfPi = pi.times(0.5); + + x = x.abs(); + + if (x.lte(halfPi)) { + quadrant = isNeg ? 4 : 1; + return x; + } + + t = x.divToInt(pi); + + if (t.isZero()) { + quadrant = isNeg ? 3 : 2; + } else { + x = x.minus(t.times(pi)); + + // 0 <= x < pi + if (x.lte(halfPi)) { + quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1); + return x; + } + + quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2); + } + + return x.minus(pi).abs(); + } + + + /* + * Return the value of Decimal `x` as a string in base `baseOut`. + * + * If the optional `sd` argument is present include a binary exponent suffix. + */ + function toStringBinary(x, baseOut, sd, rm) { + var base, e, i, k, len, roundUp, str, xd, y, + Ctor = x.constructor, + isExp = sd !== void 0; + + if (isExp) { + checkInt32(sd, 1, MAX_DIGITS); + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } else { + sd = Ctor.precision; + rm = Ctor.rounding; + } + + if (!x.isFinite()) { + str = nonFiniteToString(x); + } else { + str = finiteToString(x); + i = str.indexOf('.'); + + // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required: + // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10)) + // minBinaryExponent = floor(decimalExponent * log[2](10)) + // log[2](10) = 3.321928094887362347870319429489390175864 + + if (isExp) { + base = 2; + if (baseOut == 16) { + sd = sd * 4 - 3; + } else if (baseOut == 8) { + sd = sd * 3 - 2; + } + } else { + base = baseOut; + } + + // Convert the number as an integer then divide the result by its base raised to a power such + // that the fraction part will be restored. + + // Non-integer. + if (i >= 0) { + str = str.replace('.', ''); + y = new Ctor(1); + y.e = str.length - i; + y.d = convertBase(finiteToString(y), 10, base); + y.e = y.d.length; + } + + xd = convertBase(str, 10, base); + e = len = xd.length; + + // Remove trailing zeros. + for (; xd[--len] == 0;) xd.pop(); + + if (!xd[0]) { + str = isExp ? '0p+0' : '0'; + } else { + if (i < 0) { + e--; + } else { + x = new Ctor(x); + x.d = xd; + x.e = e; + x = divide(x, y, sd, rm, 0, base); + xd = x.d; + e = x.e; + roundUp = inexact; + } + + // The rounding digit, i.e. the digit after the digit that may be rounded up. + i = xd[sd]; + k = base / 2; + roundUp = roundUp || xd[sd + 1] !== void 0; + + roundUp = rm < 4 + ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2)) + : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || + rm === (x.s < 0 ? 8 : 7)); + + xd.length = sd; + + if (roundUp) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (; ++xd[--sd] > base - 1;) { + xd[sd] = 0; + if (!sd) { + ++e; + xd.unshift(1); + } + } + } + + // Determine trailing zeros. + for (len = xd.length; !xd[len - 1]; --len); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]); + + // Add binary exponent suffix? + if (isExp) { + if (len > 1) { + if (baseOut == 16 || baseOut == 8) { + i = baseOut == 16 ? 4 : 3; + for (--len; len % i; len++) str += '0'; + xd = convertBase(str, base, baseOut); + for (len = xd.length; !xd[len - 1]; --len); + + // xd[0] will always be be 1 + for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]); + } else { + str = str.charAt(0) + '.' + str.slice(1); + } + } + + str = str + (e < 0 ? 'p' : 'p+') + e; + } else if (e < 0) { + for (; ++e;) str = '0' + str; + str = '0.' + str; + } else { + if (++e > len) for (e -= len; e-- ;) str += '0'; + else if (e < len) str = str.slice(0, e) + '.' + str.slice(e); + } + } + + str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str; + } + + return x.s < 0 ? '-' + str : str; + } + + + // Does not strip trailing zeros. + function truncate(arr, len) { + if (arr.length > len) { + arr.length = len; + return true; + } + } + + + // Decimal methods + + + /* + * abs + * acos + * acosh + * add + * asin + * asinh + * atan + * atanh + * atan2 + * cbrt + * ceil + * clamp + * clone + * config + * cos + * cosh + * div + * exp + * floor + * hypot + * ln + * log + * log2 + * log10 + * max + * min + * mod + * mul + * pow + * random + * round + * set + * sign + * sin + * sinh + * sqrt + * sub + * sum + * tan + * tanh + * trunc + */ + + + /* + * Return a new Decimal whose value is the absolute value of `x`. + * + * x {number|string|Decimal} + * + */ + function abs(x) { + return new this(x).abs(); + } + + + /* + * Return a new Decimal whose value is the arccosine in radians of `x`. + * + * x {number|string|Decimal} + * + */ + function acos(x) { + return new this(x).acos(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function acosh(x) { + return new this(x).acosh(); + } + + + /* + * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function add(x, y) { + return new this(x).plus(y); + } + + + /* + * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function asin(x) { + return new this(x).asin(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function asinh(x) { + return new this(x).asinh(); + } + + + /* + * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function atan(x) { + return new this(x).atan(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function atanh(x) { + return new this(x).atanh(); + } + + + /* + * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi + * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi, pi] + * + * y {number|string|Decimal} The y-coordinate. + * x {number|string|Decimal} The x-coordinate. + * + * atan2(±0, -0) = ±pi + * atan2(±0, +0) = ±0 + * atan2(±0, -x) = ±pi for x > 0 + * atan2(±0, x) = ±0 for x > 0 + * atan2(-y, ±0) = -pi/2 for y > 0 + * atan2(y, ±0) = pi/2 for y > 0 + * atan2(±y, -Infinity) = ±pi for finite y > 0 + * atan2(±y, +Infinity) = ±0 for finite y > 0 + * atan2(±Infinity, x) = ±pi/2 for finite x + * atan2(±Infinity, -Infinity) = ±3*pi/4 + * atan2(±Infinity, +Infinity) = ±pi/4 + * atan2(NaN, x) = NaN + * atan2(y, NaN) = NaN + * + */ + function atan2(y, x) { + y = new this(y); + x = new this(x); + var r, + pr = this.precision, + rm = this.rounding, + wpr = pr + 4; + + // Either NaN + if (!y.s || !x.s) { + r = new this(NaN); + + // Both ±Infinity + } else if (!y.d && !x.d) { + r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75); + r.s = y.s; + + // x is ±Infinity or y is ±0 + } else if (!x.d || y.isZero()) { + r = x.s < 0 ? getPi(this, pr, rm) : new this(0); + r.s = y.s; + + // y is ±Infinity or x is ±0 + } else if (!y.d || x.isZero()) { + r = getPi(this, wpr, 1).times(0.5); + r.s = y.s; + + // Both non-zero and finite + } else if (x.s < 0) { + this.precision = wpr; + this.rounding = 1; + r = this.atan(divide(y, x, wpr, 1)); + x = getPi(this, wpr, 1); + this.precision = pr; + this.rounding = rm; + r = y.s < 0 ? r.minus(x) : r.plus(x); + } else { + r = this.atan(divide(y, x, wpr, 1)); + } + + return r; + } + + + /* + * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function cbrt(x) { + return new this(x).cbrt(); + } + + + /* + * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`. + * + * x {number|string|Decimal} + * + */ + function ceil(x) { + return finalise(x = new this(x), x.e + 1, 2); + } + + + /* + * Return a new Decimal whose value is `x` clamped to the range delineated by `min` and `max`. + * + * x {number|string|Decimal} + * min {number|string|Decimal} + * max {number|string|Decimal} + * + */ + function clamp(x, min, max) { + return new this(x).clamp(min, max); + } + + + /* + * Configure global settings for a Decimal constructor. + * + * `obj` is an object with one or more of the following properties, + * + * precision {number} + * rounding {number} + * toExpNeg {number} + * toExpPos {number} + * maxE {number} + * minE {number} + * modulo {number} + * crypto {boolean|number} + * defaults {true} + * + * E.g. Decimal.config({ precision: 20, rounding: 4 }) + * + */ + function config(obj) { + if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); + var i, p, v, + useDefaults = obj.defaults === true, + ps = [ + 'precision', 1, MAX_DIGITS, + 'rounding', 0, 8, + 'toExpNeg', -EXP_LIMIT, 0, + 'toExpPos', 0, EXP_LIMIT, + 'maxE', 0, EXP_LIMIT, + 'minE', -EXP_LIMIT, 0, + 'modulo', 0, 9 + ]; + + for (i = 0; i < ps.length; i += 3) { + if (p = ps[i], useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; + else throw Error(invalidArgument + p + ': ' + v); + } + } + + if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (v === true || v === false || v === 0 || v === 1) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + this[p] = true; + } else { + throw Error(cryptoUnavailable); + } + } else { + this[p] = false; + } + } else { + throw Error(invalidArgument + p + ': ' + v); + } + } + + return this; + } + + + /* + * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function cos(x) { + return new this(x).cos(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function cosh(x) { + return new this(x).cosh(); + } + + + /* + * Create and return a Decimal constructor with the same configuration properties as this Decimal + * constructor. + * + */ + function clone(obj) { + var i, p, ps; + + /* + * The Decimal constructor and exported function. + * Return a new Decimal instance. + * + * v {number|string|Decimal} A numeric value. + * + */ + function Decimal(v) { + var e, i, t, + x = this; + + // Decimal called without new. + if (!(x instanceof Decimal)) return new Decimal(v); + + // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor + // which points to Object. + x.constructor = Decimal; + + // Duplicate. + if (isDecimalInstance(v)) { + x.s = v.s; + + if (external) { + if (!v.d || v.e > Decimal.maxE) { + + // Infinity. + x.e = NaN; + x.d = null; + } else if (v.e < Decimal.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + } else { + x.e = v.e; + x.d = v.d.slice(); + } + } else { + x.e = v.e; + x.d = v.d ? v.d.slice() : v.d; + } + + return; + } + + t = typeof v; + + if (t === 'number') { + if (v === 0) { + x.s = 1 / v < 0 ? -1 : 1; + x.e = 0; + x.d = [0]; + return; + } + + if (v < 0) { + v = -v; + x.s = -1; + } else { + x.s = 1; + } + + // Fast path for small integers. + if (v === ~~v && v < 1e7) { + for (e = 0, i = v; i >= 10; i /= 10) e++; + + if (external) { + if (e > Decimal.maxE) { + x.e = NaN; + x.d = null; + } else if (e < Decimal.minE) { + x.e = 0; + x.d = [0]; + } else { + x.e = e; + x.d = [v]; + } + } else { + x.e = e; + x.d = [v]; + } + + return; + + // Infinity, NaN. + } else if (v * 0 !== 0) { + if (!v) x.s = NaN; + x.e = NaN; + x.d = null; + return; + } + + return parseDecimal(x, v.toString()); + + } else if (t !== 'string') { + throw Error(invalidArgument + v); + } + + // Minus sign? + if ((i = v.charCodeAt(0)) === 45) { + v = v.slice(1); + x.s = -1; + } else { + // Plus sign? + if (i === 43) v = v.slice(1); + x.s = 1; + } + + return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); + } + + Decimal.prototype = P; + + Decimal.ROUND_UP = 0; + Decimal.ROUND_DOWN = 1; + Decimal.ROUND_CEIL = 2; + Decimal.ROUND_FLOOR = 3; + Decimal.ROUND_HALF_UP = 4; + Decimal.ROUND_HALF_DOWN = 5; + Decimal.ROUND_HALF_EVEN = 6; + Decimal.ROUND_HALF_CEIL = 7; + Decimal.ROUND_HALF_FLOOR = 8; + Decimal.EUCLID = 9; + + Decimal.config = Decimal.set = config; + Decimal.clone = clone; + Decimal.isDecimal = isDecimalInstance; + + Decimal.abs = abs; + Decimal.acos = acos; + Decimal.acosh = acosh; // ES6 + Decimal.add = add; + Decimal.asin = asin; + Decimal.asinh = asinh; // ES6 + Decimal.atan = atan; + Decimal.atanh = atanh; // ES6 + Decimal.atan2 = atan2; + Decimal.cbrt = cbrt; // ES6 + Decimal.ceil = ceil; + Decimal.clamp = clamp; + Decimal.cos = cos; + Decimal.cosh = cosh; // ES6 + Decimal.div = div; + Decimal.exp = exp; + Decimal.floor = floor; + Decimal.hypot = hypot; // ES6 + Decimal.ln = ln; + Decimal.log = log; + Decimal.log10 = log10; // ES6 + Decimal.log2 = log2; // ES6 + Decimal.max = max; + Decimal.min = min; + Decimal.mod = mod; + Decimal.mul = mul; + Decimal.pow = pow; + Decimal.random = random; + Decimal.round = round; + Decimal.sign = sign; // ES6 + Decimal.sin = sin; + Decimal.sinh = sinh; // ES6 + Decimal.sqrt = sqrt; + Decimal.sub = sub; + Decimal.sum = sum; + Decimal.tan = tan; + Decimal.tanh = tanh; // ES6 + Decimal.trunc = trunc; // ES6 + + if (obj === void 0) obj = {}; + if (obj) { + if (obj.defaults !== true) { + ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto']; + for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; + } + } + + Decimal.config(obj); + + return Decimal; + } + + + /* + * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function div(x, y) { + return new this(x).div(y); + } + + + /* + * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The power to which to raise the base of the natural log. + * + */ + function exp(x) { + return new this(x).exp(); + } + + + /* + * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`. + * + * x {number|string|Decimal} + * + */ + function floor(x) { + return finalise(x = new this(x), x.e + 1, 3); + } + + + /* + * Return a new Decimal whose value is the square root of the sum of the squares of the arguments, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...) + * + * arguments {number|string|Decimal} + * + */ + function hypot() { + var i, n, + t = new this(0); + + external = false; + + for (i = 0; i < arguments.length;) { + n = new this(arguments[i++]); + if (!n.d) { + if (n.s) { + external = true; + return new this(1 / 0); + } + t = n; + } else if (t.d) { + t = t.plus(n.times(n)); + } + } + + external = true; + + return t.sqrt(); + } + + + /* + * Return true if object is a Decimal instance (where Decimal is any Decimal constructor), + * otherwise return false. + * + */ + function isDecimalInstance(obj) { + return obj instanceof Decimal || obj && obj.toStringTag === tag || false; + } + + + /* + * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function ln(x) { + return new this(x).ln(); + } + + + /* + * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base + * is specified, rounded to `precision` significant digits using rounding mode `rounding`. + * + * log[y](x) + * + * x {number|string|Decimal} The argument of the logarithm. + * y {number|string|Decimal} The base of the logarithm. + * + */ + function log(x, y) { + return new this(x).log(y); + } + + + /* + * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function log2(x) { + return new this(x).log(2); + } + + + /* + * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function log10(x) { + return new this(x).log(10); + } + + + /* + * Return a new Decimal whose value is the maximum of the arguments. + * + * arguments {number|string|Decimal} + * + */ + function max() { + return maxOrMin(this, arguments, 'lt'); + } + + + /* + * Return a new Decimal whose value is the minimum of the arguments. + * + * arguments {number|string|Decimal} + * + */ + function min() { + return maxOrMin(this, arguments, 'gt'); + } + + + /* + * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function mod(x, y) { + return new this(x).mod(y); + } + + + /* + * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function mul(x, y) { + return new this(x).mul(y); + } + + + /* + * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The base. + * y {number|string|Decimal} The exponent. + * + */ + function pow(x, y) { + return new this(x).pow(y); + } + + + /* + * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with + * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros + * are produced). + * + * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive. + * + */ + function random(sd) { + var d, e, k, n, + i = 0, + r = new this(1), + rd = []; + + if (sd === void 0) sd = this.precision; + else checkInt32(sd, 1, MAX_DIGITS); + + k = Math.ceil(sd / LOG_BASE); + + if (!this.crypto) { + for (; i < k;) rd[i++] = Math.random() * 1e7 | 0; + + // Browsers supporting crypto.getRandomValues. + } else if (crypto.getRandomValues) { + d = crypto.getRandomValues(new Uint32Array(k)); + + for (; i < k;) { + n = d[i]; + + // 0 <= n < 4294967296 + // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865). + if (n >= 4.29e9) { + d[i] = crypto.getRandomValues(new Uint32Array(1))[0]; + } else { + + // 0 <= n <= 4289999999 + // 0 <= (n % 1e7) <= 9999999 + rd[i++] = n % 1e7; + } + } + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + d = crypto.randomBytes(k *= 4); + + for (; i < k;) { + + // 0 <= n < 2147483648 + n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24); + + // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286). + if (n >= 2.14e9) { + crypto.randomBytes(4).copy(d, i); + } else { + + // 0 <= n <= 2139999999 + // 0 <= (n % 1e7) <= 9999999 + rd.push(n % 1e7); + i += 4; + } + } + + i = k / 4; + } else { + throw Error(cryptoUnavailable); + } + + k = rd[--i]; + sd %= LOG_BASE; + + // Convert trailing digits to zeros according to sd. + if (k && sd) { + n = mathpow(10, LOG_BASE - sd); + rd[i] = (k / n | 0) * n; + } + + // Remove trailing words which are zero. + for (; rd[i] === 0; i--) rd.pop(); + + // Zero? + if (i < 0) { + e = 0; + rd = [0]; + } else { + e = -1; + + // Remove leading words which are zero and adjust exponent accordingly. + for (; rd[0] === 0; e -= LOG_BASE) rd.shift(); + + // Count the digits of the first word of rd to determine leading zeros. + for (k = 1, n = rd[0]; n >= 10; n /= 10) k++; + + // Adjust the exponent for leading zeros of the first word of rd. + if (k < LOG_BASE) e -= LOG_BASE - k; + } + + r.e = e; + r.d = rd; + + return r; + } + + + /* + * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`. + * + * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL). + * + * x {number|string|Decimal} + * + */ + function round(x) { + return finalise(x = new this(x), x.e + 1, this.rounding); + } + + + /* + * Return + * 1 if x > 0, + * -1 if x < 0, + * 0 if x is 0, + * -0 if x is -0, + * NaN otherwise + * + * x {number|string|Decimal} + * + */ + function sign(x) { + x = new this(x); + return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN; + } + + + /* + * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function sin(x) { + return new this(x).sin(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function sinh(x) { + return new this(x).sinh(); + } + + + /* + * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function sqrt(x) { + return new this(x).sqrt(); + } + + + /* + * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function sub(x, y) { + return new this(x).sub(y); + } + + + /* + * Return a new Decimal whose value is the sum of the arguments, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * Only the result is rounded, not the intermediate calculations. + * + * arguments {number|string|Decimal} + * + */ + function sum() { + var i = 0, + args = arguments, + x = new this(args[i]); + + external = false; + for (; x.s && ++i < args.length;) x = x.plus(args[i]); + external = true; + + return finalise(x, this.precision, this.rounding); + } + + + /* + * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function tan(x) { + return new this(x).tan(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function tanh(x) { + return new this(x).tanh(); + } + + + /* + * Return a new Decimal whose value is `x` truncated to an integer. + * + * x {number|string|Decimal} + * + */ + function trunc(x) { + return finalise(x = new this(x), x.e + 1, 1); + } + + + // Create and configure initial Decimal constructor. + Decimal = clone(DEFAULTS); + Decimal.prototype.constructor = Decimal; + Decimal['default'] = Decimal.Decimal = Decimal; + + // Create the internal constants from their string values. + LN10 = new Decimal(LN10); + PI = new Decimal(PI); + + + // Export. + + + // AMD. + if (typeof define == 'function' && define.amd) { + define(function () { + return Decimal; + }); + + // Node and other environments that support module.exports. + } else if (typeof module != 'undefined' && module.exports) { + if (typeof Symbol == 'function' && typeof Symbol.iterator == 'symbol') { + P[Symbol['for']('nodejs.util.inspect.custom')] = P.toString; + P[Symbol.toStringTag] = 'Decimal'; + } + + module.exports = Decimal; + + // Browser. + } else { + if (!globalScope) { + globalScope = typeof self != 'undefined' && self && self.self == self ? self : window; + } + + noConflict = globalScope.Decimal; + Decimal.noConflict = function () { + globalScope.Decimal = noConflict; + return Decimal; + }; + + globalScope.Decimal = Decimal; + } +})(this); diff --git a/node_modules/decimal.js/decimal.mjs b/node_modules/decimal.js/decimal.mjs new file mode 100644 index 0000000..03f385d --- /dev/null +++ b/node_modules/decimal.js/decimal.mjs @@ -0,0 +1,4898 @@ +/* + * decimal.js v10.3.1 + * An arbitrary-precision Decimal type for JavaScript. + * https://github.com/MikeMcl/decimal.js + * Copyright (c) 2021 Michael Mclaughlin + * MIT Licence + */ + + +// ----------------------------------- EDITABLE DEFAULTS ------------------------------------ // + + + // The maximum exponent magnitude. + // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`. +var EXP_LIMIT = 9e15, // 0 to 9e15 + + // The limit on the value of `precision`, and on the value of the first argument to + // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`. + MAX_DIGITS = 1e9, // 0 to 1e9 + + // Base conversion alphabet. + NUMERALS = '0123456789abcdef', + + // The natural logarithm of 10 (1025 digits). + LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058', + + // Pi (1025 digits). + PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789', + + + // The initial configuration properties of the Decimal constructor. + DEFAULTS = { + + // These values must be integers within the stated ranges (inclusive). + // Most of these values can be changed at run-time using the `Decimal.config` method. + + // The maximum number of significant digits of the result of a calculation or base conversion. + // E.g. `Decimal.config({ precision: 20 });` + precision: 20, // 1 to MAX_DIGITS + + // The rounding mode used when rounding to `precision`. + // + // ROUND_UP 0 Away from zero. + // ROUND_DOWN 1 Towards zero. + // ROUND_CEIL 2 Towards +Infinity. + // ROUND_FLOOR 3 Towards -Infinity. + // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + // + // E.g. + // `Decimal.rounding = 4;` + // `Decimal.rounding = Decimal.ROUND_HALF_UP;` + rounding: 4, // 0 to 8 + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend (JavaScript %). + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 The IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive. + // + // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian + // division (9) are commonly used for the modulus operation. The other rounding modes can also + // be used, but they may not give useful results. + modulo: 1, // 0 to 9 + + // The exponent value at and beneath which `toString` returns exponential notation. + // JavaScript numbers: -7 + toExpNeg: -7, // 0 to -EXP_LIMIT + + // The exponent value at and above which `toString` returns exponential notation. + // JavaScript numbers: 21 + toExpPos: 21, // 0 to EXP_LIMIT + + // The minimum exponent value, beneath which underflow to zero occurs. + // JavaScript numbers: -324 (5e-324) + minE: -EXP_LIMIT, // -1 to -EXP_LIMIT + + // The maximum exponent value, above which overflow to Infinity occurs. + // JavaScript numbers: 308 (1.7976931348623157e+308) + maxE: EXP_LIMIT, // 1 to EXP_LIMIT + + // Whether to use cryptographically-secure random number generation, if available. + crypto: false // true/false + }, + + +// ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- // + + + inexact, quadrant, + external = true, + + decimalError = '[DecimalError] ', + invalidArgument = decimalError + 'Invalid argument: ', + precisionLimitExceeded = decimalError + 'Precision limit exceeded', + cryptoUnavailable = decimalError + 'crypto unavailable', + tag = '[object Decimal]', + + mathfloor = Math.floor, + mathpow = Math.pow, + + isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i, + isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i, + isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i, + isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, + + BASE = 1e7, + LOG_BASE = 7, + MAX_SAFE_INTEGER = 9007199254740991, + + LN10_PRECISION = LN10.length - 1, + PI_PRECISION = PI.length - 1, + + // Decimal.prototype object + P = { toStringTag: tag }; + + +// Decimal prototype methods + + +/* + * absoluteValue abs + * ceil + * clampedTo clamp + * comparedTo cmp + * cosine cos + * cubeRoot cbrt + * decimalPlaces dp + * dividedBy div + * dividedToIntegerBy divToInt + * equals eq + * floor + * greaterThan gt + * greaterThanOrEqualTo gte + * hyperbolicCosine cosh + * hyperbolicSine sinh + * hyperbolicTangent tanh + * inverseCosine acos + * inverseHyperbolicCosine acosh + * inverseHyperbolicSine asinh + * inverseHyperbolicTangent atanh + * inverseSine asin + * inverseTangent atan + * isFinite + * isInteger isInt + * isNaN + * isNegative isNeg + * isPositive isPos + * isZero + * lessThan lt + * lessThanOrEqualTo lte + * logarithm log + * [maximum] [max] + * [minimum] [min] + * minus sub + * modulo mod + * naturalExponential exp + * naturalLogarithm ln + * negated neg + * plus add + * precision sd + * round + * sine sin + * squareRoot sqrt + * tangent tan + * times mul + * toBinary + * toDecimalPlaces toDP + * toExponential + * toFixed + * toFraction + * toHexadecimal toHex + * toNearest + * toNumber + * toOctal + * toPower pow + * toPrecision + * toSignificantDigits toSD + * toString + * truncated trunc + * valueOf toJSON + */ + + +/* + * Return a new Decimal whose value is the absolute value of this Decimal. + * + */ +P.absoluteValue = P.abs = function () { + var x = new this.constructor(this); + if (x.s < 0) x.s = 1; + return finalise(x); +}; + + +/* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of positive Infinity. + * + */ +P.ceil = function () { + return finalise(new this.constructor(this), this.e + 1, 2); +}; + + +/* + * Return a new Decimal whose value is the value of this Decimal clamped to the range + * delineated by `min` and `max`. + * + * min {number|string|Decimal} + * max {number|string|Decimal} + * + */ +P.clampedTo = P.clamp = function (min, max) { + var k, + x = this, + Ctor = x.constructor; + min = new Ctor(min); + max = new Ctor(max); + if (!min.s || !max.s) return new Ctor(NaN); + if (min.gt(max)) throw Error(invalidArgument + max); + k = x.cmp(min); + return k < 0 ? min : x.cmp(max) > 0 ? max : new Ctor(x); +}; + + +/* + * Return + * 1 if the value of this Decimal is greater than the value of `y`, + * -1 if the value of this Decimal is less than the value of `y`, + * 0 if they have the same value, + * NaN if the value of either Decimal is NaN. + * + */ +P.comparedTo = P.cmp = function (y) { + var i, j, xdL, ydL, + x = this, + xd = x.d, + yd = (y = new x.constructor(y)).d, + xs = x.s, + ys = y.s; + + // Either NaN or ±Infinity? + if (!xd || !yd) { + return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; + } + + // Either zero? + if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; + + // Signs differ? + if (xs !== ys) return xs; + + // Compare exponents. + if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; + + xdL = xd.length; + ydL = yd.length; + + // Compare digit by digit. + for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { + if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; + } + + // Compare lengths. + return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; +}; + + +/* + * Return a new Decimal whose value is the cosine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * cos(0) = 1 + * cos(-0) = 1 + * cos(Infinity) = NaN + * cos(-Infinity) = NaN + * cos(NaN) = NaN + * + */ +P.cosine = P.cos = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.d) return new Ctor(NaN); + + // cos(0) = cos(-0) = 1 + if (!x.d[0]) return new Ctor(1); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; + + x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); +}; + + +/* + * + * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * cbrt(0) = 0 + * cbrt(-0) = -0 + * cbrt(1) = 1 + * cbrt(-1) = -1 + * cbrt(N) = N + * cbrt(-I) = -I + * cbrt(I) = I + * + * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3)) + * + */ +P.cubeRoot = P.cbrt = function () { + var e, m, n, r, rep, s, sd, t, t3, t3plusx, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + external = false; + + // Initial estimate. + s = x.s * mathpow(x.s * x, 1 / 3); + + // Math.cbrt underflow/overflow? + // Pass x to Math.pow as integer, then adjust the exponent of the result. + if (!s || Math.abs(s) == 1 / 0) { + n = digitsToString(x.d); + e = x.e; + + // Adjust n exponent so it is a multiple of 3 away from x exponent. + if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); + s = mathpow(n, 1 / 3); + + // Rarely, e may be one less than the result exponent value. + e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + r.s = x.s; + } else { + r = new Ctor(s.toString()); + } + + sd = (e = Ctor.precision) + 3; + + // Halley's method. + // TODO? Compare Newton's method. + for (;;) { + t = r; + t3 = t.times(t).times(t); + t3plusx = t3.plus(x); + r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); + + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 + // , i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); + + if (t.times(t).times(t).eq(x)) { + r = t; + break; + } + } + + sd += 4; + rep = 1; + } else { + + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).times(r).eq(x); + } + + break; + } + } + } + + external = true; + + return finalise(r, e, Ctor.rounding, m); +}; + + +/* + * Return the number of decimal places of the value of this Decimal. + * + */ +P.decimalPlaces = P.dp = function () { + var w, + d = this.d, + n = NaN; + + if (d) { + w = d.length - 1; + n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last word. + w = d[w]; + if (w) for (; w % 10 == 0; w /= 10) n--; + if (n < 0) n = 0; + } + + return n; +}; + + +/* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + */ +P.dividedBy = P.div = function (y) { + return divide(this, new this.constructor(y)); +}; + + +/* + * Return a new Decimal whose value is the integer part of dividing the value of this Decimal + * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`. + * + */ +P.dividedToIntegerBy = P.divToInt = function (y) { + var x = this, + Ctor = x.constructor; + return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); +}; + + +/* + * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. + * + */ +P.equals = P.eq = function (y) { + return this.cmp(y) === 0; +}; + + +/* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of negative Infinity. + * + */ +P.floor = function () { + return finalise(new this.constructor(this), this.e + 1, 3); +}; + + +/* + * Return true if the value of this Decimal is greater than the value of `y`, otherwise return + * false. + * + */ +P.greaterThan = P.gt = function (y) { + return this.cmp(y) > 0; +}; + + +/* + * Return true if the value of this Decimal is greater than or equal to the value of `y`, + * otherwise return false. + * + */ +P.greaterThanOrEqualTo = P.gte = function (y) { + var k = this.cmp(y); + return k == 1 || k === 0; +}; + + +/* + * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [1, Infinity] + * + * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ... + * + * cosh(0) = 1 + * cosh(-0) = 1 + * cosh(Infinity) = Infinity + * cosh(-Infinity) = Infinity + * cosh(NaN) = NaN + * + * x time taken (ms) result + * 1000 9 9.8503555700852349694e+433 + * 10000 25 4.4034091128314607936e+4342 + * 100000 171 1.4033316802130615897e+43429 + * 1000000 3817 1.5166076984010437725e+434294 + * 10000000 abandoned after 2 minute wait + * + * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x)) + * + */ +P.hyperbolicCosine = P.cosh = function () { + var k, n, pr, rm, len, + x = this, + Ctor = x.constructor, + one = new Ctor(1); + + if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); + if (x.isZero()) return one; + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; + + // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 + // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) + + // Estimate the optimum number of times to use the argument reduction. + // TODO? Estimation reused from cosine() and may not be optimal here. + if (len < 32) { + k = Math.ceil(len / 3); + n = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + n = '2.3283064365386962890625e-10'; + } + + x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); + + // Reverse argument reduction + var cosh2_x, + i = k, + d8 = new Ctor(8); + for (; i--;) { + cosh2_x = x.times(x); + x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); + } + + return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); +}; + + +/* + * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ... + * + * sinh(0) = 0 + * sinh(-0) = -0 + * sinh(Infinity) = Infinity + * sinh(-Infinity) = -Infinity + * sinh(NaN) = NaN + * + * x time taken (ms) + * 10 2 ms + * 100 5 ms + * 1000 14 ms + * 10000 82 ms + * 100000 886 ms 1.4033316802130615897e+43429 + * 200000 2613 ms + * 300000 5407 ms + * 400000 8824 ms + * 500000 13026 ms 8.7080643612718084129e+217146 + * 1000000 48543 ms + * + * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x)) + * + */ +P.hyperbolicSine = P.sinh = function () { + var k, pr, rm, len, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; + + if (len < 3) { + x = taylorSeries(Ctor, 2, x, x, true); + } else { + + // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) + // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) + // 3 multiplications and 1 addition + + // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) + // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) + // 4 multiplications and 2 additions + + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; + + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x, true); + + // Reverse argument reduction + var sinh2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sinh2_x = x.times(x); + x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); + } + } + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(x, pr, rm, true); +}; + + +/* + * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * tanh(x) = sinh(x) / cosh(x) + * + * tanh(0) = 0 + * tanh(-0) = -0 + * tanh(Infinity) = 1 + * tanh(-Infinity) = -1 + * tanh(NaN) = NaN + * + */ +P.hyperbolicTangent = P.tanh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(x.s); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 7; + Ctor.rounding = 1; + + return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); +}; + + +/* + * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of + * this Decimal. + * + * Domain: [-1, 1] + * Range: [0, pi] + * + * acos(x) = pi/2 - asin(x) + * + * acos(0) = pi/2 + * acos(-0) = pi/2 + * acos(1) = 0 + * acos(-1) = pi + * acos(1/2) = pi/3 + * acos(-1/2) = 2*pi/3 + * acos(|x| > 1) = NaN + * acos(NaN) = NaN + * + */ +P.inverseCosine = P.acos = function () { + var halfPi, + x = this, + Ctor = x.constructor, + k = x.abs().cmp(1), + pr = Ctor.precision, + rm = Ctor.rounding; + + if (k !== -1) { + return k === 0 + // |x| is 1 + ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) + // |x| > 1 or x is NaN + : new Ctor(NaN); + } + + if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); + + // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 + + Ctor.precision = pr + 6; + Ctor.rounding = 1; + + x = x.asin(); + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return halfPi.minus(x); +}; + + +/* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the + * value of this Decimal. + * + * Domain: [1, Infinity] + * Range: [0, Infinity] + * + * acosh(x) = ln(x + sqrt(x^2 - 1)) + * + * acosh(x < 1) = NaN + * acosh(NaN) = NaN + * acosh(Infinity) = Infinity + * acosh(-Infinity) = NaN + * acosh(0) = NaN + * acosh(-0) = NaN + * acosh(1) = 0 + * acosh(-1) = NaN + * + */ +P.inverseHyperbolicCosine = P.acosh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); + if (!x.isFinite()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; + Ctor.rounding = 1; + external = false; + + x = x.times(x).minus(1).sqrt().plus(x); + + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.ln(); +}; + + +/* + * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * asinh(x) = ln(x + sqrt(x^2 + 1)) + * + * asinh(NaN) = NaN + * asinh(Infinity) = Infinity + * asinh(-Infinity) = -Infinity + * asinh(0) = 0 + * asinh(-0) = -0 + * + */ +P.inverseHyperbolicSine = P.asinh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; + Ctor.rounding = 1; + external = false; + + x = x.times(x).plus(1).sqrt().plus(x); + + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.ln(); +}; + + +/* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the + * value of this Decimal. + * + * Domain: [-1, 1] + * Range: [-Infinity, Infinity] + * + * atanh(x) = 0.5 * ln((1 + x) / (1 - x)) + * + * atanh(|x| > 1) = NaN + * atanh(NaN) = NaN + * atanh(Infinity) = NaN + * atanh(-Infinity) = NaN + * atanh(0) = 0 + * atanh(-0) = -0 + * atanh(1) = Infinity + * atanh(-1) = -Infinity + * + */ +P.inverseHyperbolicTangent = P.atanh = function () { + var pr, rm, wpr, xsd, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); + + pr = Ctor.precision; + rm = Ctor.rounding; + xsd = x.sd(); + + if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); + + Ctor.precision = wpr = xsd - x.e; + + x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); + + Ctor.precision = pr + 4; + Ctor.rounding = 1; + + x = x.ln(); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.times(0.5); +}; + + +/* + * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2))) + * + * asin(0) = 0 + * asin(-0) = -0 + * asin(1/2) = pi/6 + * asin(-1/2) = -pi/6 + * asin(1) = pi/2 + * asin(-1) = -pi/2 + * asin(|x| > 1) = NaN + * asin(NaN) = NaN + * + * TODO? Compare performance of Taylor series. + * + */ +P.inverseSine = P.asin = function () { + var halfPi, k, + pr, rm, + x = this, + Ctor = x.constructor; + + if (x.isZero()) return new Ctor(x); + + k = x.abs().cmp(1); + pr = Ctor.precision; + rm = Ctor.rounding; + + if (k !== -1) { + + // |x| is 1 + if (k === 0) { + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); + halfPi.s = x.s; + return halfPi; + } + + // |x| > 1 or x is NaN + return new Ctor(NaN); + } + + // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 + + Ctor.precision = pr + 6; + Ctor.rounding = 1; + + x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.times(2); +}; + + +/* + * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + * + * atan(0) = 0 + * atan(-0) = -0 + * atan(1) = pi/4 + * atan(-1) = -pi/4 + * atan(Infinity) = pi/2 + * atan(-Infinity) = -pi/2 + * atan(NaN) = NaN + * + */ +P.inverseTangent = P.atan = function () { + var i, j, k, n, px, t, r, wpr, x2, + x = this, + Ctor = x.constructor, + pr = Ctor.precision, + rm = Ctor.rounding; + + if (!x.isFinite()) { + if (!x.s) return new Ctor(NaN); + if (pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.5); + r.s = x.s; + return r; + } + } else if (x.isZero()) { + return new Ctor(x); + } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.25); + r.s = x.s; + return r; + } + + Ctor.precision = wpr = pr + 10; + Ctor.rounding = 1; + + // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); + + // Argument reduction + // Ensure |x| < 0.42 + // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) + + k = Math.min(28, wpr / LOG_BASE + 2 | 0); + + for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); + + external = false; + + j = Math.ceil(wpr / LOG_BASE); + n = 1; + x2 = x.times(x); + r = new Ctor(x); + px = x; + + // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + for (; i !== -1;) { + px = px.times(x2); + t = r.minus(px.div(n += 2)); + + px = px.times(x2); + r = t.plus(px.div(n += 2)); + + if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); + } + + if (k) r = r.times(2 << (k - 1)); + + external = true; + + return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); +}; + + +/* + * Return true if the value of this Decimal is a finite number, otherwise return false. + * + */ +P.isFinite = function () { + return !!this.d; +}; + + +/* + * Return true if the value of this Decimal is an integer, otherwise return false. + * + */ +P.isInteger = P.isInt = function () { + return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; +}; + + +/* + * Return true if the value of this Decimal is NaN, otherwise return false. + * + */ +P.isNaN = function () { + return !this.s; +}; + + +/* + * Return true if the value of this Decimal is negative, otherwise return false. + * + */ +P.isNegative = P.isNeg = function () { + return this.s < 0; +}; + + +/* + * Return true if the value of this Decimal is positive, otherwise return false. + * + */ +P.isPositive = P.isPos = function () { + return this.s > 0; +}; + + +/* + * Return true if the value of this Decimal is 0 or -0, otherwise return false. + * + */ +P.isZero = function () { + return !!this.d && this.d[0] === 0; +}; + + +/* + * Return true if the value of this Decimal is less than `y`, otherwise return false. + * + */ +P.lessThan = P.lt = function (y) { + return this.cmp(y) < 0; +}; + + +/* + * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. + * + */ +P.lessThanOrEqualTo = P.lte = function (y) { + return this.cmp(y) < 1; +}; + + +/* + * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * If no base is specified, return log[10](arg). + * + * log[base](arg) = ln(arg) / ln(base) + * + * The result will always be correctly rounded if the base of the log is 10, and 'almost always' + * otherwise: + * + * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen + * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error + * between the result and the correctly rounded result will be one ulp (unit in the last place). + * + * log[-b](a) = NaN + * log[0](a) = NaN + * log[1](a) = NaN + * log[NaN](a) = NaN + * log[Infinity](a) = NaN + * log[b](0) = -Infinity + * log[b](-0) = -Infinity + * log[b](-a) = NaN + * log[b](1) = 0 + * log[b](Infinity) = Infinity + * log[b](NaN) = NaN + * + * [base] {number|string|Decimal} The base of the logarithm. + * + */ +P.logarithm = P.log = function (base) { + var isBase10, d, denominator, k, inf, num, sd, r, + arg = this, + Ctor = arg.constructor, + pr = Ctor.precision, + rm = Ctor.rounding, + guard = 5; + + // Default base is 10. + if (base == null) { + base = new Ctor(10); + isBase10 = true; + } else { + base = new Ctor(base); + d = base.d; + + // Return NaN if base is negative, or non-finite, or is 0 or 1. + if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); + + isBase10 = base.eq(10); + } + + d = arg.d; + + // Is arg negative, non-finite, 0 or 1? + if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { + return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); + } + + // The result will have a non-terminating decimal expansion if base is 10 and arg is not an + // integer power of 10. + if (isBase10) { + if (d.length > 1) { + inf = true; + } else { + for (k = d[0]; k % 10 === 0;) k /= 10; + inf = k !== 1; + } + } + + external = false; + sd = pr + guard; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); + + // The result will have 5 rounding digits. + r = divide(num, denominator, sd, 1); + + // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, + // calculate 10 further digits. + // + // If the result is known to have an infinite decimal expansion, repeat this until it is clear + // that the result is above or below the boundary. Otherwise, if after calculating the 10 + // further digits, the last 14 are nines, round up and assume the result is exact. + // Also assume the result is exact if the last 14 are zero. + // + // Example of a result that will be incorrectly rounded: + // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... + // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it + // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so + // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal + // place is still 2.6. + if (checkRoundingDigits(r.d, k = pr, rm)) { + + do { + sd += 10; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); + r = divide(num, denominator, sd, 1); + + if (!inf) { + + // Check for 14 nines from the 2nd rounding digit, as the first may be 4. + if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } + + break; + } + } while (checkRoundingDigits(r.d, k += 10, rm)); + } + + external = true; + + return finalise(r, pr, rm); +}; + + +/* + * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * +P.max = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'lt'); +}; + */ + + +/* + * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * +P.min = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'gt'); +}; + */ + + +/* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ +P.minus = P.sub = function (y) { + var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // If either is not finite... + if (!x.d || !y.d) { + + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); + + // Return y negated if x is finite and y is ±Infinity. + else if (x.d) y.s = -y.s; + + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with different signs. + // Return NaN if both are ±Infinity with the same sign. + else y = new Ctor(y.d || x.s !== y.s ? x : NaN); + + return y; + } + + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.plus(y); + } + + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; + + // If either is zero... + if (!xd[0] || !yd[0]) { + + // Return y negated if x is zero and y is non-zero. + if (yd[0]) y.s = -y.s; + + // Return x if y is zero and x is non-zero. + else if (xd[0]) y = new Ctor(x); + + // Return zero if both are zero. + // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. + else return new Ctor(rm === 3 ? -0 : 0); + + return external ? finalise(y, pr, rm) : y; + } + + // x and y are finite, non-zero numbers with the same sign. + + // Calculate base 1e7 exponents. + e = mathfloor(y.e / LOG_BASE); + xe = mathfloor(x.e / LOG_BASE); + + xd = xd.slice(); + k = xe - e; + + // If base 1e7 exponents differ... + if (k) { + xLTy = k < 0; + + if (xLTy) { + d = xd; + k = -k; + len = yd.length; + } else { + d = yd; + e = xe; + len = xd.length; + } + + // Numbers with massively different exponents would result in a very high number of + // zeros needing to be prepended, but this can be avoided while still ensuring correct + // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. + i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; + + if (k > i) { + k = i; + d.length = 1; + } + + // Prepend zeros to equalise exponents. + d.reverse(); + for (i = k; i--;) d.push(0); + d.reverse(); + + // Base 1e7 exponents equal. + } else { + + // Check digits to determine which is the bigger number. + + i = xd.length; + len = yd.length; + xLTy = i < len; + if (xLTy) len = i; + + for (i = 0; i < len; i++) { + if (xd[i] != yd[i]) { + xLTy = xd[i] < yd[i]; + break; + } + } + + k = 0; + } + + if (xLTy) { + d = xd; + xd = yd; + yd = d; + y.s = -y.s; + } + + len = xd.length; + + // Append zeros to `xd` if shorter. + // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. + for (i = yd.length - len; i > 0; --i) xd[len++] = 0; + + // Subtract yd from xd. + for (i = yd.length; i > k;) { + + if (xd[--i] < yd[i]) { + for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; + --xd[j]; + xd[i] += BASE; + } + + xd[i] -= yd[i]; + } + + // Remove trailing zeros. + for (; xd[--len] === 0;) xd.pop(); + + // Remove leading zeros and adjust exponent accordingly. + for (; xd[0] === 0; xd.shift()) --e; + + // Zero? + if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); + + y.d = xd; + y.e = getBase10Exponent(xd, e); + + return external ? finalise(y, pr, rm) : y; +}; + + +/* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * The result depends on the modulo mode. + * + */ +P.modulo = P.mod = function (y) { + var q, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. + if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); + + // Return x if y is ±Infinity or x is ±0. + if (!y.d || x.d && !x.d[0]) { + return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); + } + + // Prevent rounding of intermediate calculations. + external = false; + + if (Ctor.modulo == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // result = x - q * y where 0 <= result < abs(y) + q = divide(x, y.abs(), 0, 3, 1); + q.s *= y.s; + } else { + q = divide(x, y, 0, Ctor.modulo, 1); + } + + q = q.times(y); + + external = true; + + return x.minus(q); +}; + + +/* + * Return a new Decimal whose value is the natural exponential of the value of this Decimal, + * i.e. the base e raised to the power the value of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ +P.naturalExponential = P.exp = function () { + return naturalExponential(this); +}; + + +/* + * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + */ +P.naturalLogarithm = P.ln = function () { + return naturalLogarithm(this); +}; + + +/* + * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by + * -1. + * + */ +P.negated = P.neg = function () { + var x = new this.constructor(this); + x.s = -x.s; + return finalise(x); +}; + + +/* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ +P.plus = P.add = function (y) { + var carry, d, e, i, k, len, pr, rm, xd, yd, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // If either is not finite... + if (!x.d || !y.d) { + + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); + + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with the same sign. + // Return NaN if both are ±Infinity with different signs. + // Return y if x is finite and y is ±Infinity. + else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); + + return y; + } + + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.minus(y); + } + + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; + + // If either is zero... + if (!xd[0] || !yd[0]) { + + // Return x if y is zero. + // Return y if y is non-zero. + if (!yd[0]) y = new Ctor(x); + + return external ? finalise(y, pr, rm) : y; + } + + // x and y are finite, non-zero numbers with the same sign. + + // Calculate base 1e7 exponents. + k = mathfloor(x.e / LOG_BASE); + e = mathfloor(y.e / LOG_BASE); + + xd = xd.slice(); + i = k - e; + + // If base 1e7 exponents differ... + if (i) { + + if (i < 0) { + d = xd; + i = -i; + len = yd.length; + } else { + d = yd; + e = k; + len = xd.length; + } + + // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. + k = Math.ceil(pr / LOG_BASE); + len = k > len ? k + 1 : len + 1; + + if (i > len) { + i = len; + d.length = 1; + } + + // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. + d.reverse(); + for (; i--;) d.push(0); + d.reverse(); + } + + len = xd.length; + i = yd.length; + + // If yd is longer than xd, swap xd and yd so xd points to the longer array. + if (len - i < 0) { + i = len; + d = yd; + yd = xd; + xd = d; + } + + // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. + for (carry = 0; i;) { + carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; + xd[i] %= BASE; + } + + if (carry) { + xd.unshift(carry); + ++e; + } + + // Remove trailing zeros. + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + for (len = xd.length; xd[--len] == 0;) xd.pop(); + + y.d = xd; + y.e = getBase10Exponent(xd, e); + + return external ? finalise(y, pr, rm) : y; +}; + + +/* + * Return the number of significant digits of the value of this Decimal. + * + * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + * + */ +P.precision = P.sd = function (z) { + var k, + x = this; + + if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); + + if (x.d) { + k = getPrecision(x.d); + if (z && x.e + 1 > k) k = x.e + 1; + } else { + k = NaN; + } + + return k; +}; + + +/* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using + * rounding mode `rounding`. + * + */ +P.round = function () { + var x = this, + Ctor = x.constructor; + + return finalise(new Ctor(x), x.e + 1, Ctor.rounding); +}; + + +/* + * Return a new Decimal whose value is the sine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * sin(x) = x - x^3/3! + x^5/5! - ... + * + * sin(0) = 0 + * sin(-0) = -0 + * sin(Infinity) = NaN + * sin(-Infinity) = NaN + * sin(NaN) = NaN + * + */ +P.sine = P.sin = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; + + x = sine(Ctor, toLessThanHalfPi(Ctor, x)); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); +}; + + +/* + * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + */ +P.squareRoot = P.sqrt = function () { + var m, n, sd, r, rep, t, + x = this, + d = x.d, + e = x.e, + s = x.s, + Ctor = x.constructor; + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !d || !d[0]) { + return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); + } + + external = false; + + // Initial estimate. + s = Math.sqrt(+x); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = digitsToString(d); + + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(n); + e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + } else { + r = new Ctor(s.toString()); + } + + sd = (e = Ctor.precision) + 3; + + // Newton-Raphson iteration. + for (;;) { + t = r; + r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); + + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or + // 4999, i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + sd += 4; + rep = 1; + } else { + + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + + external = true; + + return finalise(r, e, Ctor.rounding, m); +}; + + +/* + * Return a new Decimal whose value is the tangent of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * tan(0) = 0 + * tan(-0) = -0 + * tan(Infinity) = NaN + * tan(-Infinity) = NaN + * tan(NaN) = NaN + * + */ +P.tangent = P.tan = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 10; + Ctor.rounding = 1; + + x = x.sin(); + x.s = 1; + x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); +}; + + +/* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + */ +P.times = P.mul = function (y) { + var carry, e, i, k, r, rL, t, xdL, ydL, + x = this, + Ctor = x.constructor, + xd = x.d, + yd = (y = new Ctor(y)).d; + + y.s *= x.s; + + // If either is NaN, ±Infinity or ±0... + if (!xd || !xd[0] || !yd || !yd[0]) { + + return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd + + // Return NaN if either is NaN. + // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. + ? NaN + + // Return ±Infinity if either is ±Infinity. + // Return ±0 if either is ±0. + : !xd || !yd ? y.s / 0 : y.s * 0); + } + + e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); + xdL = xd.length; + ydL = yd.length; + + // Ensure xd points to the longer array. + if (xdL < ydL) { + r = xd; + xd = yd; + yd = r; + rL = xdL; + xdL = ydL; + ydL = rL; + } + + // Initialise the result array with zeros. + r = []; + rL = xdL + ydL; + for (i = rL; i--;) r.push(0); + + // Multiply! + for (i = ydL; --i >= 0;) { + carry = 0; + for (k = xdL + i; k > i;) { + t = r[k] + yd[i] * xd[k - i - 1] + carry; + r[k--] = t % BASE | 0; + carry = t / BASE | 0; + } + + r[k] = (r[k] + carry) % BASE | 0; + } + + // Remove trailing zeros. + for (; !r[--rL];) r.pop(); + + if (carry) ++e; + else r.shift(); + + y.d = r; + y.e = getBase10Exponent(r, e); + + return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; +}; + + +/* + * Return a string representing the value of this Decimal in base 2, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ +P.toBinary = function (sd, rm) { + return toStringBinary(this, 2, sd, rm); +}; + + +/* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` + * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. + * + * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ +P.toDecimalPlaces = P.toDP = function (dp, rm) { + var x = this, + Ctor = x.constructor; + + x = new Ctor(x); + if (dp === void 0) return x; + + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + return finalise(x, dp + x.e + 1, rm); +}; + + +/* + * Return a string representing the value of this Decimal in exponential notation rounded to + * `dp` fixed decimal places using rounding mode `rounding`. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ +P.toExponential = function (dp, rm) { + var str, + x = this, + Ctor = x.constructor; + + if (dp === void 0) { + str = finiteToString(x, true); + } else { + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = finalise(new Ctor(x), dp + 1, rm); + str = finiteToString(x, true, dp + 1); + } + + return x.isNeg() && !x.isZero() ? '-' + str : str; +}; + + +/* + * Return a string representing the value of this Decimal in normal (fixed-point) notation to + * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is + * omitted. + * + * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. + * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. + * (-0).toFixed(3) is '0.000'. + * (-0.5).toFixed(0) is '-0'. + * + */ +P.toFixed = function (dp, rm) { + var str, y, + x = this, + Ctor = x.constructor; + + if (dp === void 0) { + str = finiteToString(x); + } else { + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + y = finalise(new Ctor(x), dp + x.e + 1, rm); + str = finiteToString(y, false, dp + y.e + 1); + } + + // To determine whether to add the minus sign look at the value before it was rounded, + // i.e. look at `x` rather than `y`. + return x.isNeg() && !x.isZero() ? '-' + str : str; +}; + + +/* + * Return an array representing the value of this Decimal as a simple fraction with an integer + * numerator and an integer denominator. + * + * The denominator will be a positive non-zero value less than or equal to the specified maximum + * denominator. If a maximum denominator is not specified, the denominator will be the lowest + * value necessary to represent the number exactly. + * + * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity. + * + */ +P.toFraction = function (maxD) { + var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, + x = this, + xd = x.d, + Ctor = x.constructor; + + if (!xd) return new Ctor(x); + + n1 = d0 = new Ctor(1); + d1 = n0 = new Ctor(0); + + d = new Ctor(d1); + e = d.e = getPrecision(xd) - x.e - 1; + k = e % LOG_BASE; + d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k); + + if (maxD == null) { + + // d is 10**e, the minimum max-denominator needed. + maxD = e > 0 ? d : n1; + } else { + n = new Ctor(maxD); + if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n); + maxD = n.gt(d) ? (e > 0 ? d : n1) : n; + } + + external = false; + n = new Ctor(digitsToString(xd)); + pr = Ctor.precision; + Ctor.precision = e = xd.length * LOG_BASE * 2; + + for (;;) { + q = divide(n, d, 0, 1, 1); + d2 = d0.plus(q.times(d1)); + if (d2.cmp(maxD) == 1) break; + d0 = d1; + d1 = d2; + d2 = n1; + n1 = n0.plus(q.times(d2)); + n0 = d2; + d2 = d; + d = n.minus(q.times(d2)); + n = d2; + } + + d2 = divide(maxD.minus(d0), d1, 0, 1, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + + // Determine which fraction is closer to x, n0/d0 or n1/d1? + r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 + ? [n1, d1] : [n0, d0]; + + Ctor.precision = pr; + external = true; + + return r; +}; + + +/* + * Return a string representing the value of this Decimal in base 16, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ +P.toHexadecimal = P.toHex = function (sd, rm) { + return toStringBinary(this, 16, sd, rm); +}; + + +/* + * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding + * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal. + * + * The return value will always have the same sign as this Decimal, unless either this Decimal + * or `y` is NaN, in which case the return value will be also be NaN. + * + * The return value is not affected by the value of `precision`. + * + * y {number|string|Decimal} The magnitude to round to a multiple of. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toNearest() rounding mode not an integer: {rm}' + * 'toNearest() rounding mode out of range: {rm}' + * + */ +P.toNearest = function (y, rm) { + var x = this, + Ctor = x.constructor; + + x = new Ctor(x); + + if (y == null) { + + // If x is not finite, return x. + if (!x.d) return x; + + y = new Ctor(1); + rm = Ctor.rounding; + } else { + y = new Ctor(y); + if (rm === void 0) { + rm = Ctor.rounding; + } else { + checkInt32(rm, 0, 8); + } + + // If x is not finite, return x if y is not NaN, else NaN. + if (!x.d) return y.s ? x : y; + + // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN. + if (!y.d) { + if (y.s) y.s = x.s; + return y; + } + } + + // If y is not zero, calculate the nearest multiple of y to x. + if (y.d[0]) { + external = false; + x = divide(x, y, 0, rm, 1).times(y); + external = true; + finalise(x); + + // If y is zero, return zero with the sign of x. + } else { + y.s = x.s; + x = y; + } + + return x; +}; + + +/* + * Return the value of this Decimal converted to a number primitive. + * Zero keeps its sign. + * + */ +P.toNumber = function () { + return +this; +}; + + +/* + * Return a string representing the value of this Decimal in base 8, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ +P.toOctal = function (sd, rm) { + return toStringBinary(this, 8, sd, rm); +}; + + +/* + * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded + * to `precision` significant digits using rounding mode `rounding`. + * + * ECMAScript compliant. + * + * pow(x, NaN) = NaN + * pow(x, ±0) = 1 + + * pow(NaN, non-zero) = NaN + * pow(abs(x) > 1, +Infinity) = +Infinity + * pow(abs(x) > 1, -Infinity) = +0 + * pow(abs(x) == 1, ±Infinity) = NaN + * pow(abs(x) < 1, +Infinity) = +0 + * pow(abs(x) < 1, -Infinity) = +Infinity + * pow(+Infinity, y > 0) = +Infinity + * pow(+Infinity, y < 0) = +0 + * pow(-Infinity, odd integer > 0) = -Infinity + * pow(-Infinity, even integer > 0) = +Infinity + * pow(-Infinity, odd integer < 0) = -0 + * pow(-Infinity, even integer < 0) = +0 + * pow(+0, y > 0) = +0 + * pow(+0, y < 0) = +Infinity + * pow(-0, odd integer > 0) = -0 + * pow(-0, even integer > 0) = +0 + * pow(-0, odd integer < 0) = -Infinity + * pow(-0, even integer < 0) = +Infinity + * pow(finite x < 0, finite non-integer) = NaN + * + * For non-integer or very large exponents pow(x, y) is calculated using + * + * x^y = exp(y*ln(x)) + * + * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the + * probability of an incorrectly rounded result + * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14 + * i.e. 1 in 250,000,000,000,000 + * + * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place). + * + * y {number|string|Decimal} The power to which to raise this Decimal. + * + */ +P.toPower = P.pow = function (y) { + var e, k, pr, r, rm, s, + x = this, + Ctor = x.constructor, + yn = +(y = new Ctor(y)); + + // Either ±Infinity, NaN or ±0? + if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); + + x = new Ctor(x); + + if (x.eq(1)) return x; + + pr = Ctor.precision; + rm = Ctor.rounding; + + if (y.eq(1)) return finalise(x, pr, rm); + + // y exponent + e = mathfloor(y.e / LOG_BASE); + + // If y is a small integer use the 'exponentiation by squaring' algorithm. + if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { + r = intPow(Ctor, x, k, pr); + return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); + } + + s = x.s; + + // if x is negative + if (s < 0) { + + // if y is not an integer + if (e < y.d.length - 1) return new Ctor(NaN); + + // Result is positive if x is negative and the last digit of integer y is even. + if ((y.d[e] & 1) == 0) s = 1; + + // if x.eq(-1) + if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) { + x.s = s; + return x; + } + } + + // Estimate result exponent. + // x^y = 10^e, where e = y * log10(x) + // log10(x) = log10(x_significand) + x_exponent + // log10(x_significand) = ln(x_significand) / ln(10) + k = mathpow(+x, yn); + e = k == 0 || !isFinite(k) + ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) + : new Ctor(k + '').e; + + // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. + + // Overflow/underflow? + if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0); + + external = false; + Ctor.rounding = x.s = 1; + + // Estimate the extra guard digits needed to ensure five correct rounding digits from + // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): + // new Decimal(2.32456).pow('2087987436534566.46411') + // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 + k = Math.min(12, (e + '').length); + + // r = x^y = exp(y*ln(x)) + r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); + + // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40) + if (r.d) { + + // Truncate to the required precision plus five rounding digits. + r = finalise(r, pr + 5, 1); + + // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate + // the result. + if (checkRoundingDigits(r.d, pr, rm)) { + e = pr + 10; + + // Truncate to the increased precision plus five rounding digits. + r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); + + // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). + if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } + } + } + + r.s = s; + external = true; + Ctor.rounding = rm; + + return finalise(r, pr, rm); +}; + + +/* + * Return a string representing the value of this Decimal rounded to `sd` significant digits + * using rounding mode `rounding`. + * + * Return exponential notation if `sd` is less than the number of digits necessary to represent + * the integer part of the value in normal notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ +P.toPrecision = function (sd, rm) { + var str, + x = this, + Ctor = x.constructor; + + if (sd === void 0) { + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = finalise(new Ctor(x), sd, rm); + str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd); + } + + return x.isNeg() && !x.isZero() ? '-' + str : str; +}; + + +/* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` + * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if + * omitted. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toSD() digits out of range: {sd}' + * 'toSD() digits not an integer: {sd}' + * 'toSD() rounding mode not an integer: {rm}' + * 'toSD() rounding mode out of range: {rm}' + * + */ +P.toSignificantDigits = P.toSD = function (sd, rm) { + var x = this, + Ctor = x.constructor; + + if (sd === void 0) { + sd = Ctor.precision; + rm = Ctor.rounding; + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } + + return finalise(new Ctor(x), sd, rm); +}; + + +/* + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ +P.toString = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + + return x.isNeg() && !x.isZero() ? '-' + str : str; +}; + + +/* + * Return a new Decimal whose value is the value of this Decimal truncated to a whole number. + * + */ +P.truncated = P.trunc = function () { + return finalise(new this.constructor(this), this.e + 1, 1); +}; + + +/* + * Return a string representing the value of this Decimal. + * Unlike `toString`, negative zero will include the minus sign. + * + */ +P.valueOf = P.toJSON = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + + return x.isNeg() ? '-' + str : str; +}; + + +// Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. + + +/* + * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower, + * finiteToString, naturalExponential, naturalLogarithm + * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest, + * P.toPrecision, P.toSignificantDigits, toStringBinary, random + * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm + * convertBase toStringBinary, parseOther + * cos P.cos + * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy, + * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction, + * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm, + * taylorSeries, atan2, parseOther + * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh, + * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus, + * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot, + * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed, + * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits, + * P.truncated, divide, getLn10, getPi, naturalExponential, + * naturalLogarithm, ceil, floor, round, trunc + * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf, + * toStringBinary + * getBase10Exponent P.minus, P.plus, P.times, parseOther + * getLn10 P.logarithm, naturalLogarithm + * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2 + * getPrecision P.precision, P.toFraction + * getZeroString digitsToString, finiteToString + * intPow P.toPower, parseOther + * isOdd toLessThanHalfPi + * maxOrMin max, min + * naturalExponential P.naturalExponential, P.toPower + * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm, + * P.toPower, naturalExponential + * nonFiniteToString finiteToString, toStringBinary + * parseDecimal Decimal + * parseOther Decimal + * sin P.sin + * taylorSeries P.cosh, P.sinh, cos, sin + * toLessThanHalfPi P.cos, P.sin + * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal + * truncate intPow + * + * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi, + * naturalLogarithm, config, parseOther, random, Decimal + */ + + +function digitsToString(d) { + var i, k, ws, + indexOfLastWord = d.length - 1, + str = '', + w = d[0]; + + if (indexOfLastWord > 0) { + str += w; + for (i = 1; i < indexOfLastWord; i++) { + ws = d[i] + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + str += ws; + } + + w = d[i]; + ws = w + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + } else if (w === 0) { + return '0'; + } + + // Remove trailing zeros of last w. + for (; w % 10 === 0;) w /= 10; + + return str + w; +} + + +function checkInt32(i, min, max) { + if (i !== ~~i || i < min || i > max) { + throw Error(invalidArgument + i); + } +} + + +/* + * Check 5 rounding digits if `repeating` is null, 4 otherwise. + * `repeating == null` if caller is `log` or `pow`, + * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`. + */ +function checkRoundingDigits(d, i, rm, repeating) { + var di, k, r, rd; + + // Get the length of the first word of the array d. + for (k = d[0]; k >= 10; k /= 10) --i; + + // Is the rounding digit in the first word of d? + if (--i < 0) { + i += LOG_BASE; + di = 0; + } else { + di = Math.ceil((i + 1) / LOG_BASE); + i %= LOG_BASE; + } + + // i is the index (0 - 6) of the rounding digit. + // E.g. if within the word 3487563 the first rounding digit is 5, + // then i = 4, k = 1000, rd = 3487563 % 1000 = 563 + k = mathpow(10, LOG_BASE - i); + rd = d[di] % k | 0; + + if (repeating == null) { + if (i < 3) { + if (i == 0) rd = rd / 100 | 0; + else if (i == 1) rd = rd / 10 | 0; + r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0; + } else { + r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && + (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || + (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0; + } + } else { + if (i < 4) { + if (i == 0) rd = rd / 1000 | 0; + else if (i == 1) rd = rd / 100 | 0; + else if (i == 2) rd = rd / 10 | 0; + r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999; + } else { + r = ((repeating || rm < 4) && rd + 1 == k || + (!repeating && rm > 3) && rd + 1 == k / 2) && + (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1; + } + } + + return r; +} + + +// Convert string of `baseIn` to an array of numbers of `baseOut`. +// Eg. convertBase('255', 10, 16) returns [15, 15]. +// Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. +function convertBase(str, baseIn, baseOut) { + var j, + arr = [0], + arrL, + i = 0, + strL = str.length; + + for (; i < strL;) { + for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn; + arr[0] += NUMERALS.indexOf(str.charAt(i++)); + for (j = 0; j < arr.length; j++) { + if (arr[j] > baseOut - 1) { + if (arr[j + 1] === void 0) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); +} + + +/* + * cos(x) = 1 - x^2/2! + x^4/4! - ... + * |x| < pi/2 + * + */ +function cosine(Ctor, x) { + var k, len, y; + + if (x.isZero()) return x; + + // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1 + // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1 + + // Estimate the optimum number of times to use the argument reduction. + len = x.d.length; + if (len < 32) { + k = Math.ceil(len / 3); + y = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + y = '2.3283064365386962890625e-10'; + } + + Ctor.precision += k; + + x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1)); + + // Reverse argument reduction + for (var i = k; i--;) { + var cos2x = x.times(x); + x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1); + } + + Ctor.precision -= k; + + return x; +} + + +/* + * Perform division in the specified base. + */ +var divide = (function () { + + // Assumes non-zero x and k, and hence non-zero result. + function multiplyInteger(x, k, base) { + var temp, + carry = 0, + i = x.length; + + for (x = x.slice(); i--;) { + temp = x[i] * k + carry; + x[i] = temp % base | 0; + carry = temp / base | 0; + } + + if (carry) x.unshift(carry); + + return x; + } + + function compare(a, b, aL, bL) { + var i, r; + + if (aL != bL) { + r = aL > bL ? 1 : -1; + } else { + for (i = r = 0; i < aL; i++) { + if (a[i] != b[i]) { + r = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return r; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1;) a.shift(); + } + + return function (x, y, pr, rm, dp, base) { + var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, + yL, yz, + Ctor = x.constructor, + sign = x.s == y.s ? 1 : -1, + xd = x.d, + yd = y.d; + + // Either NaN, Infinity or 0? + if (!xd || !xd[0] || !yd || !yd[0]) { + + return new Ctor(// Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN : + + // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0. + xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0); + } + + if (base) { + logBase = 1; + e = x.e - y.e; + } else { + base = BASE; + logBase = LOG_BASE; + e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase); + } + + yL = yd.length; + xL = xd.length; + q = new Ctor(sign); + qd = q.d = []; + + // Result exponent may be one less than e. + // The digit array of a Decimal from toStringBinary may have trailing zeros. + for (i = 0; yd[i] == (xd[i] || 0); i++); + + if (yd[i] > (xd[i] || 0)) e--; + + if (pr == null) { + sd = pr = Ctor.precision; + rm = Ctor.rounding; + } else if (dp) { + sd = pr + (x.e - y.e) + 1; + } else { + sd = pr; + } + + if (sd < 0) { + qd.push(1); + more = true; + } else { + + // Convert precision in number of base 10 digits to base 1e7 digits. + sd = sd / logBase + 2 | 0; + i = 0; + + // divisor < 1e7 + if (yL == 1) { + k = 0; + yd = yd[0]; + sd++; + + // k is the carry. + for (; (i < xL || k) && sd--; i++) { + t = k * base + (xd[i] || 0); + qd[i] = t / yd | 0; + k = t % yd | 0; + } + + more = k || i < xL; + + // divisor >= 1e7 + } else { + + // Normalise xd and yd so highest order digit of yd is >= base/2 + k = base / (yd[0] + 1) | 0; + + if (k > 1) { + yd = multiplyInteger(yd, k, base); + xd = multiplyInteger(xd, k, base); + yL = yd.length; + xL = xd.length; + } + + xi = yL; + rem = xd.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL;) rem[remL++] = 0; + + yz = yd.slice(); + yz.unshift(0); + yd0 = yd[0]; + + if (yd[1] >= base / 2) ++yd0; + + do { + k = 0; + + // Compare divisor and remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, k. + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // k will be how many times the divisor goes into the current remainder. + k = rem0 / yd0 | 0; + + // Algorithm: + // 1. product = divisor * trial digit (k) + // 2. if product > remainder: product -= divisor, k-- + // 3. remainder -= product + // 4. if product was < remainder at 2: + // 5. compare new remainder and divisor + // 6. If remainder > divisor: remainder -= divisor, k++ + + if (k > 1) { + if (k >= base) k = base - 1; + + // product = divisor * trial digit. + prod = multiplyInteger(yd, k, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + cmp = compare(prod, rem, prodL, remL); + + // product > remainder. + if (cmp == 1) { + k--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yd, prodL, base); + } + } else { + + // cmp is -1. + // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1 + // to avoid it. If k is 1 there is a need to compare yd and rem again below. + if (k == 0) cmp = k = 1; + prod = yd.slice(); + } + + prodL = prod.length; + if (prodL < remL) prod.unshift(0); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + + // If product was < previous remainder. + if (cmp == -1) { + remL = rem.length; + + // Compare divisor and new remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < new remainder, subtract divisor from remainder. + if (cmp < 1) { + k++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yd, remL, base); + } + } + + remL = rem.length; + } else if (cmp === 0) { + k++; + rem = [0]; + } // if cmp === 1, k will be 0 + + // Add the next digit, k, to the result array. + qd[i++] = k; + + // Update the remainder. + if (cmp && rem[0]) { + rem[remL++] = xd[xi] || 0; + } else { + rem = [xd[xi]]; + remL = 1; + } + + } while ((xi++ < xL || rem[0] !== void 0) && sd--); + + more = rem[0] !== void 0; + } + + // Leading zero? + if (!qd[0]) qd.shift(); + } + + // logBase is 1 when divide is being used for base conversion. + if (logBase == 1) { + q.e = e; + inexact = more; + } else { + + // To calculate q.e, first get the number of digits of qd[0]. + for (i = 1, k = qd[0]; k >= 10; k /= 10) i++; + q.e = i + e * logBase - 1; + + finalise(q, dp ? pr + q.e + 1 : pr, rm, more); + } + + return q; + }; +})(); + + +/* + * Round `x` to `sd` significant digits using rounding mode `rm`. + * Check for over/under-flow. + */ + function finalise(x, sd, rm, isTruncated) { + var digits, i, j, k, rd, roundUp, w, xd, xdi, + Ctor = x.constructor; + + // Don't round if sd is null or undefined. + out: if (sd != null) { + xd = x.d; + + // Infinity/NaN. + if (!xd) return x; + + // rd: the rounding digit, i.e. the digit after the digit that may be rounded up. + // w: the word of xd containing rd, a base 1e7 number. + // xdi: the index of w within xd. + // digits: the number of digits of w. + // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if + // they had leading zeros) + // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero). + + // Get the length of the first word of the digits array xd. + for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++; + i = sd - digits; + + // Is the rounding digit in the first word of xd? + if (i < 0) { + i += LOG_BASE; + j = sd; + w = xd[xdi = 0]; + + // Get the rounding digit at index j of w. + rd = w / mathpow(10, digits - j - 1) % 10 | 0; + } else { + xdi = Math.ceil((i + 1) / LOG_BASE); + k = xd.length; + if (xdi >= k) { + if (isTruncated) { + + // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`. + for (; k++ <= xdi;) xd.push(0); + w = rd = 0; + digits = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + w = k = xd[xdi]; + + // Get the number of digits of w. + for (digits = 1; k >= 10; k /= 10) digits++; + + // Get the index of rd within w. + i %= LOG_BASE; + + // Get the index of rd within w, adjusted for leading zeros. + // The number of leading zeros of w is given by LOG_BASE - digits. + j = i - LOG_BASE + digits; + + // Get the rounding digit at index j of w. + rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0; + } + } + + // Are there any non-zero digits after the rounding digit? + isTruncated = isTruncated || sd < 0 || + xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1)); + + // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right + // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression + // will give 714. + + roundUp = rm < 4 + ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xd[0]) { + xd.length = 0; + if (roundUp) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE); + x.e = -sd || 0; + } else { + + // Zero. + xd[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xd.length = xdi; + k = 1; + xdi--; + } else { + xd.length = xdi + 1; + k = mathpow(10, LOG_BASE - i); + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of w. + xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0; + } + + if (roundUp) { + for (;;) { + + // Is the digit to be rounded up in the first word of xd? + if (xdi == 0) { + + // i will be the length of xd[0] before k is added. + for (i = 1, j = xd[0]; j >= 10; j /= 10) i++; + j = xd[0] += k; + for (k = 1; j >= 10; j /= 10) k++; + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xd[0] == BASE) xd[0] = 1; + } + + break; + } else { + xd[xdi] += k; + if (xd[xdi] != BASE) break; + xd[xdi--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xd.length; xd[--i] === 0;) xd.pop(); + } + + if (external) { + + // Overflow? + if (x.e > Ctor.maxE) { + + // Infinity. + x.d = null; + x.e = NaN; + + // Underflow? + } else if (x.e < Ctor.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + // Ctor.underflow = true; + } // else Ctor.underflow = false; + } + + return x; +} + + +function finiteToString(x, isExp, sd) { + if (!x.isFinite()) return nonFiniteToString(x); + var k, + e = x.e, + str = digitsToString(x.d), + len = str.length; + + if (isExp) { + if (sd && (k = sd - len) > 0) { + str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k); + } else if (len > 1) { + str = str.charAt(0) + '.' + str.slice(1); + } + + str = str + (x.e < 0 ? 'e' : 'e+') + x.e; + } else if (e < 0) { + str = '0.' + getZeroString(-e - 1) + str; + if (sd && (k = sd - len) > 0) str += getZeroString(k); + } else if (e >= len) { + str += getZeroString(e + 1 - len); + if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k); + } else { + if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k); + if (sd && (k = sd - len) > 0) { + if (e + 1 === len) str += '.'; + str += getZeroString(k); + } + } + + return str; +} + + +// Calculate the base 10 exponent from the base 1e7 exponent. +function getBase10Exponent(digits, e) { + var w = digits[0]; + + // Add the number of digits of the first word of the digits array. + for ( e *= LOG_BASE; w >= 10; w /= 10) e++; + return e; +} + + +function getLn10(Ctor, sd, pr) { + if (sd > LN10_PRECISION) { + + // Reset global state in case the exception is caught. + external = true; + if (pr) Ctor.precision = pr; + throw Error(precisionLimitExceeded); + } + return finalise(new Ctor(LN10), sd, 1, true); +} + + +function getPi(Ctor, sd, rm) { + if (sd > PI_PRECISION) throw Error(precisionLimitExceeded); + return finalise(new Ctor(PI), sd, rm, true); +} + + +function getPrecision(digits) { + var w = digits.length - 1, + len = w * LOG_BASE + 1; + + w = digits[w]; + + // If non-zero... + if (w) { + + // Subtract the number of trailing zeros of the last word. + for (; w % 10 == 0; w /= 10) len--; + + // Add the number of digits of the first word. + for (w = digits[0]; w >= 10; w /= 10) len++; + } + + return len; +} + + +function getZeroString(k) { + var zs = ''; + for (; k--;) zs += '0'; + return zs; +} + + +/* + * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an + * integer of type number. + * + * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`. + * + */ +function intPow(Ctor, x, n, pr) { + var isTruncated, + r = new Ctor(1), + + // Max n of 9007199254740991 takes 53 loop iterations. + // Maximum digits array length; leaves [28, 34] guard digits. + k = Math.ceil(pr / LOG_BASE + 4); + + external = false; + + for (;;) { + if (n % 2) { + r = r.times(x); + if (truncate(r.d, k)) isTruncated = true; + } + + n = mathfloor(n / 2); + if (n === 0) { + + // To ensure correct rounding when r.d is truncated, increment the last word if it is zero. + n = r.d.length - 1; + if (isTruncated && r.d[n] === 0) ++r.d[n]; + break; + } + + x = x.times(x); + truncate(x.d, k); + } + + external = true; + + return r; +} + + +function isOdd(n) { + return n.d[n.d.length - 1] & 1; +} + + +/* + * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'. + */ +function maxOrMin(Ctor, args, ltgt) { + var y, + x = new Ctor(args[0]), + i = 0; + + for (; ++i < args.length;) { + y = new Ctor(args[i]); + if (!y.s) { + x = y; + break; + } else if (x[ltgt](y)) { + x = y; + } + } + + return x; +} + + +/* + * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant + * digits. + * + * Taylor/Maclaurin series. + * + * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ... + * + * Argument reduction: + * Repeat x = x / 32, k += 5, until |x| < 0.1 + * exp(x) = exp(x / 2^k)^(2^k) + * + * Previously, the argument was initially reduced by + * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10) + * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was + * found to be slower than just dividing repeatedly by 32 as above. + * + * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000 + * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000 + * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324) + * + * exp(Infinity) = Infinity + * exp(-Infinity) = 0 + * exp(NaN) = NaN + * exp(±0) = 1 + * + * exp(x) is non-terminating for any finite, non-zero x. + * + * The result will always be correctly rounded. + * + */ +function naturalExponential(x, sd) { + var denominator, guard, j, pow, sum, t, wpr, + rep = 0, + i = 0, + k = 0, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; + + // 0/NaN/Infinity? + if (!x.d || !x.d[0] || x.e > 17) { + + return new Ctor(x.d + ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 + : x.s ? x.s < 0 ? 0 : x : 0 / 0); + } + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + t = new Ctor(0.03125); + + // while abs(x) >= 0.1 + while (x.e > -2) { + + // x = x / 2^5 + x = x.times(t); + k += 5; + } + + // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision + // necessary to ensure the first 4 rounding digits are correct. + guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0; + wpr += guard; + denominator = pow = sum = new Ctor(1); + Ctor.precision = wpr; + + for (;;) { + pow = finalise(pow.times(x), wpr, 1); + denominator = denominator.times(++i); + t = sum.plus(divide(pow, denominator, wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + j = k; + while (j--) sum = finalise(sum.times(sum), wpr, 1); + + // Check to see if the first 4 rounding digits are [49]999. + // If so, repeat the summation with a higher precision, otherwise + // e.g. with precision: 18, rounding: 1 + // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123) + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + + if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += 10; + denominator = pow = t = new Ctor(1); + i = 0; + rep++; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } + + sum = t; + } +} + + +/* + * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant + * digits. + * + * ln(-n) = NaN + * ln(0) = -Infinity + * ln(-0) = -Infinity + * ln(1) = 0 + * ln(Infinity) = Infinity + * ln(-Infinity) = NaN + * ln(NaN) = NaN + * + * ln(n) (n != 1) is non-terminating. + * + */ +function naturalLogarithm(y, sd) { + var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2, + n = 1, + guard = 10, + x = y, + xd = x.d, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; + + // Is x negative or Infinity, NaN, 0 or 1? + if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) { + return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x); + } + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + Ctor.precision = wpr += guard; + c = digitsToString(xd); + c0 = c.charAt(0); + + if (Math.abs(e = x.e) < 1.5e15) { + + // Argument reduction. + // The series converges faster the closer the argument is to 1, so using + // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b + // multiply the argument by itself until the leading digits of the significand are 7, 8, 9, + // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can + // later be divided by this number, then separate out the power of 10 using + // ln(a*10^b) = ln(a) + b*ln(10). + + // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14). + //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) { + // max n is 6 (gives 0.7 - 1.3) + while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) { + x = x.times(y); + c = digitsToString(x.d); + c0 = c.charAt(0); + n++; + } + + e = x.e; + + if (c0 > 1) { + x = new Ctor('0.' + c); + e++; + } else { + x = new Ctor(c0 + '.' + c.slice(1)); + } + } else { + + // The argument reduction method above may result in overflow if the argument y is a massive + // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this + // function using ln(x*10^e) = ln(x) + e*ln(10). + t = getLn10(Ctor, wpr + 2, pr).times(e + ''); + x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t); + Ctor.precision = pr; + + return sd == null ? finalise(x, pr, rm, external = true) : x; + } + + // x1 is x reduced to a value near 1. + x1 = x; + + // Taylor series. + // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...) + // where x = (y - 1)/(y + 1) (|x| < 1) + sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = 3; + + for (;;) { + numerator = finalise(numerator.times(x2), wpr, 1); + t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + sum = sum.times(2); + + // Reverse the argument reduction. Check that e is not 0 because, besides preventing an + // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0. + if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + '')); + sum = divide(sum, new Ctor(n), wpr, 1); + + // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has + // been repeated previously) and the first 4 rounding digits 9999? + // If so, restart the summation with a higher precision, otherwise + // e.g. with precision: 12, rounding: 1 + // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463. + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += guard; + t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = rep = 1; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } + + sum = t; + denominator += 2; + } +} + + +// ±Infinity, NaN. +function nonFiniteToString(x) { + // Unsigned. + return String(x.s * x.s / 0); +} + + +/* + * Parse the value of a new Decimal `x` from string `str`. + */ +function parseDecimal(x, str) { + var e, i, len; + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(len - 1) === 48; --len); + str = str.slice(i, len); + + if (str) { + len -= i; + x.e = e = e - i - 1; + x.d = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first word of the digits array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; + + if (i < len) { + if (i) x.d.push(+str.slice(0, i)); + for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE)); + str = str.slice(i); + i = LOG_BASE - str.length; + } else { + i -= len; + } + + for (; i--;) str += '0'; + x.d.push(+str); + + if (external) { + + // Overflow? + if (x.e > x.constructor.maxE) { + + // Infinity. + x.d = null; + x.e = NaN; + + // Underflow? + } else if (x.e < x.constructor.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + // x.constructor.underflow = true; + } // else x.constructor.underflow = false; + } + } else { + + // Zero. + x.e = 0; + x.d = [0]; + } + + return x; +} + + +/* + * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value. + */ +function parseOther(x, str) { + var base, Ctor, divisor, i, isFloat, len, p, xd, xe; + + if (str.indexOf('_') > -1) { + str = str.replace(/(\d)_(?=\d)/g, '$1'); + if (isDecimal.test(str)) return parseDecimal(x, str); + } else if (str === 'Infinity' || str === 'NaN') { + if (!+str) x.s = NaN; + x.e = NaN; + x.d = null; + return x; + } + + if (isHex.test(str)) { + base = 16; + str = str.toLowerCase(); + } else if (isBinary.test(str)) { + base = 2; + } else if (isOctal.test(str)) { + base = 8; + } else { + throw Error(invalidArgument + str); + } + + // Is there a binary exponent part? + i = str.search(/p/i); + + if (i > 0) { + p = +str.slice(i + 1); + str = str.substring(2, i); + } else { + str = str.slice(2); + } + + // Convert `str` as an integer then divide the result by `base` raised to a power such that the + // fraction part will be restored. + i = str.indexOf('.'); + isFloat = i >= 0; + Ctor = x.constructor; + + if (isFloat) { + str = str.replace('.', ''); + len = str.length; + i = len - i; + + // log[10](16) = 1.2041... , log[10](88) = 1.9444.... + divisor = intPow(Ctor, new Ctor(base), i, i * 2); + } + + xd = convertBase(str, base, BASE); + xe = xd.length - 1; + + // Remove trailing zeros. + for (i = xe; xd[i] === 0; --i) xd.pop(); + if (i < 0) return new Ctor(x.s * 0); + x.e = getBase10Exponent(xd, xe); + x.d = xd; + external = false; + + // At what precision to perform the division to ensure exact conversion? + // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount) + // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412 + // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits. + // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount + // Therefore using 4 * the number of digits of str will always be enough. + if (isFloat) x = divide(x, divisor, len * 4); + + // Multiply by the binary exponent part if present. + if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p)); + external = true; + + return x; +} + + +/* + * sin(x) = x - x^3/3! + x^5/5! - ... + * |x| < pi/2 + * + */ +function sine(Ctor, x) { + var k, + len = x.d.length; + + if (len < 3) { + return x.isZero() ? x : taylorSeries(Ctor, 2, x, x); + } + + // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x) + // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5) + // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20)) + + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; + + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x); + + // Reverse argument reduction + var sin2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sin2_x = x.times(x); + x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20)))); + } + + return x; +} + + +// Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`. +function taylorSeries(Ctor, n, x, y, isHyperbolic) { + var j, t, u, x2, + i = 1, + pr = Ctor.precision, + k = Math.ceil(pr / LOG_BASE); + + external = false; + x2 = x.times(x); + u = new Ctor(y); + + for (;;) { + t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1); + u = isHyperbolic ? y.plus(t) : y.minus(t); + y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1); + t = u.plus(y); + + if (t.d[k] !== void 0) { + for (j = k; t.d[j] === u.d[j] && j--;); + if (j == -1) break; + } + + j = u; + u = y; + y = t; + t = j; + i++; + } + + external = true; + t.d.length = k + 1; + + return t; +} + + +// Exponent e must be positive and non-zero. +function tinyPow(b, e) { + var n = b; + while (--e) n *= b; + return n; +} + + +// Return the absolute value of `x` reduced to less than or equal to half pi. +function toLessThanHalfPi(Ctor, x) { + var t, + isNeg = x.s < 0, + pi = getPi(Ctor, Ctor.precision, 1), + halfPi = pi.times(0.5); + + x = x.abs(); + + if (x.lte(halfPi)) { + quadrant = isNeg ? 4 : 1; + return x; + } + + t = x.divToInt(pi); + + if (t.isZero()) { + quadrant = isNeg ? 3 : 2; + } else { + x = x.minus(t.times(pi)); + + // 0 <= x < pi + if (x.lte(halfPi)) { + quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1); + return x; + } + + quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2); + } + + return x.minus(pi).abs(); +} + + +/* + * Return the value of Decimal `x` as a string in base `baseOut`. + * + * If the optional `sd` argument is present include a binary exponent suffix. + */ +function toStringBinary(x, baseOut, sd, rm) { + var base, e, i, k, len, roundUp, str, xd, y, + Ctor = x.constructor, + isExp = sd !== void 0; + + if (isExp) { + checkInt32(sd, 1, MAX_DIGITS); + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } else { + sd = Ctor.precision; + rm = Ctor.rounding; + } + + if (!x.isFinite()) { + str = nonFiniteToString(x); + } else { + str = finiteToString(x); + i = str.indexOf('.'); + + // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required: + // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10)) + // minBinaryExponent = floor(decimalExponent * log[2](10)) + // log[2](10) = 3.321928094887362347870319429489390175864 + + if (isExp) { + base = 2; + if (baseOut == 16) { + sd = sd * 4 - 3; + } else if (baseOut == 8) { + sd = sd * 3 - 2; + } + } else { + base = baseOut; + } + + // Convert the number as an integer then divide the result by its base raised to a power such + // that the fraction part will be restored. + + // Non-integer. + if (i >= 0) { + str = str.replace('.', ''); + y = new Ctor(1); + y.e = str.length - i; + y.d = convertBase(finiteToString(y), 10, base); + y.e = y.d.length; + } + + xd = convertBase(str, 10, base); + e = len = xd.length; + + // Remove trailing zeros. + for (; xd[--len] == 0;) xd.pop(); + + if (!xd[0]) { + str = isExp ? '0p+0' : '0'; + } else { + if (i < 0) { + e--; + } else { + x = new Ctor(x); + x.d = xd; + x.e = e; + x = divide(x, y, sd, rm, 0, base); + xd = x.d; + e = x.e; + roundUp = inexact; + } + + // The rounding digit, i.e. the digit after the digit that may be rounded up. + i = xd[sd]; + k = base / 2; + roundUp = roundUp || xd[sd + 1] !== void 0; + + roundUp = rm < 4 + ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2)) + : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || + rm === (x.s < 0 ? 8 : 7)); + + xd.length = sd; + + if (roundUp) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (; ++xd[--sd] > base - 1;) { + xd[sd] = 0; + if (!sd) { + ++e; + xd.unshift(1); + } + } + } + + // Determine trailing zeros. + for (len = xd.length; !xd[len - 1]; --len); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]); + + // Add binary exponent suffix? + if (isExp) { + if (len > 1) { + if (baseOut == 16 || baseOut == 8) { + i = baseOut == 16 ? 4 : 3; + for (--len; len % i; len++) str += '0'; + xd = convertBase(str, base, baseOut); + for (len = xd.length; !xd[len - 1]; --len); + + // xd[0] will always be be 1 + for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]); + } else { + str = str.charAt(0) + '.' + str.slice(1); + } + } + + str = str + (e < 0 ? 'p' : 'p+') + e; + } else if (e < 0) { + for (; ++e;) str = '0' + str; + str = '0.' + str; + } else { + if (++e > len) for (e -= len; e-- ;) str += '0'; + else if (e < len) str = str.slice(0, e) + '.' + str.slice(e); + } + } + + str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str; + } + + return x.s < 0 ? '-' + str : str; +} + + +// Does not strip trailing zeros. +function truncate(arr, len) { + if (arr.length > len) { + arr.length = len; + return true; + } +} + + +// Decimal methods + + +/* + * abs + * acos + * acosh + * add + * asin + * asinh + * atan + * atanh + * atan2 + * cbrt + * ceil + * clamp + * clone + * config + * cos + * cosh + * div + * exp + * floor + * hypot + * ln + * log + * log2 + * log10 + * max + * min + * mod + * mul + * pow + * random + * round + * set + * sign + * sin + * sinh + * sqrt + * sub + * sum + * tan + * tanh + * trunc + */ + + +/* + * Return a new Decimal whose value is the absolute value of `x`. + * + * x {number|string|Decimal} + * + */ +function abs(x) { + return new this(x).abs(); +} + + +/* + * Return a new Decimal whose value is the arccosine in radians of `x`. + * + * x {number|string|Decimal} + * + */ +function acos(x) { + return new this(x).acos(); +} + + +/* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ +function acosh(x) { + return new this(x).acosh(); +} + + +/* + * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ +function add(x, y) { + return new this(x).plus(y); +} + + +/* + * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ +function asin(x) { + return new this(x).asin(); +} + + +/* + * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ +function asinh(x) { + return new this(x).asinh(); +} + + +/* + * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ +function atan(x) { + return new this(x).atan(); +} + + +/* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ +function atanh(x) { + return new this(x).atanh(); +} + + +/* + * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi + * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi, pi] + * + * y {number|string|Decimal} The y-coordinate. + * x {number|string|Decimal} The x-coordinate. + * + * atan2(±0, -0) = ±pi + * atan2(±0, +0) = ±0 + * atan2(±0, -x) = ±pi for x > 0 + * atan2(±0, x) = ±0 for x > 0 + * atan2(-y, ±0) = -pi/2 for y > 0 + * atan2(y, ±0) = pi/2 for y > 0 + * atan2(±y, -Infinity) = ±pi for finite y > 0 + * atan2(±y, +Infinity) = ±0 for finite y > 0 + * atan2(±Infinity, x) = ±pi/2 for finite x + * atan2(±Infinity, -Infinity) = ±3*pi/4 + * atan2(±Infinity, +Infinity) = ±pi/4 + * atan2(NaN, x) = NaN + * atan2(y, NaN) = NaN + * + */ +function atan2(y, x) { + y = new this(y); + x = new this(x); + var r, + pr = this.precision, + rm = this.rounding, + wpr = pr + 4; + + // Either NaN + if (!y.s || !x.s) { + r = new this(NaN); + + // Both ±Infinity + } else if (!y.d && !x.d) { + r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75); + r.s = y.s; + + // x is ±Infinity or y is ±0 + } else if (!x.d || y.isZero()) { + r = x.s < 0 ? getPi(this, pr, rm) : new this(0); + r.s = y.s; + + // y is ±Infinity or x is ±0 + } else if (!y.d || x.isZero()) { + r = getPi(this, wpr, 1).times(0.5); + r.s = y.s; + + // Both non-zero and finite + } else if (x.s < 0) { + this.precision = wpr; + this.rounding = 1; + r = this.atan(divide(y, x, wpr, 1)); + x = getPi(this, wpr, 1); + this.precision = pr; + this.rounding = rm; + r = y.s < 0 ? r.minus(x) : r.plus(x); + } else { + r = this.atan(divide(y, x, wpr, 1)); + } + + return r; +} + + +/* + * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ +function cbrt(x) { + return new this(x).cbrt(); +} + + +/* + * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`. + * + * x {number|string|Decimal} + * + */ +function ceil(x) { + return finalise(x = new this(x), x.e + 1, 2); +} + + +/* + * Return a new Decimal whose value is `x` clamped to the range delineated by `min` and `max`. + * + * x {number|string|Decimal} + * min {number|string|Decimal} + * max {number|string|Decimal} + * + */ +function clamp(x, min, max) { + return new this(x).clamp(min, max); +} + + +/* + * Configure global settings for a Decimal constructor. + * + * `obj` is an object with one or more of the following properties, + * + * precision {number} + * rounding {number} + * toExpNeg {number} + * toExpPos {number} + * maxE {number} + * minE {number} + * modulo {number} + * crypto {boolean|number} + * defaults {true} + * + * E.g. Decimal.config({ precision: 20, rounding: 4 }) + * + */ +function config(obj) { + if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); + var i, p, v, + useDefaults = obj.defaults === true, + ps = [ + 'precision', 1, MAX_DIGITS, + 'rounding', 0, 8, + 'toExpNeg', -EXP_LIMIT, 0, + 'toExpPos', 0, EXP_LIMIT, + 'maxE', 0, EXP_LIMIT, + 'minE', -EXP_LIMIT, 0, + 'modulo', 0, 9 + ]; + + for (i = 0; i < ps.length; i += 3) { + if (p = ps[i], useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; + else throw Error(invalidArgument + p + ': ' + v); + } + } + + if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (v === true || v === false || v === 0 || v === 1) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + this[p] = true; + } else { + throw Error(cryptoUnavailable); + } + } else { + this[p] = false; + } + } else { + throw Error(invalidArgument + p + ': ' + v); + } + } + + return this; +} + + +/* + * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ +function cos(x) { + return new this(x).cos(); +} + + +/* + * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ +function cosh(x) { + return new this(x).cosh(); +} + + +/* + * Create and return a Decimal constructor with the same configuration properties as this Decimal + * constructor. + * + */ +function clone(obj) { + var i, p, ps; + + /* + * The Decimal constructor and exported function. + * Return a new Decimal instance. + * + * v {number|string|Decimal} A numeric value. + * + */ + function Decimal(v) { + var e, i, t, + x = this; + + // Decimal called without new. + if (!(x instanceof Decimal)) return new Decimal(v); + + // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor + // which points to Object. + x.constructor = Decimal; + + // Duplicate. + if (isDecimalInstance(v)) { + x.s = v.s; + + if (external) { + if (!v.d || v.e > Decimal.maxE) { + + // Infinity. + x.e = NaN; + x.d = null; + } else if (v.e < Decimal.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + } else { + x.e = v.e; + x.d = v.d.slice(); + } + } else { + x.e = v.e; + x.d = v.d ? v.d.slice() : v.d; + } + + return; + } + + t = typeof v; + + if (t === 'number') { + if (v === 0) { + x.s = 1 / v < 0 ? -1 : 1; + x.e = 0; + x.d = [0]; + return; + } + + if (v < 0) { + v = -v; + x.s = -1; + } else { + x.s = 1; + } + + // Fast path for small integers. + if (v === ~~v && v < 1e7) { + for (e = 0, i = v; i >= 10; i /= 10) e++; + + if (external) { + if (e > Decimal.maxE) { + x.e = NaN; + x.d = null; + } else if (e < Decimal.minE) { + x.e = 0; + x.d = [0]; + } else { + x.e = e; + x.d = [v]; + } + } else { + x.e = e; + x.d = [v]; + } + + return; + + // Infinity, NaN. + } else if (v * 0 !== 0) { + if (!v) x.s = NaN; + x.e = NaN; + x.d = null; + return; + } + + return parseDecimal(x, v.toString()); + + } else if (t !== 'string') { + throw Error(invalidArgument + v); + } + + // Minus sign? + if ((i = v.charCodeAt(0)) === 45) { + v = v.slice(1); + x.s = -1; + } else { + // Plus sign? + if (i === 43) v = v.slice(1); + x.s = 1; + } + + return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); + } + + Decimal.prototype = P; + + Decimal.ROUND_UP = 0; + Decimal.ROUND_DOWN = 1; + Decimal.ROUND_CEIL = 2; + Decimal.ROUND_FLOOR = 3; + Decimal.ROUND_HALF_UP = 4; + Decimal.ROUND_HALF_DOWN = 5; + Decimal.ROUND_HALF_EVEN = 6; + Decimal.ROUND_HALF_CEIL = 7; + Decimal.ROUND_HALF_FLOOR = 8; + Decimal.EUCLID = 9; + + Decimal.config = Decimal.set = config; + Decimal.clone = clone; + Decimal.isDecimal = isDecimalInstance; + + Decimal.abs = abs; + Decimal.acos = acos; + Decimal.acosh = acosh; // ES6 + Decimal.add = add; + Decimal.asin = asin; + Decimal.asinh = asinh; // ES6 + Decimal.atan = atan; + Decimal.atanh = atanh; // ES6 + Decimal.atan2 = atan2; + Decimal.cbrt = cbrt; // ES6 + Decimal.ceil = ceil; + Decimal.clamp = clamp; + Decimal.cos = cos; + Decimal.cosh = cosh; // ES6 + Decimal.div = div; + Decimal.exp = exp; + Decimal.floor = floor; + Decimal.hypot = hypot; // ES6 + Decimal.ln = ln; + Decimal.log = log; + Decimal.log10 = log10; // ES6 + Decimal.log2 = log2; // ES6 + Decimal.max = max; + Decimal.min = min; + Decimal.mod = mod; + Decimal.mul = mul; + Decimal.pow = pow; + Decimal.random = random; + Decimal.round = round; + Decimal.sign = sign; // ES6 + Decimal.sin = sin; + Decimal.sinh = sinh; // ES6 + Decimal.sqrt = sqrt; + Decimal.sub = sub; + Decimal.sum = sum; + Decimal.tan = tan; + Decimal.tanh = tanh; // ES6 + Decimal.trunc = trunc; // ES6 + + if (obj === void 0) obj = {}; + if (obj) { + if (obj.defaults !== true) { + ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto']; + for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; + } + } + + Decimal.config(obj); + + return Decimal; +} + + +/* + * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ +function div(x, y) { + return new this(x).div(y); +} + + +/* + * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The power to which to raise the base of the natural log. + * + */ +function exp(x) { + return new this(x).exp(); +} + + +/* + * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`. + * + * x {number|string|Decimal} + * + */ +function floor(x) { + return finalise(x = new this(x), x.e + 1, 3); +} + + +/* + * Return a new Decimal whose value is the square root of the sum of the squares of the arguments, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...) + * + * arguments {number|string|Decimal} + * + */ +function hypot() { + var i, n, + t = new this(0); + + external = false; + + for (i = 0; i < arguments.length;) { + n = new this(arguments[i++]); + if (!n.d) { + if (n.s) { + external = true; + return new this(1 / 0); + } + t = n; + } else if (t.d) { + t = t.plus(n.times(n)); + } + } + + external = true; + + return t.sqrt(); +} + + +/* + * Return true if object is a Decimal instance (where Decimal is any Decimal constructor), + * otherwise return false. + * + */ +function isDecimalInstance(obj) { + return obj instanceof Decimal || obj && obj.toStringTag === tag || false; +} + + +/* + * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ +function ln(x) { + return new this(x).ln(); +} + + +/* + * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base + * is specified, rounded to `precision` significant digits using rounding mode `rounding`. + * + * log[y](x) + * + * x {number|string|Decimal} The argument of the logarithm. + * y {number|string|Decimal} The base of the logarithm. + * + */ +function log(x, y) { + return new this(x).log(y); +} + + +/* + * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ +function log2(x) { + return new this(x).log(2); +} + + +/* + * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ +function log10(x) { + return new this(x).log(10); +} + + +/* + * Return a new Decimal whose value is the maximum of the arguments. + * + * arguments {number|string|Decimal} + * + */ +function max() { + return maxOrMin(this, arguments, 'lt'); +} + + +/* + * Return a new Decimal whose value is the minimum of the arguments. + * + * arguments {number|string|Decimal} + * + */ +function min() { + return maxOrMin(this, arguments, 'gt'); +} + + +/* + * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ +function mod(x, y) { + return new this(x).mod(y); +} + + +/* + * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ +function mul(x, y) { + return new this(x).mul(y); +} + + +/* + * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The base. + * y {number|string|Decimal} The exponent. + * + */ +function pow(x, y) { + return new this(x).pow(y); +} + + +/* + * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with + * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros + * are produced). + * + * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive. + * + */ +function random(sd) { + var d, e, k, n, + i = 0, + r = new this(1), + rd = []; + + if (sd === void 0) sd = this.precision; + else checkInt32(sd, 1, MAX_DIGITS); + + k = Math.ceil(sd / LOG_BASE); + + if (!this.crypto) { + for (; i < k;) rd[i++] = Math.random() * 1e7 | 0; + + // Browsers supporting crypto.getRandomValues. + } else if (crypto.getRandomValues) { + d = crypto.getRandomValues(new Uint32Array(k)); + + for (; i < k;) { + n = d[i]; + + // 0 <= n < 4294967296 + // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865). + if (n >= 4.29e9) { + d[i] = crypto.getRandomValues(new Uint32Array(1))[0]; + } else { + + // 0 <= n <= 4289999999 + // 0 <= (n % 1e7) <= 9999999 + rd[i++] = n % 1e7; + } + } + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + d = crypto.randomBytes(k *= 4); + + for (; i < k;) { + + // 0 <= n < 2147483648 + n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24); + + // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286). + if (n >= 2.14e9) { + crypto.randomBytes(4).copy(d, i); + } else { + + // 0 <= n <= 2139999999 + // 0 <= (n % 1e7) <= 9999999 + rd.push(n % 1e7); + i += 4; + } + } + + i = k / 4; + } else { + throw Error(cryptoUnavailable); + } + + k = rd[--i]; + sd %= LOG_BASE; + + // Convert trailing digits to zeros according to sd. + if (k && sd) { + n = mathpow(10, LOG_BASE - sd); + rd[i] = (k / n | 0) * n; + } + + // Remove trailing words which are zero. + for (; rd[i] === 0; i--) rd.pop(); + + // Zero? + if (i < 0) { + e = 0; + rd = [0]; + } else { + e = -1; + + // Remove leading words which are zero and adjust exponent accordingly. + for (; rd[0] === 0; e -= LOG_BASE) rd.shift(); + + // Count the digits of the first word of rd to determine leading zeros. + for (k = 1, n = rd[0]; n >= 10; n /= 10) k++; + + // Adjust the exponent for leading zeros of the first word of rd. + if (k < LOG_BASE) e -= LOG_BASE - k; + } + + r.e = e; + r.d = rd; + + return r; +} + + +/* + * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`. + * + * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL). + * + * x {number|string|Decimal} + * + */ +function round(x) { + return finalise(x = new this(x), x.e + 1, this.rounding); +} + + +/* + * Return + * 1 if x > 0, + * -1 if x < 0, + * 0 if x is 0, + * -0 if x is -0, + * NaN otherwise + * + * x {number|string|Decimal} + * + */ +function sign(x) { + x = new this(x); + return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN; +} + + +/* + * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ +function sin(x) { + return new this(x).sin(); +} + + +/* + * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ +function sinh(x) { + return new this(x).sinh(); +} + + +/* + * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ +function sqrt(x) { + return new this(x).sqrt(); +} + + +/* + * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ +function sub(x, y) { + return new this(x).sub(y); +} + + +/* + * Return a new Decimal whose value is the sum of the arguments, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * Only the result is rounded, not the intermediate calculations. + * + * arguments {number|string|Decimal} + * + */ +function sum() { + var i = 0, + args = arguments, + x = new this(args[i]); + + external = false; + for (; x.s && ++i < args.length;) x = x.plus(args[i]); + external = true; + + return finalise(x, this.precision, this.rounding); +} + + +/* + * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ +function tan(x) { + return new this(x).tan(); +} + + +/* + * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ +function tanh(x) { + return new this(x).tanh(); +} + + +/* + * Return a new Decimal whose value is `x` truncated to an integer. + * + * x {number|string|Decimal} + * + */ +function trunc(x) { + return finalise(x = new this(x), x.e + 1, 1); +} + + +P[Symbol.for('nodejs.util.inspect.custom')] = P.toString; +P[Symbol.toStringTag] = 'Decimal'; + +// Create and configure initial Decimal constructor. +export var Decimal = P.constructor = clone(DEFAULTS); + +// Create the internal constants from their string values. +LN10 = new Decimal(LN10); +PI = new Decimal(PI); + +export default Decimal; diff --git a/node_modules/decimal.js/package.json b/node_modules/decimal.js/package.json new file mode 100644 index 0000000..355b18c --- /dev/null +++ b/node_modules/decimal.js/package.json @@ -0,0 +1,40 @@ +{ + "name": "decimal.js", + "description": "An arbitrary-precision Decimal type for JavaScript.", + "version": "10.3.1", + "keywords": [ + "arbitrary", + "precision", + "arithmetic", + "big", + "number", + "decimal", + "float", + "biginteger", + "bigdecimal", + "bignumber", + "bigint", + "bignum" + ], + "repository" : { + "type": "git", + "url": "https://github.com/MikeMcl/decimal.js.git" + }, + "main": "decimal", + "module": "decimal.mjs", + "browser": "decimal.js", + "author": { + "name": "Michael Mclaughlin", + "email": "M8ch88l@gmail.com" + }, + "license": "MIT", + "scripts": { + "test": "node ./test/test.js" + }, + "types": "decimal.d.ts", + "files": [ + "decimal.js", + "decimal.mjs", + "decimal.d.ts" + ] +} diff --git a/node_modules/escape-latex/LICENSE.md b/node_modules/escape-latex/LICENSE.md new file mode 100644 index 0000000..6e54eff --- /dev/null +++ b/node_modules/escape-latex/LICENSE.md @@ -0,0 +1,18 @@ +Copyright (c) 2012 Dang Mai + +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. diff --git a/node_modules/escape-latex/README.md b/node_modules/escape-latex/README.md new file mode 100644 index 0000000..78ff9da --- /dev/null +++ b/node_modules/escape-latex/README.md @@ -0,0 +1,75 @@ +# escape-latex + +[![Greenkeeper badge](https://badges.greenkeeper.io/dangmai/escape-latex.svg)](https://greenkeeper.io/) + +[![Build Status](https://travis-ci.org/dangmai/escape-latex.png)](https://travis-ci.org/dangmai/escape-latex) + +Escape LaTeX special characters with Javascript in NodeJS (>= 4.x) environment. + +## Usage + +```javascript +npm install escape-latex +var lescape = require('escape-latex'); +lescape("String to be escaped here #yolo"); +``` + +## API + +```javascript +lescape((input: String), { + preserveFormatting: Boolean, + escapeMapFn: Function, +}); +``` + +By default, +`escape-latex` only escapes characters that would result in malformed LaTeX. +These characters include `# $ % & \ ^ _ { }`. + +This means that the final LaTeX output might not look the same as your input Javascript string. +For example, multiple spaces are kept as-is, which may be truncated to 1 space by your LaTeX software. + +If you want the final output string to be as similar to your input Javascript string as possible, +you can set the `preserveFormatting` param to `true`, like so: + +```javascript +lescape("Hello World", { preserveFormatting: true }); +// Hello~~~World +``` + +Which will be converted to three non-breaking spaces by your LaTeX software. + +The list of format characters that are escaped include `space, \t (tab), – (en-dash), — (em-dash)`. + +There is also the param `escapeMapFn` to modify the mapping of escaped characters, +so you can add/modify/remove your own escapes if necessary. + +It accepts a callback function that takes in the default character escapes and the formatting escapes as parameters, and returns a complete escape mapping. Here's an example: + +```javascript +lescape("Hello World", { + preseveFormatting: true, + escapeMapFn: function(defaultEscapes, formattingEscapes) { + formattingEscapes[" "] = "\\\\"; + return Object.assign({}, defaultEscapes, formattingEscapes); + }, +}); +// Hello\\\\\\world +``` + +## Testing + +``` +npm test +``` + +## Notes + +* If you are updating from `escape-latex < 1.0.0`, + the `en-dash` and `em-dash` are no longer escaped by default. + Please use `preserveFormatting` to turn them on if necessary. + +## License + +MIT diff --git a/node_modules/escape-latex/dist/index.js b/node_modules/escape-latex/dist/index.js new file mode 100644 index 0000000..0da9c0d --- /dev/null +++ b/node_modules/escape-latex/dist/index.js @@ -0,0 +1,80 @@ +"use strict"; + +// Map the characters to escape to their escaped values. The list is derived +// from http://www.cespedes.org/blog/85/how-to-escape-latex-special-characters + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var defaultEscapes = { + "{": "\\{", + "}": "\\}", + "\\": "\\textbackslash{}", + "#": "\\#", + $: "\\$", + "%": "\\%", + "&": "\\&", + "^": "\\textasciicircum{}", + _: "\\_", + "~": "\\textasciitilde{}" +}; +var formatEscapes = { + "\u2013": "\\--", + "\u2014": "\\---", + " ": "~", + "\t": "\\qquad{}", + "\r\n": "\\newline{}", + "\n": "\\newline{}" +}; + +var defaultEscapeMapFn = function defaultEscapeMapFn(defaultEscapes, formatEscapes) { + return _extends({}, defaultEscapes, formatEscapes); +}; + +/** + * Escape a string to be used in LaTeX documents. + * @param {string} str the string to be escaped. + * @param {boolean} params.preserveFormatting whether formatting escapes should + * be performed (default: false). + * @param {function} params.escapeMapFn the function to modify the escape maps. + * @return {string} the escaped string, ready to be used in LaTeX. + */ +module.exports = function (str) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$preserveFormatti = _ref.preserveFormatting, + preserveFormatting = _ref$preserveFormatti === undefined ? false : _ref$preserveFormatti, + _ref$escapeMapFn = _ref.escapeMapFn, + escapeMapFn = _ref$escapeMapFn === undefined ? defaultEscapeMapFn : _ref$escapeMapFn; + + var runningStr = String(str); + var result = ""; + + var escapes = escapeMapFn(_extends({}, defaultEscapes), preserveFormatting ? _extends({}, formatEscapes) : {}); + var escapeKeys = Object.keys(escapes); // as it is reused later on + + // Algorithm: Go through the string character by character, if it matches + // with one of the special characters then we'll replace it with the escaped + // version. + + var _loop = function _loop() { + var specialCharFound = false; + escapeKeys.forEach(function (key, index) { + if (specialCharFound) { + return; + } + if (runningStr.length >= key.length && runningStr.slice(0, key.length) === key) { + result += escapes[escapeKeys[index]]; + runningStr = runningStr.slice(key.length, runningStr.length); + specialCharFound = true; + } + }); + if (!specialCharFound) { + result += runningStr.slice(0, 1); + runningStr = runningStr.slice(1, runningStr.length); + } + }; + + while (runningStr) { + _loop(); + } + return result; +}; \ No newline at end of file diff --git a/node_modules/escape-latex/package.json b/node_modules/escape-latex/package.json new file mode 100644 index 0000000..a57945d --- /dev/null +++ b/node_modules/escape-latex/package.json @@ -0,0 +1,55 @@ +{ + "name": "escape-latex", + "version": "1.2.0", + "description": "Escape LaTeX special characters with Javascript", + "main": "./dist/index.js", + "files": ["dist"], + "scripts": { + "test": "mocha --require babel-core/register -u tdd ./src/**/*.test.js", + "preversion": "npm test && npm run build", + "postversion": "git push && git push --tags", + "precommit": "npm run lint && lint-staged", + "prettier": "prettier --write ./src/**/*.js", + "lint": "eslint ./src", + "init": "mkdir dist", + "clean": "rm -rf dist", + "prebuild": "npm run clean && npm run init", + "build": "babel ./src -d ./dist --ignore index.test.js" + }, + "lint-staged": { + "*.{js,json,css,md}": ["npm run prettier", "git add"] + }, + "eslintConfig": { + "parserOptions": { + "ecmaVersion": 8 + }, + "extends": ["eslint:recommended", "google", "prettier"], + "env": { + "node": "true" + } + }, + "prettier": { + "trailingComma": "all" + }, + "repository": { + "type": "git", + "url": "https://github.com/dangmai/escape-latex" + }, + "keywords": ["latex", "escape"], + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-core": "^6.26.0", + "babel-plugin-transform-object-assign": "^6.22.0", + "babel-preset-env": "^1.6.1", + "chai": "^4.1.2", + "eslint": "^5.0.1", + "eslint-config-google": "^0.9.1", + "eslint-config-prettier": "^3.0.1", + "husky": "^0.14.3", + "lint-staged": "^7.0.5", + "mocha": "^5.0.0", + "prettier": "^1.9.2" + }, + "author": "Dang Mai", + "license": "MIT" +} diff --git a/node_modules/fraction.js/LICENSE b/node_modules/fraction.js/LICENSE new file mode 100644 index 0000000..49057d3 --- /dev/null +++ b/node_modules/fraction.js/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Robert Eisele + +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. diff --git a/node_modules/fraction.js/README.md b/node_modules/fraction.js/README.md new file mode 100644 index 0000000..8ae1963 --- /dev/null +++ b/node_modules/fraction.js/README.md @@ -0,0 +1,492 @@ +# Fraction.js - ℚ in JavaScript + +[![NPM Package](https://nodei.co/npm-dl/fraction.js.png?months=6&height=1)](https://npmjs.org/package/fraction.js) + +[![Build Status](https://travis-ci.org/infusion/Fraction.js.svg?branch=master)](https://travis-ci.org/infusion/Fraction.js) +[![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT) + + +Tired of inprecise numbers represented by doubles, which have to store rational and irrational numbers like PI or sqrt(2) the same way? Obviously the following problem is preventable: + +```javascript +1 / 98 * 98 // = 0.9999999999999999 +``` + +If you need more precision or just want a fraction as a result, have a look at *Fraction.js*: + +```javascript +var Fraction = require('fraction.js'); + +Fraction(1).div(98).mul(98) // = 1 +``` + +Internally, numbers are represented as *numerator / denominator*, which adds just a little overhead. However, the library is written with performance in mind and outperforms any other implementation, as you can see [here](http://jsperf.com/convert-a-rational-number-to-a-babylonian-fractions/28). This basic data-type makes it the perfect basis for [Polynomial.js](https://github.com/infusion/Polynomial.js) and [Math.js](https://github.com/josdejong/mathjs). + +Convert decimal to fraction +=== +The simplest job for fraction.js is to get a fraction out of a decimal: +```javascript +var x = new Fraction(1.88); +var res = x.toFraction(true); // String "1 22/25" +``` + +Examples / Motivation +=== +A simple example might be + +```javascript +var f = new Fraction("9.4'31'"); // 9.4313131313131... +f.mul([-4, 3]).mod("4.'8'"); // 4.88888888888888... +``` +The result is + +```javascript +console.log(f.toFraction()); // -4154 / 1485 +``` +You could of course also access the sign (s), numerator (n) and denominator (d) on your own: +```javascript +f.s * f.n / f.d = -1 * 4154 / 1485 = -2.797306... +``` + +If you would try to calculate it yourself, you would come up with something like: + +```javascript +(9.4313131 * (-4 / 3)) % 4.888888 = -2.797308133... +``` + +Quite okay, but yea - not as accurate as it could be. + + +Laplace Probability +=== +Simple example. What's the probability of throwing a 3, and 1 or 4, and 2 or 4 or 6 with a fair dice? + +P({3}): +```javascript +var p = new Fraction([3].length, 6).toString(); // 0.1(6) +``` + +P({1, 4}): +```javascript +var p = new Fraction([1, 4].length, 6).toString(); // 0.(3) +``` + +P({2, 4, 6}): +```javascript +var p = new Fraction([2, 4, 6].length, 6).toString(); // 0.5 +``` + +Convert degrees/minutes/seconds to precise rational representation: +=== + +57+45/60+17/3600 +```javascript +var deg = 57; // 57° +var min = 45; // 45 Minutes +var sec = 17; // 17 Seconds + +new Fraction(deg).add(min, 60).add(sec, 3600).toString() // -> 57.7547(2) +``` + +Rounding a fraction to the closest tape measure value +=== + +A tape measure is usually divided in parts of `1/16`. Rounding a given fraction to the closest value on a tape measure can be determined by + +```javascript +function closestTapeMeasure(frac) { + + /* + k/16 ≤ a/b < (k+1)/16 + ⇔ k ≤ 16*a/b < (k+1) + ⇔ k = floor(16*a/b) + */ + return new Fraction(Math.round(16 * Fraction(frac).valueOf()), 16); +} +// closestTapeMeasure("1/3") // 5/16 +``` + +Rational approximation of irrational numbers +=== + +Now it's getting messy ;d To approximate a number like *sqrt(5) - 2* with a numerator and denominator, you can reformat the equation as follows: *pow(n / d + 2, 2) = 5*. + +Then the following algorithm will generate the rational number besides the binary representation. + +```javascript +var x = "/", s = ""; + +var a = new Fraction(0), + b = new Fraction(1); +for (var n = 0; n <= 10; n++) { + + var c = a.add(b).div(2); + + console.log(n + "\t" + a + "\t" + b + "\t" + c + "\t" + x); + + if (c.add(2).pow(2) < 5) { + a = c; + x = "1"; + } else { + b = c; + x = "0"; + } + s+= x; +} +console.log(s) +``` + +The result is + +``` +n a[n] b[n] c[n] x[n] +0 0/1 1/1 1/2 / +1 0/1 1/2 1/4 0 +2 0/1 1/4 1/8 0 +3 1/8 1/4 3/16 1 +4 3/16 1/4 7/32 1 +5 7/32 1/4 15/64 1 +6 15/64 1/4 31/128 1 +7 15/64 31/128 61/256 0 +8 15/64 61/256 121/512 0 +9 15/64 121/512 241/1024 0 +10 241/1024 121/512 483/2048 1 +``` +Thus the approximation after 11 iterations of the bisection method is *483 / 2048* and the binary representation is 0.00111100011 (see [WolframAlpha](http://www.wolframalpha.com/input/?i=sqrt%285%29-2+binary)) + + +I published another example on how to approximate PI with fraction.js on my [blog](http://www.xarg.org/2014/03/precise-calculations-in-javascript/) (Still not the best idea to approximate irrational numbers, but it illustrates the capabilities of Fraction.js perfectly). + + +Get the exact fractional part of a number +--- +```javascript +var f = new Fraction("-6.(3416)"); +console.log("" + f.mod(1).abs()); // Will print 0.(3416) +``` + +Mathematical correct modulo +--- +The behaviour on negative congruences is different to most modulo implementations in computer science. Even the *mod()* function of Fraction.js behaves in the typical way. To solve the problem of having the mathematical correct modulo with Fraction.js you could come up with this: + +```javascript +var a = -1; +var b = 10.99; + +console.log(new Fraction(a) + .mod(b)); // Not correct, usual Modulo + +console.log(new Fraction(a) + .mod(b).add(b).mod(b)); // Correct! Mathematical Modulo +``` + +fmod() impreciseness circumvented +--- +It turns out that Fraction.js outperforms almost any fmod() implementation, including JavaScript itself, [php.js](http://phpjs.org/functions/fmod/), C++, Python, Java and even Wolframalpha due to the fact that numbers like 0.05, 0.1, ... are infinite decimal in base 2. + +The equation *fmod(4.55, 0.05)* gives *0.04999999999999957*, wolframalpha says *1/20*. The correct answer should be **zero**, as 0.05 divides 4.55 without any remainder. + + +Parser +=== + +Any function (see below) as well as the constructor of the *Fraction* class parses its input and reduce it to the smallest term. + +You can pass either Arrays, Objects, Integers, Doubles or Strings. + +Arrays / Objects +--- +```javascript +new Fraction(numerator, denominator); +new Fraction([numerator, denominator]); +new Fraction({n: numerator, d: denominator}); +``` + +Integers +--- +```javascript +new Fraction(123); +``` + +Doubles +--- +```javascript +new Fraction(55.4); +``` + +**Note:** If you pass a double as it is, Fraction.js will perform a number analysis based on Farey Sequences. If you concern performance, cache Fraction.js objects and pass arrays/objects. + +The method is really precise, but too large exact numbers, like 1234567.9991829 will result in a wrong approximation. If you want to keep the number as it is, convert it to a string, as the string parser will not perform any further observations. If you have problems with the approximation, in the file `examples/approx.js` is a different approximation algorithm, which might work better in some more specific use-cases. + + +Strings +--- +```javascript +new Fraction("123.45"); +new Fraction("123/45"); // A rational number represented as two decimals, separated by a slash +new Fraction("123:45"); // A rational number represented as two decimals, separated by a colon +new Fraction("4 123/45"); // A rational number represented as a whole number and a fraction +new Fraction("123.'456'"); // Note the quotes, see below! +new Fraction("123.(456)"); // Note the brackets, see below! +new Fraction("123.45'6'"); // Note the quotes, see below! +new Fraction("123.45(6)"); // Note the brackets, see below! +``` + +Two arguments +--- +```javascript +new Fraction(3, 2); // 3/2 = 1.5 +``` + +Repeating decimal places +--- +*Fraction.js* can easily handle repeating decimal places. For example *1/3* is *0.3333...*. There is only one repeating digit. As you can see in the examples above, you can pass a number like *1/3* as "0.'3'" or "0.(3)", which are synonym. There are no tests to parse something like 0.166666666 to 1/6! If you really want to handle this number, wrap around brackets on your own with the function below for example: 0.1(66666666) + +Assume you want to divide 123.32 / 33.6(567). [WolframAlpha](http://www.wolframalpha.com/input/?i=123.32+%2F+%2812453%2F370%29) states that you'll get a period of 1776 digits. *Fraction.js* comes to the same result. Give it a try: + +```javascript +var f = new Fraction("123.32"); +console.log("Bam: " + f.div("33.6(567)")); +``` + +To automatically make a number like "0.123123123" to something more Fraction.js friendly like "0.(123)", I hacked this little brute force algorithm in a 10 minutes. Improvements are welcome... + +```javascript +function formatDecimal(str) { + + var comma, pre, offset, pad, times, repeat; + + if (-1 === (comma = str.indexOf("."))) + return str; + + pre = str.substr(0, comma + 1); + str = str.substr(comma + 1); + + for (var i = 0; i < str.length; i++) { + + offset = str.substr(0, i); + + for (var j = 0; j < 5; j++) { + + pad = str.substr(i, j + 1); + + times = Math.ceil((str.length - offset.length) / pad.length); + + repeat = new Array(times + 1).join(pad); // Silly String.repeat hack + + if (0 === (offset + repeat).indexOf(str)) { + return pre + offset + "(" + pad + ")"; + } + } + } + return null; +} + +var f, x = formatDecimal("13.0123123123"); // = 13.0(123) +if (x !== null) { + f = new Fraction(x); +} +``` + +Attributes +=== + +The Fraction object allows direct access to the numerator, denominator and sign attributes. It is ensured that only the sign-attribute holds sign information so that a sign comparison is only necessary against this attribute. + +```javascript +var f = new Fraction('-1/2'); +console.log(f.n); // Numerator: 1 +console.log(f.d); // Denominator: 2 +console.log(f.s); // Sign: -1 +``` + + +Functions +=== + +Fraction abs() +--- +Returns the actual number without any sign information + +Fraction neg() +--- +Returns the actual number with flipped sign in order to get the additive inverse + +Fraction add(n) +--- +Returns the sum of the actual number and the parameter n + +Fraction sub(n) +--- +Returns the difference of the actual number and the parameter n + +Fraction mul(n) +--- +Returns the product of the actual number and the parameter n + +Fraction div(n) +--- +Returns the quotient of the actual number and the parameter n + +Fraction pow(exp) +--- +Returns the power of the actual number, raised to an possible rational exponent. If the result becomes non-rational the function returns `null`. + +Fraction mod(n) +--- +Returns the modulus (rest of the division) of the actual object and n (this % n). It's a much more precise [fmod()](#fmod-impreciseness-circumvented) if you will. Please note that *mod()* is just like the modulo operator of most programming languages. If you want a mathematical correct modulo, see [here](#mathematical-correct-modulo). + +Fraction mod() +--- +Returns the modulus (rest of the division) of the actual object (numerator mod denominator) + +Fraction gcd(n) +--- +Returns the fractional greatest common divisor + +Fraction lcm(n) +--- +Returns the fractional least common multiple + +Fraction ceil([places=0-16]) +--- +Returns the ceiling of a rational number with Math.ceil + +Fraction floor([places=0-16]) +--- +Returns the floor of a rational number with Math.floor + +Fraction round([places=0-16]) +--- +Returns the rational number rounded with Math.round + +Fraction inverse() +--- +Returns the multiplicative inverse of the actual number (n / d becomes d / n) in order to get the reciprocal + +Fraction simplify([eps=0.001]) +--- +Simplifies the rational number under a certain error threshold. Ex. `0.333` will be `1/3` with `eps=0.001` + +boolean equals(n) +--- +Check if two numbers are equal + +int compare(n) +--- +Compare two numbers. +``` +result < 0: n is greater than actual number +result > 0: n is smaller than actual number +result = 0: n is equal to the actual number +``` + +boolean divisible(n) +--- +Check if two numbers are divisible (n divides this) + +double valueOf() +--- +Returns a decimal representation of the fraction + +String toString([decimalPlaces=15]) +--- +Generates an exact string representation of the actual object. For repeated decimal places all digits are collected within brackets, like `1/3 = "0.(3)"`. For all other numbers, up to `decimalPlaces` significant digits are collected - which includes trailing zeros if the number is getting truncated. However, `1/2 = "0.5"` without trailing zeros of course. + +**Note:** As `valueOf()` and `toString()` are provided, `toString()` is only called implicitly in a real string context. Using the plus-operator like `"123" + new Fraction` will call valueOf(), because JavaScript tries to combine two primitives first and concatenates them later, as string will be the more dominant type. `alert(new Fraction)` or `String(new Fraction)` on the other hand will do what you expect. If you really want to have control, you should call `toString()` or `valueOf()` explicitly! + +String toLatex(excludeWhole=false) +--- +Generates an exact LaTeX representation of the actual object. You can see a [live demo](http://www.xarg.org/2014/03/precise-calculations-in-javascript/) on my blog. + +The optional boolean parameter indicates if you want to exclude the whole part. "1 1/3" instead of "4/3" + +String toFraction(excludeWhole=false) +--- +Gets a string representation of the fraction + +The optional boolean parameter indicates if you want to exclude the whole part. "1 1/3" instead of "4/3" + +Array toContinued() +--- +Gets an array of the fraction represented as a continued fraction. The first element always contains the whole part. + +```javascript +var f = new Fraction('88/33'); +var c = f.toContinued(); // [2, 1, 2] +``` + +Fraction clone() +--- +Creates a copy of the actual Fraction object + + +Exceptions +=== +If a really hard error occurs (parsing error, division by zero), *fraction.js* throws exceptions! Please make sure you handle them correctly. + + + +Installation +=== +Installing fraction.js is as easy as cloning this repo or use one of the following commands: + +``` +bower install fraction.js +``` +or + +``` +npm install fraction.js +``` + +Using Fraction.js with the browser +=== +```html + + +``` + +Using Fraction.js with require.js +=== +```html + + +``` + +Using Fraction.js with TypeScript +=== +```js +import Fraction from "fraction.js"; +console.log(Fraction("123/456")); +``` + +Coding Style +=== +As every library I publish, fraction.js is also built to be as small as possible after compressing it with Google Closure Compiler in advanced mode. Thus the coding style orientates a little on maxing-out the compression rate. Please make sure you keep this style if you plan to extend the library. + + +Precision +=== +Fraction.js tries to circumvent floating point errors, by having an internal representation of numerator and denominator. As it relies on JavaScript, there is also a limit. The biggest number representable is `Number.MAX_SAFE_INTEGER / 1` and the smallest is `-1 / Number.MAX_SAFE_INTEGER`, with `Number.MAX_SAFE_INTEGER=9007199254740991`. If this is not enough, there is `bigfraction.js` shipped experimentally, which relies on `BigInt` and should become the new Fraction.js eventually. + +Testing +=== +If you plan to enhance the library, make sure you add test cases and all the previous tests are passing. You can test the library with + +``` +npm test +``` + + +Copyright and licensing +=== +Copyright (c) 2014-2019, [Robert Eisele](https://www.xarg.org/) +Dual licensed under the MIT or GPL Version 2 licenses. diff --git a/node_modules/fraction.js/bigfraction.js b/node_modules/fraction.js/bigfraction.js new file mode 100644 index 0000000..2e504d7 --- /dev/null +++ b/node_modules/fraction.js/bigfraction.js @@ -0,0 +1,895 @@ +/** + * @license Fraction.js v4.2.0 23/05/2021 + * https://www.xarg.org/2014/03/rational-numbers-in-javascript/ + * + * Copyright (c) 2021, Robert Eisele (robert@xarg.org) + * Dual licensed under the MIT or GPL Version 2 licenses. + **/ + + +/** + * + * This class offers the possibility to calculate fractions. + * You can pass a fraction in different formats. Either as array, as double, as string or as an integer. + * + * Array/Object form + * [ 0 => , 1 => ] + * [ n => , d => ] + * + * Integer form + * - Single integer value + * + * Double form + * - Single double value + * + * String form + * 123.456 - a simple double + * 123/456 - a string fraction + * 123.'456' - a double with repeating decimal places + * 123.(456) - synonym + * 123.45'6' - a double with repeating last place + * 123.45(6) - synonym + * + * Example: + * + * let f = new Fraction("9.4'31'"); + * f.mul([-4, 3]).div(4.9); + * + */ + +(function(root) { + + "use strict"; + + // Set Identity function to downgrade BigInt to Number if needed + if (!BigInt) BigInt = function(n) { if (isNaN(n)) throw new Error(""); return n; }; + + const C_ONE = BigInt(1); + const C_ZERO = BigInt(0); + const C_TEN = BigInt(10); + const C_TWO = BigInt(2); + const C_FIVE = BigInt(5); + + // Maximum search depth for cyclic rational numbers. 2000 should be more than enough. + // Example: 1/7 = 0.(142857) has 6 repeating decimal places. + // If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits + const MAX_CYCLE_LEN = 2000; + + // Parsed data to avoid calling "new" all the time + const P = { + "s": C_ONE, + "n": C_ZERO, + "d": C_ONE + }; + + function assign(n, s) { + + try { + n = BigInt(n); + } catch (e) { + throw Fraction['InvalidParameter']; + } + return n * s; + } + + // Creates a new Fraction internally without the need of the bulky constructor + function newFraction(n, d) { + + if (d === C_ZERO) { + throw Fraction['DivisionByZero']; + } + + const f = Object.create(Fraction.prototype); + f["s"] = n < C_ZERO ? -C_ONE : C_ONE; + + n = n < C_ZERO ? -n : n; + + const a = gcd(n, d); + + f["n"] = n / a; + f["d"] = d / a; + return f; + } + + function factorize(num) { + + const factors = {}; + + let n = num; + let i = C_TWO; + let s = C_FIVE - C_ONE; + + while (s <= n) { + + while (n % i === C_ZERO) { + n/= i; + factors[i] = (factors[i] || C_ZERO) + C_ONE; + } + s+= C_ONE + C_TWO * i++; + } + + if (n !== num) { + if (n > 1) + factors[n] = (factors[n] || C_ZERO) + C_ONE; + } else { + factors[num] = (factors[num] || C_ZERO) + C_ONE; + } + return factors; + } + + const parse = function(p1, p2) { + + let n = C_ZERO, d = C_ONE, s = C_ONE; + + if (p1 === undefined || p1 === null) { + /* void */ + } else if (p2 !== undefined) { + n = BigInt(p1); + d = BigInt(p2); + s = n * d; + + if (n % C_ONE !== C_ZERO || d % C_ONE !== C_ZERO) { + throw Fraction['NonIntegerParameter']; + } + + } else if (typeof p1 === "object") { + if ("d" in p1 && "n" in p1) { + n = BigInt(p1["n"]); + d = BigInt(p1["d"]); + if ("s" in p1) + n*= BigInt(p1["s"]); + } else if (0 in p1) { + n = BigInt(p1[0]); + if (1 in p1) + d = BigInt(p1[1]); + } else if (p1 instanceof BigInt) { + n = BigInt(p1); + } else { + throw Fraction['InvalidParameter']; + } + s = n * d; + } else if (typeof p1 === "bigint") { + n = p1; + s = p1; + d = BigInt(1); + } else if (typeof p1 === "number") { + + if (isNaN(p1)) { + throw Fraction['InvalidParameter']; + } + + if (p1 < 0) { + s = -C_ONE; + p1 = -p1; + } + + if (p1 % 1 === 0) { + n = BigInt(p1); + } else if (p1 > 0) { // check for != 0, scale would become NaN (log(0)), which converges really slow + + let z = 1; + + let A = 0, B = 1; + let C = 1, D = 1; + + let N = 10000000; + + if (p1 >= 1) { + z = 10 ** Math.floor(1 + Math.log10(p1)); + p1/= z; + } + + // Using Farey Sequences + + while (B <= N && D <= N) { + let M = (A + C) / (B + D); + + if (p1 === M) { + if (B + D <= N) { + n = A + C; + d = B + D; + } else if (D > B) { + n = C; + d = D; + } else { + n = A; + d = B; + } + break; + + } else { + + if (p1 > M) { + A+= C; + B+= D; + } else { + C+= A; + D+= B; + } + + if (B > N) { + n = C; + d = D; + } else { + n = A; + d = B; + } + } + } + n = BigInt(n) * BigInt(z); + d = BigInt(d); + + } + + } else if (typeof p1 === "string") { + + let ndx = 0; + + let v = C_ZERO, w = C_ZERO, x = C_ZERO, y = C_ONE, z = C_ONE; + + let match = p1.match(/\d+|./g); + + if (match === null) + throw Fraction['InvalidParameter']; + + if (match[ndx] === '-') {// Check for minus sign at the beginning + s = -C_ONE; + ndx++; + } else if (match[ndx] === '+') {// Check for plus sign at the beginning + ndx++; + } + + if (match.length === ndx + 1) { // Check if it's just a simple number "1234" + w = assign(match[ndx++], s); + } else if (match[ndx + 1] === '.' || match[ndx] === '.') { // Check if it's a decimal number + + if (match[ndx] !== '.') { // Handle 0.5 and .5 + v = assign(match[ndx++], s); + } + ndx++; + + // Check for decimal places + if (ndx + 1 === match.length || match[ndx + 1] === '(' && match[ndx + 3] === ')' || match[ndx + 1] === "'" && match[ndx + 3] === "'") { + w = assign(match[ndx], s); + y = C_TEN ** BigInt(match[ndx].length); + ndx++; + } + + // Check for repeating places + if (match[ndx] === '(' && match[ndx + 2] === ')' || match[ndx] === "'" && match[ndx + 2] === "'") { + x = assign(match[ndx + 1], s); + z = C_TEN ** BigInt(match[ndx + 1].length) - C_ONE; + ndx+= 3; + } + + } else if (match[ndx + 1] === '/' || match[ndx + 1] === ':') { // Check for a simple fraction "123/456" or "123:456" + w = assign(match[ndx], s); + y = assign(match[ndx + 2], C_ONE); + ndx+= 3; + } else if (match[ndx + 3] === '/' && match[ndx + 1] === ' ') { // Check for a complex fraction "123 1/2" + v = assign(match[ndx], s); + w = assign(match[ndx + 2], s); + y = assign(match[ndx + 4], C_ONE); + ndx+= 5; + } + + if (match.length <= ndx) { // Check for more tokens on the stack + d = y * z; + s = /* void */ + n = x + d * v + z * w; + } else { + throw Fraction['InvalidParameter']; + } + + } else { + throw Fraction['InvalidParameter']; + } + + if (d === C_ZERO) { + throw Fraction['DivisionByZero']; + } + + P["s"] = s < C_ZERO ? -C_ONE : C_ONE; + P["n"] = n < C_ZERO ? -n : n; + P["d"] = d < C_ZERO ? -d : d; + }; + + function modpow(b, e, m) { + + let r = C_ONE; + for (; e > C_ZERO; b = (b * b) % m, e >>= C_ONE) { + + if (e & C_ONE) { + r = (r * b) % m; + } + } + return r; + } + + function cycleLen(n, d) { + + for (; d % C_TWO === C_ZERO; + d/= C_TWO) { + } + + for (; d % C_FIVE === C_ZERO; + d/= C_FIVE) { + } + + if (d === C_ONE) // Catch non-cyclic numbers + return C_ZERO; + + // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem: + // 10^(d-1) % d == 1 + // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone, + // as we want to translate the numbers to strings. + + let rem = C_TEN % d; + let t = 1; + + for (; rem !== C_ONE; t++) { + rem = rem * C_TEN % d; + + if (t > MAX_CYCLE_LEN) + return C_ZERO; // Returning 0 here means that we don't print it as a cyclic number. It's likely that the answer is `d-1` + } + return BigInt(t); + } + + function cycleStart(n, d, len) { + + let rem1 = C_ONE; + let rem2 = modpow(C_TEN, len, d); + + for (let t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE) + // Solve 10^s == 10^(s+t) (mod d) + + if (rem1 === rem2) + return BigInt(t); + + rem1 = rem1 * C_TEN % d; + rem2 = rem2 * C_TEN % d; + } + return 0; + } + + function gcd(a, b) { + + if (!a) + return b; + if (!b) + return a; + + while (1) { + a%= b; + if (!a) + return b; + b%= a; + if (!b) + return a; + } + } + + /** + * Module constructor + * + * @constructor + * @param {number|Fraction=} a + * @param {number=} b + */ + function Fraction(a, b) { + + parse(a, b); + + if (this instanceof Fraction) { + a = gcd(P["d"], P["n"]); // Abuse a + this["s"] = P["s"]; + this["n"] = P["n"] / a; + this["d"] = P["d"] / a; + } else { + return newFraction(P['s'] * P['n'], P['d']); + } + } + + Fraction['DivisionByZero'] = new Error("Division by Zero"); + Fraction['InvalidParameter'] = new Error("Invalid argument"); + Fraction['NonIntegerParameter'] = new Error("Parameters must be integer"); + + Fraction.prototype = { + + "s": C_ONE, + "n": C_ZERO, + "d": C_ONE, + + /** + * Calculates the absolute value + * + * Ex: new Fraction(-4).abs() => 4 + **/ + "abs": function() { + + return newFraction(this["n"], this["d"]); + }, + + /** + * Inverts the sign of the current fraction + * + * Ex: new Fraction(-4).neg() => 4 + **/ + "neg": function() { + + return newFraction(-this["s"] * this["n"], this["d"]); + }, + + /** + * Adds two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => 467 / 30 + **/ + "add": function(a, b) { + + parse(a, b); + return newFraction( + this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Subtracts two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => -427 / 30 + **/ + "sub": function(a, b) { + + parse(a, b); + return newFraction( + this["s"] * this["n"] * P["d"] - P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Multiplies two rational numbers + * + * Ex: new Fraction("-17.(345)").mul(3) => 5776 / 111 + **/ + "mul": function(a, b) { + + parse(a, b); + return newFraction( + this["s"] * P["s"] * this["n"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Divides two rational numbers + * + * Ex: new Fraction("-17.(345)").inverse().div(3) + **/ + "div": function(a, b) { + + parse(a, b); + return newFraction( + this["s"] * P["s"] * this["n"] * P["d"], + this["d"] * P["n"] + ); + }, + + /** + * Clones the actual object + * + * Ex: new Fraction("-17.(345)").clone() + **/ + "clone": function() { + return newFraction(this['s'] * this['n'], this['d']); + }, + + /** + * Calculates the modulo of two rational numbers - a more precise fmod + * + * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6) + **/ + "mod": function(a, b) { + + if (a === undefined) { + return newFraction(this["s"] * this["n"] % this["d"], C_ONE); + } + + parse(a, b); + if (0 === P["n"] && 0 === this["d"]) { + throw Fraction['DivisionByZero']; + } + + /* + * First silly attempt, kinda slow + * + return that["sub"]({ + "n": num["n"] * Math.floor((this.n / this.d) / (num.n / num.d)), + "d": num["d"], + "s": this["s"] + });*/ + + /* + * New attempt: a1 / b1 = a2 / b2 * q + r + * => b2 * a1 = a2 * b1 * q + b1 * b2 * r + * => (b2 * a1 % a2 * b1) / (b1 * b2) + */ + return newFraction( + this["s"] * (P["d"] * this["n"]) % (P["n"] * this["d"]), + P["d"] * this["d"] + ); + }, + + /** + * Calculates the fractional gcd of two rational numbers + * + * Ex: new Fraction(5,8).gcd(3,7) => 1/56 + */ + "gcd": function(a, b) { + + parse(a, b); + + // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d) + + return newFraction(gcd(P["n"], this["n"]) * gcd(P["d"], this["d"]), P["d"] * this["d"]); + }, + + /** + * Calculates the fractional lcm of two rational numbers + * + * Ex: new Fraction(5,8).lcm(3,7) => 15 + */ + "lcm": function(a, b) { + + parse(a, b); + + // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d) + + if (P["n"] === C_ZERO && this["n"] === C_ZERO) { + return newFraction(C_ZERO, C_ONE); + } + return newFraction(P["n"] * this["n"], gcd(P["n"], this["n"]) * gcd(P["d"], this["d"])); + }, + + /** + * Gets the inverse of the fraction, means numerator and denominator are exchanged + * + * Ex: new Fraction([-3, 4]).inverse() => -4 / 3 + **/ + "inverse": function() { + return newFraction(this["s"] * this["d"], this["n"]); + }, + + /** + * Calculates the fraction to some integer exponent + * + * Ex: new Fraction(-1,2).pow(-3) => -8 + */ + "pow": function(a, b) { + + parse(a, b); + + // Trivial case when exp is an integer + + if (P['d'] === C_ONE) { + + if (P['s'] < C_ZERO) { + return newFraction((this['s'] * this["d"]) ** P['n'], this["n"] ** P['n']); + } else { + return newFraction((this['s'] * this["n"]) ** P['n'], this["d"] ** P['n']); + } + } + + // Negative roots become complex + // (-a/b)^(c/d) = x + // <=> (-1)^(c/d) * (a/b)^(c/d) = x + // <=> (cos(pi) + i*sin(pi))^(c/d) * (a/b)^(c/d) = x + // <=> (cos(c*pi/d) + i*sin(c*pi/d)) * (a/b)^(c/d) = x # DeMoivre's formula + // From which follows that only for c=0 the root is non-complex + if (this['s'] < C_ZERO) return null; + + // Now prime factor n and d + let N = factorize(this['n']); + let D = factorize(this['d']); + + // Exponentiate and take root for n and d individually + let n = C_ONE; + let d = C_ONE; + for (let k in N) { + if (k === '1') continue; + if (k === '0') { + n = C_ZERO; + break; + } + N[k]*= P['n']; + + if (N[k] % P['d'] === C_ZERO) { + N[k]/= P['d']; + } else return null; + n*= BigInt(k) ** N[k]; + } + + for (let k in D) { + if (k === '1') continue; + D[k]*= P['n']; + + if (D[k] % P['d'] === C_ZERO) { + D[k]/= P['d']; + } else return null; + d*= BigInt(k) ** D[k]; + } + + if (P['s'] < C_ZERO) { + return newFraction(d, n); + } + return newFraction(n, d); + }, + + /** + * Check if two rational numbers are the same + * + * Ex: new Fraction(19.6).equals([98, 5]); + **/ + "equals": function(a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] === P["s"] * P["n"] * this["d"]; // Same as compare() === 0 + }, + + /** + * Check if two rational numbers are the same + * + * Ex: new Fraction(19.6).equals([98, 5]); + **/ + "compare": function(a, b) { + + parse(a, b); + let t = (this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]); + + return (C_ZERO < t) - (t < C_ZERO); + }, + + /** + * Calculates the ceil of a rational number + * + * Ex: new Fraction('4.(3)').ceil() => (5 / 1) + **/ + "ceil": function(places) { + + places = C_TEN ** BigInt(places || 0); + + return newFraction(this["s"] * places * this["n"] / this["d"] + + (places * this["n"] % this["d"] > C_ZERO && this["s"] >= C_ZERO ? C_ONE : C_ZERO), + places); + }, + + /** + * Calculates the floor of a rational number + * + * Ex: new Fraction('4.(3)').floor() => (4 / 1) + **/ + "floor": function(places) { + + places = C_TEN ** BigInt(places || 0); + + return newFraction(this["s"] * places * this["n"] / this["d"] - + (places * this["n"] % this["d"] > C_ZERO && this["s"] < C_ZERO ? C_ONE : C_ZERO), + places); + }, + + /** + * Rounds a rational numbers + * + * Ex: new Fraction('4.(3)').round() => (4 / 1) + **/ + "round": function(places) { + + places = C_TEN ** BigInt(places || 0); + + /* Derivation: + + s >= 0: + round(n / d) = trunc(n / d) + (n % d) / d >= 0.5 ? 1 : 0 + = trunc(n / d) + 2(n % d) >= d ? 1 : 0 + s < 0: + round(n / d) =-trunc(n / d) - (n % d) / d > 0.5 ? 1 : 0 + =-trunc(n / d) - 2(n % d) > d ? 1 : 0 + + =>: + + round(s * n / d) = s * trunc(n / d) + s * (C + 2(n % d) > d ? 1 : 0) + where C = s >= 0 ? 1 : 0, to fix the >= for the positve case. + */ + + return newFraction(this["s"] * places * this["n"] / this["d"] + + this["s"] * ((this["s"] >= C_ZERO ? C_ONE : C_ZERO) + C_TWO * (places * this["n"] % this["d"]) > this["d"] ? C_ONE : C_ZERO), + places); + }, + + /** + * Check if two rational numbers are divisible + * + * Ex: new Fraction(19.6).divisible(1.5); + */ + "divisible": function(a, b) { + + parse(a, b); + return !(!(P["n"] * this["d"]) || ((this["n"] * P["d"]) % (P["n"] * this["d"]))); + }, + + /** + * Returns a decimal representation of the fraction + * + * Ex: new Fraction("100.'91823'").valueOf() => 100.91823918239183 + **/ + 'valueOf': function() { + // Best we can do so far + return Number(this["s"] * this["n"]) / Number(this["d"]); + }, + + /** + * Creates a string representation of a fraction with all digits + * + * Ex: new Fraction("100.'91823'").toString() => "100.(91823)" + **/ + 'toString': function(dec) { + + let N = this["n"]; + let D = this["d"]; + + dec = dec || 15; // 15 = decimal places when no repitation + + let cycLen = cycleLen(N, D); // Cycle length + let cycOff = cycleStart(N, D, cycLen); // Cycle start + + let str = this['s'] < C_ZERO ? "-" : ""; + + // Append integer part + str+= N / D; + + N%= D; + N*= C_TEN; + + if (N) + str+= "."; + + if (cycLen) { + + for (let i = cycOff; i--;) { + str+= N / D; + N%= D; + N*= C_TEN; + } + str+= "("; + for (let i = cycLen; i--;) { + str+= N / D; + N%= D; + N*= C_TEN; + } + str+= ")"; + } else { + for (let i = dec; N && i--;) { + str+= N / D; + N%= D; + N*= C_TEN; + } + } + return str; + }, + + /** + * Returns a string-fraction representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toFraction() => "4 1/3" + **/ + 'toFraction': function(excludeWhole) { + + let n = this["n"]; + let d = this["d"]; + let str = this['s'] < C_ZERO ? "-" : ""; + + if (d === C_ONE) { + str+= n; + } else { + let whole = n / d; + if (excludeWhole && whole > C_ZERO) { + str+= whole; + str+= " "; + n%= d; + } + + str+= n; + str+= '/'; + str+= d; + } + return str; + }, + + /** + * Returns a latex representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toLatex() => "\frac{4}{3}" + **/ + 'toLatex': function(excludeWhole) { + + let n = this["n"]; + let d = this["d"]; + let str = this['s'] < C_ZERO ? "-" : ""; + + if (d === C_ONE) { + str+= n; + } else { + let whole = n / d; + if (excludeWhole && whole > C_ZERO) { + str+= whole; + n%= d; + } + + str+= "\\frac{"; + str+= n; + str+= '}{'; + str+= d; + str+= '}'; + } + return str; + }, + + /** + * Returns an array of continued fraction elements + * + * Ex: new Fraction("7/8").toContinued() => [0,1,7] + */ + 'toContinued': function() { + + let a = this['n']; + let b = this['d']; + let res = []; + + do { + res.push(a / b); + let t = a % b; + a = b; + b = t; + } while (a !== C_ONE); + + return res; + }, + + "simplify": function(eps) { + + eps = eps || 0.001; + + const thisABS = this['abs'](); + const cont = thisABS['toContinued'](); + + for (let i = 1; i < cont.length; i++) { + + let s = newFraction(cont[i - 1], C_ONE); + for (let k = i - 2; k >= 0; k--) { + s = s['inverse']()['add'](cont[k]); + } + + if (s['sub'](thisABS)['abs']().valueOf() < eps) { + return s['mul'](this['s']); + } + } + return this; + } + }; + + if (typeof define === "function" && define["amd"]) { + define([], function() { + return Fraction; + }); + } else if (typeof exports === "object") { + Object.defineProperty(exports, "__esModule", { 'value': true }); + Fraction['default'] = Fraction; + Fraction['Fraction'] = Fraction; + module['exports'] = Fraction; + } else { + root['Fraction'] = Fraction; + } + +})(this); diff --git a/node_modules/fraction.js/fraction.d.ts b/node_modules/fraction.js/fraction.d.ts new file mode 100644 index 0000000..e62cfe1 --- /dev/null +++ b/node_modules/fraction.js/fraction.d.ts @@ -0,0 +1,60 @@ +declare module 'Fraction'; + +export interface NumeratorDenominator { + n: number; + d: number; +} + +type FractionConstructor = { + (fraction: Fraction): Fraction; + (num: number | string): Fraction; + (numerator: number, denominator: number): Fraction; + (numbers: [number | string, number | string]): Fraction; + (fraction: NumeratorDenominator): Fraction; + (firstValue: Fraction | number | string | [number | string, number | string] | NumeratorDenominator, secondValue?: number): Fraction; +}; + +export default class Fraction { + constructor (fraction: Fraction); + constructor (num: number | string); + constructor (numerator: number, denominator: number); + constructor (numbers: [number | string, number | string]); + constructor (fraction: NumeratorDenominator); + constructor (firstValue: Fraction | number | string | [number | string, number | string] | NumeratorDenominator, secondValue?: number); + + s: number; + n: number; + d: number; + + abs(): Fraction; + neg(): Fraction; + + add: FractionConstructor; + sub: FractionConstructor; + mul: FractionConstructor; + div: FractionConstructor; + pow: FractionConstructor; + gcd: FractionConstructor; + lcm: FractionConstructor; + + mod(n?: number | string | Fraction): Fraction; + + ceil(places?: number): Fraction; + floor(places?: number): Fraction; + round(places?: number): Fraction; + + inverse(): Fraction; + + simplify(eps?: number): Fraction; + + equals(n: number | string | Fraction): boolean; + compare(n: number | string | Fraction): number; + divisible(n: number | string | Fraction): boolean; + + valueOf(): number; + toString(decimalPlaces?: number): string; + toLatex(excludeWhole?: boolean): string; + toFraction(excludeWhole?: boolean): string; + toContinued(): number[]; + clone(): Fraction; +} diff --git a/node_modules/fraction.js/fraction.js b/node_modules/fraction.js/fraction.js new file mode 100644 index 0000000..82d05d2 --- /dev/null +++ b/node_modules/fraction.js/fraction.js @@ -0,0 +1,891 @@ +/** + * @license Fraction.js v4.2.0 05/03/2022 + * https://www.xarg.org/2014/03/rational-numbers-in-javascript/ + * + * Copyright (c) 2021, Robert Eisele (robert@xarg.org) + * Dual licensed under the MIT or GPL Version 2 licenses. + **/ + + +/** + * + * This class offers the possibility to calculate fractions. + * You can pass a fraction in different formats. Either as array, as double, as string or as an integer. + * + * Array/Object form + * [ 0 => , 1 => ] + * [ n => , d => ] + * + * Integer form + * - Single integer value + * + * Double form + * - Single double value + * + * String form + * 123.456 - a simple double + * 123/456 - a string fraction + * 123.'456' - a double with repeating decimal places + * 123.(456) - synonym + * 123.45'6' - a double with repeating last place + * 123.45(6) - synonym + * + * Example: + * + * var f = new Fraction("9.4'31'"); + * f.mul([-4, 3]).div(4.9); + * + */ + +(function(root) { + + "use strict"; + + // Maximum search depth for cyclic rational numbers. 2000 should be more than enough. + // Example: 1/7 = 0.(142857) has 6 repeating decimal places. + // If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits + var MAX_CYCLE_LEN = 2000; + + // Parsed data to avoid calling "new" all the time + var P = { + "s": 1, + "n": 0, + "d": 1 + }; + + function assign(n, s) { + + if (isNaN(n = parseInt(n, 10))) { + throw Fraction['InvalidParameter']; + } + return n * s; + } + + // Creates a new Fraction internally without the need of the bulky constructor + function newFraction(n, d) { + + if (d === 0) { + throw Fraction['DivisionByZero']; + } + + var f = Object.create(Fraction.prototype); + f["s"] = n < 0 ? -1 : 1; + + n = n < 0 ? -n : n; + + var a = gcd(n, d); + + f["n"] = n / a; + f["d"] = d / a; + return f; + } + + function factorize(num) { + + var factors = {}; + + var n = num; + var i = 2; + var s = 4; + + while (s <= n) { + + while (n % i === 0) { + n/= i; + factors[i] = (factors[i] || 0) + 1; + } + s+= 1 + 2 * i++; + } + + if (n !== num) { + if (n > 1) + factors[n] = (factors[n] || 0) + 1; + } else { + factors[num] = (factors[num] || 0) + 1; + } + return factors; + } + + var parse = function(p1, p2) { + + var n = 0, d = 1, s = 1; + var v = 0, w = 0, x = 0, y = 1, z = 1; + + var A = 0, B = 1; + var C = 1, D = 1; + + var N = 10000000; + var M; + + if (p1 === undefined || p1 === null) { + /* void */ + } else if (p2 !== undefined) { + n = p1; + d = p2; + s = n * d; + + if (n % 1 !== 0 || d % 1 !== 0) { + throw Fraction['NonIntegerParameter']; + } + + } else + switch (typeof p1) { + + case "object": + { + if ("d" in p1 && "n" in p1) { + n = p1["n"]; + d = p1["d"]; + if ("s" in p1) + n*= p1["s"]; + } else if (0 in p1) { + n = p1[0]; + if (1 in p1) + d = p1[1]; + } else { + throw Fraction['InvalidParameter']; + } + s = n * d; + break; + } + case "number": + { + if (p1 < 0) { + s = p1; + p1 = -p1; + } + + if (p1 % 1 === 0) { + n = p1; + } else if (p1 > 0) { // check for != 0, scale would become NaN (log(0)), which converges really slow + + if (p1 >= 1) { + z = Math.pow(10, Math.floor(1 + Math.log(p1) / Math.LN10)); + p1/= z; + } + + // Using Farey Sequences + // http://www.johndcook.com/blog/2010/10/20/best-rational-approximation/ + + while (B <= N && D <= N) { + M = (A + C) / (B + D); + + if (p1 === M) { + if (B + D <= N) { + n = A + C; + d = B + D; + } else if (D > B) { + n = C; + d = D; + } else { + n = A; + d = B; + } + break; + + } else { + + if (p1 > M) { + A+= C; + B+= D; + } else { + C+= A; + D+= B; + } + + if (B > N) { + n = C; + d = D; + } else { + n = A; + d = B; + } + } + } + n*= z; + } else if (isNaN(p1) || isNaN(p2)) { + d = n = NaN; + } + break; + } + case "string": + { + B = p1.match(/\d+|./g); + + if (B === null) + throw Fraction['InvalidParameter']; + + if (B[A] === '-') {// Check for minus sign at the beginning + s = -1; + A++; + } else if (B[A] === '+') {// Check for plus sign at the beginning + A++; + } + + if (B.length === A + 1) { // Check if it's just a simple number "1234" + w = assign(B[A++], s); + } else if (B[A + 1] === '.' || B[A] === '.') { // Check if it's a decimal number + + if (B[A] !== '.') { // Handle 0.5 and .5 + v = assign(B[A++], s); + } + A++; + + // Check for decimal places + if (A + 1 === B.length || B[A + 1] === '(' && B[A + 3] === ')' || B[A + 1] === "'" && B[A + 3] === "'") { + w = assign(B[A], s); + y = Math.pow(10, B[A].length); + A++; + } + + // Check for repeating places + if (B[A] === '(' && B[A + 2] === ')' || B[A] === "'" && B[A + 2] === "'") { + x = assign(B[A + 1], s); + z = Math.pow(10, B[A + 1].length) - 1; + A+= 3; + } + + } else if (B[A + 1] === '/' || B[A + 1] === ':') { // Check for a simple fraction "123/456" or "123:456" + w = assign(B[A], s); + y = assign(B[A + 2], 1); + A+= 3; + } else if (B[A + 3] === '/' && B[A + 1] === ' ') { // Check for a complex fraction "123 1/2" + v = assign(B[A], s); + w = assign(B[A + 2], s); + y = assign(B[A + 4], 1); + A+= 5; + } + + if (B.length <= A) { // Check for more tokens on the stack + d = y * z; + s = /* void */ + n = x + d * v + z * w; + break; + } + + /* Fall through on error */ + } + default: + throw Fraction['InvalidParameter']; + } + + if (d === 0) { + throw Fraction['DivisionByZero']; + } + + P["s"] = s < 0 ? -1 : 1; + P["n"] = Math.abs(n); + P["d"] = Math.abs(d); + }; + + function modpow(b, e, m) { + + var r = 1; + for (; e > 0; b = (b * b) % m, e >>= 1) { + + if (e & 1) { + r = (r * b) % m; + } + } + return r; + } + + + function cycleLen(n, d) { + + for (; d % 2 === 0; + d/= 2) { + } + + for (; d % 5 === 0; + d/= 5) { + } + + if (d === 1) // Catch non-cyclic numbers + return 0; + + // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem: + // 10^(d-1) % d == 1 + // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone, + // as we want to translate the numbers to strings. + + var rem = 10 % d; + var t = 1; + + for (; rem !== 1; t++) { + rem = rem * 10 % d; + + if (t > MAX_CYCLE_LEN) + return 0; // Returning 0 here means that we don't print it as a cyclic number. It's likely that the answer is `d-1` + } + return t; + } + + + function cycleStart(n, d, len) { + + var rem1 = 1; + var rem2 = modpow(10, len, d); + + for (var t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE) + // Solve 10^s == 10^(s+t) (mod d) + + if (rem1 === rem2) + return t; + + rem1 = rem1 * 10 % d; + rem2 = rem2 * 10 % d; + } + return 0; + } + + function gcd(a, b) { + + if (!a) + return b; + if (!b) + return a; + + while (1) { + a%= b; + if (!a) + return b; + b%= a; + if (!b) + return a; + } + }; + + /** + * Module constructor + * + * @constructor + * @param {number|Fraction=} a + * @param {number=} b + */ + function Fraction(a, b) { + + parse(a, b); + + if (this instanceof Fraction) { + a = gcd(P["d"], P["n"]); // Abuse variable a + this["s"] = P["s"]; + this["n"] = P["n"] / a; + this["d"] = P["d"] / a; + } else { + return newFraction(P['s'] * P['n'], P['d']); + } + } + + Fraction['DivisionByZero'] = new Error("Division by Zero"); + Fraction['InvalidParameter'] = new Error("Invalid argument"); + Fraction['NonIntegerParameter'] = new Error("Parameters must be integer"); + + Fraction.prototype = { + + "s": 1, + "n": 0, + "d": 1, + + /** + * Calculates the absolute value + * + * Ex: new Fraction(-4).abs() => 4 + **/ + "abs": function() { + + return newFraction(this["n"], this["d"]); + }, + + /** + * Inverts the sign of the current fraction + * + * Ex: new Fraction(-4).neg() => 4 + **/ + "neg": function() { + + return newFraction(-this["s"] * this["n"], this["d"]); + }, + + /** + * Adds two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => 467 / 30 + **/ + "add": function(a, b) { + + parse(a, b); + return newFraction( + this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Subtracts two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => -427 / 30 + **/ + "sub": function(a, b) { + + parse(a, b); + return newFraction( + this["s"] * this["n"] * P["d"] - P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Multiplies two rational numbers + * + * Ex: new Fraction("-17.(345)").mul(3) => 5776 / 111 + **/ + "mul": function(a, b) { + + parse(a, b); + return newFraction( + this["s"] * P["s"] * this["n"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Divides two rational numbers + * + * Ex: new Fraction("-17.(345)").inverse().div(3) + **/ + "div": function(a, b) { + + parse(a, b); + return newFraction( + this["s"] * P["s"] * this["n"] * P["d"], + this["d"] * P["n"] + ); + }, + + /** + * Clones the actual object + * + * Ex: new Fraction("-17.(345)").clone() + **/ + "clone": function() { + return newFraction(this['s'] * this['n'], this['d']); + }, + + /** + * Calculates the modulo of two rational numbers - a more precise fmod + * + * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6) + **/ + "mod": function(a, b) { + + if (isNaN(this['n']) || isNaN(this['d'])) { + return new Fraction(NaN); + } + + if (a === undefined) { + return newFraction(this["s"] * this["n"] % this["d"], 1); + } + + parse(a, b); + if (0 === P["n"] && 0 === this["d"]) { + throw Fraction['DivisionByZero']; + } + + /* + * First silly attempt, kinda slow + * + return that["sub"]({ + "n": num["n"] * Math.floor((this.n / this.d) / (num.n / num.d)), + "d": num["d"], + "s": this["s"] + });*/ + + /* + * New attempt: a1 / b1 = a2 / b2 * q + r + * => b2 * a1 = a2 * b1 * q + b1 * b2 * r + * => (b2 * a1 % a2 * b1) / (b1 * b2) + */ + return newFraction( + this["s"] * (P["d"] * this["n"]) % (P["n"] * this["d"]), + P["d"] * this["d"] + ); + }, + + /** + * Calculates the fractional gcd of two rational numbers + * + * Ex: new Fraction(5,8).gcd(3,7) => 1/56 + */ + "gcd": function(a, b) { + + parse(a, b); + + // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d) + + return newFraction(gcd(P["n"], this["n"]) * gcd(P["d"], this["d"]), P["d"] * this["d"]); + }, + + /** + * Calculates the fractional lcm of two rational numbers + * + * Ex: new Fraction(5,8).lcm(3,7) => 15 + */ + "lcm": function(a, b) { + + parse(a, b); + + // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d) + + if (P["n"] === 0 && this["n"] === 0) { + return newFraction(0, 1); + } + return newFraction(P["n"] * this["n"], gcd(P["n"], this["n"]) * gcd(P["d"], this["d"])); + }, + + /** + * Calculates the ceil of a rational number + * + * Ex: new Fraction('4.(3)').ceil() => (5 / 1) + **/ + "ceil": function(places) { + + places = Math.pow(10, places || 0); + + if (isNaN(this["n"]) || isNaN(this["d"])) { + return new Fraction(NaN); + } + return newFraction(Math.ceil(places * this["s"] * this["n"] / this["d"]), places); + }, + + /** + * Calculates the floor of a rational number + * + * Ex: new Fraction('4.(3)').floor() => (4 / 1) + **/ + "floor": function(places) { + + places = Math.pow(10, places || 0); + + if (isNaN(this["n"]) || isNaN(this["d"])) { + return new Fraction(NaN); + } + return newFraction(Math.floor(places * this["s"] * this["n"] / this["d"]), places); + }, + + /** + * Rounds a rational numbers + * + * Ex: new Fraction('4.(3)').round() => (4 / 1) + **/ + "round": function(places) { + + places = Math.pow(10, places || 0); + + if (isNaN(this["n"]) || isNaN(this["d"])) { + return new Fraction(NaN); + } + return newFraction(Math.round(places * this["s"] * this["n"] / this["d"]), places); + }, + + /** + * Gets the inverse of the fraction, means numerator and denominator are exchanged + * + * Ex: new Fraction([-3, 4]).inverse() => -4 / 3 + **/ + "inverse": function() { + + return newFraction(this["s"] * this["d"], this["n"]); + }, + + /** + * Calculates the fraction to some rational exponent, if possible + * + * Ex: new Fraction(-1,2).pow(-3) => -8 + */ + "pow": function(a, b) { + + parse(a, b); + + // Trivial case when exp is an integer + + if (P['d'] === 1) { + + if (P['s'] < 0) { + return newFraction(Math.pow(this['s'] * this["d"], P['n']), Math.pow(this["n"], P['n'])); + } else { + return newFraction(Math.pow(this['s'] * this["n"], P['n']), Math.pow(this["d"], P['n'])); + } + } + + // Negative roots become complex + // (-a/b)^(c/d) = x + // <=> (-1)^(c/d) * (a/b)^(c/d) = x + // <=> (cos(pi) + i*sin(pi))^(c/d) * (a/b)^(c/d) = x # rotate 1 by 180° + // <=> (cos(c*pi/d) + i*sin(c*pi/d)) * (a/b)^(c/d) = x # DeMoivre's formula in Q ( https://proofwiki.org/wiki/De_Moivre%27s_Formula/Rational_Index ) + // From which follows that only for c=0 the root is non-complex. c/d is a reduced fraction, so that sin(c/dpi)=0 occurs for d=1, which is handled by our trivial case. + if (this['s'] < 0) return null; + + // Now prime factor n and d + var N = factorize(this['n']); + var D = factorize(this['d']); + + // Exponentiate and take root for n and d individually + var n = 1; + var d = 1; + for (var k in N) { + if (k === '1') continue; + if (k === '0') { + n = 0; + break; + } + N[k]*= P['n']; + + if (N[k] % P['d'] === 0) { + N[k]/= P['d']; + } else return null; + n*= Math.pow(k, N[k]); + } + + for (var k in D) { + if (k === '1') continue; + D[k]*= P['n']; + + if (D[k] % P['d'] === 0) { + D[k]/= P['d']; + } else return null; + d*= Math.pow(k, D[k]); + } + + if (P['s'] < 0) { + return newFraction(d, n); + } + return newFraction(n, d); + }, + + /** + * Check if two rational numbers are the same + * + * Ex: new Fraction(19.6).equals([98, 5]); + **/ + "equals": function(a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] === P["s"] * P["n"] * this["d"]; // Same as compare() === 0 + }, + + /** + * Check if two rational numbers are the same + * + * Ex: new Fraction(19.6).equals([98, 5]); + **/ + "compare": function(a, b) { + + parse(a, b); + var t = (this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]); + return (0 < t) - (t < 0); + }, + + "simplify": function(eps) { + + if (isNaN(this['n']) || isNaN(this['d'])) { + return this; + } + + eps = eps || 0.001; + + var thisABS = this['abs'](); + var cont = thisABS['toContinued'](); + + for (var i = 1; i < cont.length; i++) { + + var s = newFraction(cont[i - 1], 1); + for (var k = i - 2; k >= 0; k--) { + s = s['inverse']()['add'](cont[k]); + } + + if (s['sub'](thisABS)['abs']().valueOf() < eps) { + return s['mul'](this['s']); + } + } + return this; + }, + + /** + * Check if two rational numbers are divisible + * + * Ex: new Fraction(19.6).divisible(1.5); + */ + "divisible": function(a, b) { + + parse(a, b); + return !(!(P["n"] * this["d"]) || ((this["n"] * P["d"]) % (P["n"] * this["d"]))); + }, + + /** + * Returns a decimal representation of the fraction + * + * Ex: new Fraction("100.'91823'").valueOf() => 100.91823918239183 + **/ + 'valueOf': function() { + + return this["s"] * this["n"] / this["d"]; + }, + + /** + * Returns a string-fraction representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toFraction(true) => "4 1/3" + **/ + 'toFraction': function(excludeWhole) { + + var whole, str = ""; + var n = this["n"]; + var d = this["d"]; + if (this["s"] < 0) { + str+= '-'; + } + + if (d === 1) { + str+= n; + } else { + + if (excludeWhole && (whole = Math.floor(n / d)) > 0) { + str+= whole; + str+= " "; + n%= d; + } + + str+= n; + str+= '/'; + str+= d; + } + return str; + }, + + /** + * Returns a latex representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toLatex() => "\frac{4}{3}" + **/ + 'toLatex': function(excludeWhole) { + + var whole, str = ""; + var n = this["n"]; + var d = this["d"]; + if (this["s"] < 0) { + str+= '-'; + } + + if (d === 1) { + str+= n; + } else { + + if (excludeWhole && (whole = Math.floor(n / d)) > 0) { + str+= whole; + n%= d; + } + + str+= "\\frac{"; + str+= n; + str+= '}{'; + str+= d; + str+= '}'; + } + return str; + }, + + /** + * Returns an array of continued fraction elements + * + * Ex: new Fraction("7/8").toContinued() => [0,1,7] + */ + 'toContinued': function() { + + var t; + var a = this['n']; + var b = this['d']; + var res = []; + + if (isNaN(a) || isNaN(b)) { + return res; + } + + do { + res.push(Math.floor(a / b)); + t = a % b; + a = b; + b = t; + } while (a !== 1); + + return res; + }, + + /** + * Creates a string representation of a fraction with all digits + * + * Ex: new Fraction("100.'91823'").toString() => "100.(91823)" + **/ + 'toString': function(dec) { + + var N = this["n"]; + var D = this["d"]; + + if (isNaN(N) || isNaN(D)) { + return "NaN"; + } + + dec = dec || 15; // 15 = decimal places when no repetation + + var cycLen = cycleLen(N, D); // Cycle length + var cycOff = cycleStart(N, D, cycLen); // Cycle start + + var str = this['s'] < 0 ? "-" : ""; + + str+= N / D | 0; + + N%= D; + N*= 10; + + if (N) + str+= "."; + + if (cycLen) { + + for (var i = cycOff; i--;) { + str+= N / D | 0; + N%= D; + N*= 10; + } + str+= "("; + for (var i = cycLen; i--;) { + str+= N / D | 0; + N%= D; + N*= 10; + } + str+= ")"; + } else { + for (var i = dec; N && i--;) { + str+= N / D | 0; + N%= D; + N*= 10; + } + } + return str; + } + }; + + if (typeof define === "function" && define["amd"]) { + define([], function() { + return Fraction; + }); + } else if (typeof exports === "object") { + Object.defineProperty(Fraction, "__esModule", { 'value': true }); + Fraction['default'] = Fraction; + Fraction['Fraction'] = Fraction; + module['exports'] = Fraction; + } else { + root['Fraction'] = Fraction; + } + +})(this); diff --git a/node_modules/fraction.js/fraction.min.js b/node_modules/fraction.js/fraction.min.js new file mode 100644 index 0000000..f0cc9d5 --- /dev/null +++ b/node_modules/fraction.js/fraction.min.js @@ -0,0 +1,19 @@ +/* +Fraction.js v4.2.0 05/03/2022 +https://www.xarg.org/2014/03/rational-numbers-in-javascript/ + +Copyright (c) 2021, Robert Eisele (robert@xarg.org) +Dual licensed under the MIT or GPL Version 2 licenses. +*/ +(function(z){function p(a,c){var b=0,d=1,f=1,l=0,k=0,t=0,x=1,u=1,g=0,h=1,v=1,q=1;if(void 0!==a&&null!==a)if(void 0!==c){if(b=a,d=c,f=b*d,0!==b%1||0!==d%1)throw m.NonIntegerParameter;}else switch(typeof a){case "object":if("d"in a&&"n"in a)b=a.n,d=a.d,"s"in a&&(b*=a.s);else if(0 in a)b=a[0],1 in a&&(d=a[1]);else throw m.InvalidParameter;f=b*d;break;case "number":0>a&&(f=a,a=-a);if(0===a%1)b=a;else if(0=h&&1E7>=q;)if(b=(g+ +v)/(h+q),a===b){1E7>=h+q?(b=g+v,d=h+q):q>h?(b=v,d=q):(b=g,d=h);break}else a>b?(g+=v,h+=q):(v+=g,q+=h),1E7f?-1:1;e.n=Math.abs(b);e.d=Math.abs(d)}function r(a,c){if(isNaN(a=parseInt(a,10)))throw m.InvalidParameter;return a*c}function n(a,c){if(0===c)throw m.DivisionByZero; +var b=Object.create(m.prototype);b.s=0>a?-1:1;a=0>a?-a:a;var d=w(a,c);b.n=a/d;b.d=c/d;return b}function y(a){for(var c={},b=a,d=2,f=4;f<=b;){for(;0===b%d;)b/=d,c[d]=(c[d]||0)+1;f+=1+2*d++}b!==a?1e.s?n(Math.pow(this.s*this.d,e.n),Math.pow(this.n,e.n)):n(Math.pow(this.s*this.n,e.n),Math.pow(this.d, +e.n));if(0>this.s)return null;var b=y(this.n),d=y(this.d),f=1,l=1,k;for(k in b)if("1"!==k){if("0"===k){f=0;break}b[k]*=e.n;if(0===b[k]%e.d)b[k]/=e.d;else return null;f*=Math.pow(k,b[k])}for(k in d)if("1"!==k){d[k]*=e.n;if(0===d[k]%e.d)d[k]/=e.d;else return null;l*=Math.pow(k,d[k])}return 0>e.s?n(l,f):n(f,l)},equals:function(a,c){p(a,c);return this.s*this.n*e.d===e.s*e.n*this.d},compare:function(a,c){p(a,c);var b=this.s*this.n*e.d-e.s*e.n*this.d;return(0b)},simplify:function(a){if(isNaN(this.n)|| +isNaN(this.d))return this;a=a||.001;for(var c=this.abs(),b=c.toContinued(),d=1;dthis.s&&(b+="-");1===f?b+=d:(a&&0<(c=Math.floor(d/f))&&(b=b+c+" ",d%=f),b=b+d+"/",b+=f);return b},toLatex:function(a){var c, +b="",d=this.n,f=this.d;0>this.s&&(b+="-");1===f?b+=d:(a&&0<(c=Math.floor(d/f))&&(b+=c,d%=f),b=b+"\\frac{"+d+"}{"+f,b+="}");return b},toContinued:function(){var a=this.n,c=this.d,b=[];if(isNaN(a)||isNaN(c))return b;do{b.push(Math.floor(a/c));var d=a%c;a=c;c=d}while(1!==a);return b},toString:function(a){var c=this.n,b=this.d;if(isNaN(c)||isNaN(b))return"NaN";var d;a:{for(d=b;0===d%2;d/=2);for(;0===d%5;d/=5);if(1===d)d=0;else{for(var f=10%d,l=1;1!==f;l++)if(f=10*f%d,2E3>=1)k&1&&(t=t*l%b);l=t;for(k=0;300>k;k++){if(f===l){l=k;break a}f=10*f%b;l=10*l%b}l=0}f=0>this.s?"-":"";f+=c/b|0;(c=c%b*10)&&(f+=".");if(d){for(a=l;a--;)f+=c/b|0,c%=b,c*=10;f+="(";for(a=d;a--;)f+=c/b|0,c%=b,c*=10;f+=")"}else for(a=a||15;c&&a--;)f+=c/b|0,c%=b,c*=10;return f}};"function"===typeof define&&define.amd?define([],function(){return m}):"object"===typeof exports?(Object.defineProperty(m,"__esModule",{value:!0}),m["default"]=m,m.Fraction=m,module.exports=m): +z.Fraction=m})(this); \ No newline at end of file diff --git a/node_modules/fraction.js/package.json b/node_modules/fraction.js/package.json new file mode 100644 index 0000000..9be0262 --- /dev/null +++ b/node_modules/fraction.js/package.json @@ -0,0 +1,43 @@ +{ + "name": "fraction.js", + "title": "fraction.js", + "version": "4.2.0", + "homepage": "https://www.xarg.org/2014/03/rational-numbers-in-javascript/", + "bugs": "https://github.com/infusion/Fraction.js/issues", + "description": "A rational number library", + "keywords": [ + "math", + "fraction", + "rational", + "rationals", + "number", + "parser", + "rational numbers" + ], + "author": "Robert Eisele (http://www.xarg.org/)", + "main": "fraction", + "types": "./fraction.d.ts", + "private": false, + "readmeFilename": "README.md", + "directories": { + "example": "examples" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/infusion/Fraction.js.git" + }, + "funding": { + "type": "patreon", + "url": "https://www.patreon.com/infusion" + }, + "engines": { + "node": "*" + }, + "scripts": { + "test": "mocha tests/*.js" + }, + "devDependencies": { + "mocha": "*" + } +} diff --git a/node_modules/javascript-natural-sort/.gitattributes b/node_modules/javascript-natural-sort/.gitattributes new file mode 100644 index 0000000..412eeda --- /dev/null +++ b/node_modules/javascript-natural-sort/.gitattributes @@ -0,0 +1,22 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp +*.sln merge=union +*.csproj merge=union +*.vbproj merge=union +*.fsproj merge=union +*.dbproj merge=union + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/node_modules/javascript-natural-sort/.idea/.name b/node_modules/javascript-natural-sort/.idea/.name new file mode 100644 index 0000000..f9bd021 --- /dev/null +++ b/node_modules/javascript-natural-sort/.idea/.name @@ -0,0 +1 @@ +javascript-natural-sort \ No newline at end of file diff --git a/node_modules/javascript-natural-sort/.idea/encodings.xml b/node_modules/javascript-natural-sort/.idea/encodings.xml new file mode 100644 index 0000000..e206d70 --- /dev/null +++ b/node_modules/javascript-natural-sort/.idea/encodings.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/node_modules/javascript-natural-sort/.idea/javascript-natural-sort.iml b/node_modules/javascript-natural-sort/.idea/javascript-natural-sort.iml new file mode 100644 index 0000000..6b8184f --- /dev/null +++ b/node_modules/javascript-natural-sort/.idea/javascript-natural-sort.iml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/node_modules/javascript-natural-sort/.idea/misc.xml b/node_modules/javascript-natural-sort/.idea/misc.xml new file mode 100644 index 0000000..1162f43 --- /dev/null +++ b/node_modules/javascript-natural-sort/.idea/misc.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/node_modules/javascript-natural-sort/.idea/modules.xml b/node_modules/javascript-natural-sort/.idea/modules.xml new file mode 100644 index 0000000..63a98c1 --- /dev/null +++ b/node_modules/javascript-natural-sort/.idea/modules.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/node_modules/javascript-natural-sort/.idea/scopes/scope_settings.xml b/node_modules/javascript-natural-sort/.idea/scopes/scope_settings.xml new file mode 100644 index 0000000..922003b --- /dev/null +++ b/node_modules/javascript-natural-sort/.idea/scopes/scope_settings.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/node_modules/javascript-natural-sort/.idea/vcs.xml b/node_modules/javascript-natural-sort/.idea/vcs.xml new file mode 100644 index 0000000..c80f219 --- /dev/null +++ b/node_modules/javascript-natural-sort/.idea/vcs.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/node_modules/javascript-natural-sort/.idea/workspace.xml b/node_modules/javascript-natural-sort/.idea/workspace.xml new file mode 100644 index 0000000..e229274 --- /dev/null +++ b/node_modules/javascript-natural-sort/.idea/workspace.xml @@ -0,0 +1,318 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1388535088299 + 1388535088299 + + + 1388535399296 + 1388535399296 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/node_modules/javascript-natural-sort/.npmignore b/node_modules/javascript-natural-sort/.npmignore new file mode 100644 index 0000000..5ebd21a --- /dev/null +++ b/node_modules/javascript-natural-sort/.npmignore @@ -0,0 +1,163 @@ +################# +## Eclipse +################# + +*.pydevproject +.project +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + + +################# +## Visual Studio +################# + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results +[Dd]ebug/ +[Rr]elease/ +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.vspscc +.builds +*.dotCover + +## TODO: If you have NuGet Package Restore enabled, uncomment this +#packages/ + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf + +# Visual Studio profiler +*.psess +*.vsp + +# ReSharper is a .NET coding add-in +_ReSharper* + +# Installshield output folder +[Ee]xpress + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish + +# Others +[Bb]in +[Oo]bj +sql +TestResults +*.Cache +ClientBin +stylecop.* +~$* +*.dbmdl +Generated_Code #added for RIA/Silverlight projects + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML + + + +############ +## Windows +############ + +# Windows image file caches +Thumbs.db + +# Folder config file +Desktop.ini + + +############# +## Python +############# + +*.py[co] + +# Packages +*.egg +*.egg-info +dist +build +eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox + +#Translations +*.mo + +#Mr Developer +.mr.developer.cfg + +# Mac crap +.DS_Store diff --git a/node_modules/javascript-natural-sort/README.md b/node_modules/javascript-natural-sort/README.md new file mode 100644 index 0000000..8270bd1 --- /dev/null +++ b/node_modules/javascript-natural-sort/README.md @@ -0,0 +1,76 @@ +### Simple numerics + +```javascript +>>> ['10',9,2,'1','4'].sort(naturalSort) +['1',2,'4',9,'10'] +``` + +### Floats + +```javascript +>>> ['10.0401',10.022,10.042,'10.021999'].sort(naturalSort) +['10.021999',10.022,'10.0401',10.042] +``` + +### Float & decimal notation + +```javascript +>>> ['10.04f','10.039F','10.038d','10.037D'].sort(naturalSort) +['10.037D','10.038d','10.039F','10.04f'] +``` + +### Scientific notation + +```javascript +>>> ['1.528535047e5','1.528535047e7','1.528535047e3'].sort(naturalSort) +['1.528535047e3','1.528535047e5','1.528535047e7'] +``` + +### IP addresses + +```javascript +>>> ['192.168.0.100','192.168.0.1','192.168.1.1'].sort(naturalSort) +['192.168.0.1','192.168.0.100','192.168.1.1'] +``` + +### Filenames + +```javascript +>>> ['car.mov','01alpha.sgi','001alpha.sgi','my.string_41299.tif'].sort(naturalSort) +['001alpha.sgi','01alpha.sgi','car.mov','my.string_41299.tif' +``` + +### Dates + +```javascript +>>> ['10/12/2008','10/11/2008','10/11/2007','10/12/2007'].sort(naturalSort) +['10/11/2007', '10/12/2007', '10/11/2008', '10/12/2008'] +``` + +### Money + +```javascript +>>> ['$10002.00','$10001.02','$10001.01'].sort(naturalSort) +['$10001.01','$10001.02','$10002.00'] +``` + +### Movie Titles + +```javascript +>>> ['1 Title - The Big Lebowski','1 Title - Gattaca','1 Title - Last Picture Show'].sort(naturalSort) +['1 Title - Gattaca','1 Title - Last Picture Show','1 Title - The Big Lebowski'] +``` + +### By default - case-sensitive sorting + +```javascript +>>> ['a', 'B'].sort(naturalSort); +['B', 'a'] +``` + +### To enable case-insensitive sorting +```javascript +>>> naturalSort.insensitive = true; +>>> ['a', 'B'].sort(naturalSort); +['a', 'B'] +``` diff --git a/node_modules/javascript-natural-sort/index.html b/node_modules/javascript-natural-sort/index.html new file mode 100644 index 0000000..9c0bf7e --- /dev/null +++ b/node_modules/javascript-natural-sort/index.html @@ -0,0 +1,100 @@ + + + + + + overset/javascript-natural-sort @ GitHub + + + + + + Fork me on GitHub + +
+ +
+ + + + +
+ +

javascript-natural-sort + by overset

+ +
+ A fast and lightweight function to be used in conjunction with the Array.sort() using the browser's default bubble sort. This will properly sort padded numbers, numbers preceding text, dates, floats, etc. +
+ + + + + + + + +

License

+

MIT

+ + + +

Authors

+

Jim Palmer (jimpalmer@gmail.com)

+ + + +

Contact

+

Jim Palmer (jimpalmer@gmail.com)

+ + +

Download

+

+ You can download this project in either + zip or + tar formats. +

+

You can also clone the project with Git + by running: +

$ git clone git://github.com/overset/javascript-natural-sort
+

+ + + +
+ + +" + + diff --git a/node_modules/javascript-natural-sort/naturalSort.js b/node_modules/javascript-natural-sort/naturalSort.js new file mode 100644 index 0000000..28dd64d --- /dev/null +++ b/node_modules/javascript-natural-sort/naturalSort.js @@ -0,0 +1,45 @@ +/* + * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license + * Author: Jim Palmer (based on chunking idea from Dave Koelle) + */ +/*jshint unused:false */ +module.exports = function naturalSort (a, b) { + "use strict"; + var re = /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, + sre = /(^[ ]*|[ ]*$)/g, + dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, + hre = /^0x[0-9a-f]+$/i, + ore = /^0/, + i = function(s) { return naturalSort.insensitive && ('' + s).toLowerCase() || '' + s; }, + // convert all to strings strip whitespace + x = i(a).replace(sre, '') || '', + y = i(b).replace(sre, '') || '', + // chunk/tokenize + xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), + yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), + // numeric, hex or date detection + xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && x.match(dre) && Date.parse(x)), + yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null, + oFxNcL, oFyNcL; + // first try and sort Hex codes or Dates + if (yD) { + if ( xD < yD ) { return -1; } + else if ( xD > yD ) { return 1; } + } + // natural sorting through split numeric strings and default strings + for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) { + // find floats not starting with '0', string or 0 if not defined (Clint Priest) + oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0; + oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0; + // handle numeric vs string comparison - number < string - (Kyle Adams) + if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; } + // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' + else if (typeof oFxNcL !== typeof oFyNcL) { + oFxNcL += ''; + oFyNcL += ''; + } + if (oFxNcL < oFyNcL) { return -1; } + if (oFxNcL > oFyNcL) { return 1; } + } + return 0; +}; diff --git a/node_modules/javascript-natural-sort/package.json b/node_modules/javascript-natural-sort/package.json new file mode 100644 index 0000000..4b1bf07 --- /dev/null +++ b/node_modules/javascript-natural-sort/package.json @@ -0,0 +1,27 @@ +{ + "name": "javascript-natural-sort", + "version": "0.7.1", + "description": "Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license", + "main": "naturalSort.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://github.com/Bill4Time/javascript-natural-sort.git" + }, + "keywords": [ + "natural", + "sort", + "javascript", + "array", + "sort", + "sorting" + ], + "author": "Jim Palmer (based on chunking idea from Dave Koelle, packaged by @khous of Bill4Time)", + "license": "MIT", + "bugs": { + "url": "https://github.com/Bill4Time/javascript-natural-sort/issues" + }, + "homepage": "https://github.com/Bill4Time/javascript-natural-sort" +} diff --git a/node_modules/javascript-natural-sort/speed-tests.html b/node_modules/javascript-natural-sort/speed-tests.html new file mode 100644 index 0000000..090259b --- /dev/null +++ b/node_modules/javascript-natural-sort/speed-tests.html @@ -0,0 +1,105 @@ + + + + + + + + + + diff --git a/node_modules/javascript-natural-sort/unit-tests.html b/node_modules/javascript-natural-sort/unit-tests.html new file mode 100644 index 0000000..7b11540 --- /dev/null +++ b/node_modules/javascript-natural-sort/unit-tests.html @@ -0,0 +1,365 @@ + + + + js-naturalsort test suite + + + + + + + +

js-naturalsort test suite

+

+

+
    + + diff --git a/node_modules/mathjs/CONTRIBUTING.md b/node_modules/mathjs/CONTRIBUTING.md new file mode 100644 index 0000000..4478db6 --- /dev/null +++ b/node_modules/mathjs/CONTRIBUTING.md @@ -0,0 +1,23 @@ +## Contributing + +Contributions to the math.js library are very welcome! We can't do this alone. +You can contribute in different ways: spread the word, report bugs, come up with +ideas and suggestions, and contribute to the code. + +There are a few preferences regarding code contributions: + +- The code of math.js follows the JavaScript Standard Style as described on https://standardjs.com/. +- Make sure you properly unit test your changes. +- Before creating a pull request, run the unit tests to make sure they all pass. +- Only commit changes done in the source files under `src`, not to the generated builds + which are located in the folders `dist` and `lib`. +- Send pull requests to the `develop` branch, not the `master` branch. + +What can I do? + +- Search through the [issues](https://github.com/josdejong/mathjs/issues) looking + for something that looks interesting to you to pick up. Some issues are marked + ["help wanted"](https://github.com/josdejong/mathjs/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22), + these are typically issues which should be relatively easy to pick up. + +Thanks! diff --git a/node_modules/mathjs/HISTORY.md b/node_modules/mathjs/HISTORY.md new file mode 100644 index 0000000..9374900 --- /dev/null +++ b/node_modules/mathjs/HISTORY.md @@ -0,0 +1,2574 @@ +# History + + +# 2022-04-08, version 10.4.3 + +- Fix #2508: improve the precision of stirlingS2 (#2509). Thanks @gwhitney. +- Fix #2514: implement optional argument `base` in the number implementation + of function `log` (#2515). Thanks @gwhitney. +- Improve the documentation on operator `;` (#2512). Thanks @gwhitney. + + +# 2022-03-29, version 10.4.2 + +- Fix #2499: different behavior for unit conversion "degC" and "K" (#2501). + Also disables getting the sign for units with an offset, which is ambiguous. + Thanks @gwhitney. +- Fix #2503: fix an issue in `log()` for complex numbers in which the imaginary + part is much larger in absolute value than the real part, fixed in + `complex.js@2.1.0` (#2505), thanks @gwhitney, @infusion. +- Fix #2493: unclear error message when an entity that is not a function + is being called as a function (#2494). Thanks @gwhitney. +- Some fixes in the docs on units (#2498). Thanks @dvd101x. +- Add `forEach` example in embedded docs (#2507). Thanks @dvd101x. +- Correct approx.deepEqual() to accept an epsilon argument giving the + comparison tolerance. It was already being called this way, but was + silently ignoring the tolerance. Thanks @yifanwww. + + +# 2022-03-23, version 10.4.1 + +- Improve TypeScript definitions for function `unit` (#2479). + Thanks @SinanAkkoyun. +- Add tests for type declarations (#2448). Thanks @samestep. +- Further improvement to TypeScript definitions of `std` and `variance` + (make dimension parameter optional, #2474). Thanks @NattapongSiri. +- Next step (as per #2431) for full publication of "is" functions like + `isMatrix` etc: Provide TypeScript definitions of "is" functions and + make them type guards. (#2432). Thanks @ChristopherChudzicki. +- Fix #2491: Multi line object expressions don't work with comments (#2492). + Thanks @gwhitney. +- Fix #2478: a bug in calculating the eigenvectors when dealing with complex + numbers (#2496). Thanks @gwhitney. +- Update project dependencies and devDependencies. + + +# 2022-03-07, version 10.4.0 + +- Fix #2461: make sure `simplifyCore` recurses over all binary nodes (#2462). + Thanks @gwhitney. +- Fix #2429: fix the TypeScript definitions of functions `std` and `variance` + (#2455). Thanks @NattapongSiri. +- Fix #1633: implement a `cumsum` function generating cumulative sums of a list + of values or a matrix. (#1870). Thanks @hjonasson. +- Upgrade to the latest version of `Fraction.js`, having more strict input, + only accepting an integer numerator and denominator. See #2427. +- Fix typo in documentation example for `format`. (#2468) Thanks @abranhe. +- Write unit tests for all jsdoc examples. See #2452. Thanks @gwhitney. + + +# 2021-03-02, version 10.3.0 + +- Fix #1260: implement function `symbolicEqual` (#2424). Thanks @gwhitney. +- Fix #2441, #2442: support passing a function as argument to functions created + in the expression parser (#2443). Thanks @gwhitney. +- Fix #2325: improve documentation of subset indices (#2446). Thanks @gwhitney. +- Fix #2439: fix a bug in `complexEigs` in which real-valued norms were + inadvertently being typed as complex numbers (#2445). Thanks @gwhitney. +- Fix #2436: improve documentation and error message of function `map` (#2457). + Thanks @gwhitney. + + +# 2022-03-01, version 10.2.0 + +- Implemented context options to control simplifications allowed in `simplify`, + see #2399, #2391. Thanks @gwhitney. +- Implemented function `leafCount` as a first simple measure of the complexity + of an expression, see #2411, #2389. Thanks @gwhitney. +- Fix #2413: improve `combinations` to return an integer result without rounding + errors for larger values, see #2414. Thanks @gwhitney. +- Fix #2385: function `rotate` missing in TypeScript definitions. + Thanks @DIVYA-19. +- Fix #2450: Add BigNumber to parameter type in `math.unit` and add TypeScript + types for `Unit.simplify` and `Unit.units` (#2353). Thanks @joshhansen. +- Fix #2383: detect infinite loops in `simplify` (#2405). Thanks @gwhitney. +- Fix #1423: collect like factors and cancel like terms in sums (#2388). + Thanks @gwhitney. + + +# 2022-02-02, version 10.1.1 + +- Improvements and fixes in function `simplify`, thanks @gwhitney: + - Fix #2393: regression bug in `simplify('2-(x+1)')`. + - Ad option `consoleDebug` to `simplify` to see what is going on. +- Fix TypeScript definition of `ConfigOptions`, which was missing option + `predictable`. + + +# 2022-01-15, version 10.1.0 + +- Implemented function `invmod`, see #2368, #1744. Thanks @thetazero. +- Improvements and fixes in function `simplify`, thanks @gwhitney: + - Fix #1179, #1290: improve collection of non-constant like terms (#2384). + - Fix #2152: do not transform strings into numbers (#2372). + - Fix #1913: implement support for array and object simplification (#2382). +- Fix #2379: add embedded documentation for function `print`. +- Remove broken example from the embedded documentation of function `forEach`. + + +# 2021-12-29, version 10.0.2 + +- Fix #2156: simplify expressions like `-1 / (-x)` to `1/x`. Thanks @ony3000. +- Fix #2363: remove a redundant part of the regex to split a number. +- Fix #2291: add support for fractions in function `intersect`. + Thanks @thetazero. +- Fix #2358: bug in `SparseMatrix` when replacing a subset of a matrix with + a non-consecutive index. Thanks @Al-0. + + +# 2021-12-22, version 10.0.1 + +- Fix #1681: function `gamma` giving inaccurate complex results in some cases. + Thanks @kmdrGroch. +- Fixed a typo in an example, see #2366. Thanks @blackwindforce. + + +# 2021-11-03, version 10.0.0 + +!!! BE CAREFUL: BREAKING CHANGES IN THE TYPESCRIPT DEFINITIONS !!! + +- Improvements to the Typescript typings (commit fc5c202e). + Thanks @joshhansen. First introduced in v9.5.1, but reverted because + it contains breaking changes. + + Breaking changes: interface `MathNode` is now renamed to `MathNodeCommon` + and the related interfaces are structured in a different way. + +- Fixed a typo in the TypeScript definition of toHTML. Thanks @TheToto. + + +# 2021-11-03, version 9.5.2` + +- Revert the improvements to the Typescript typings because they contain + breaking changes. The improvements will be published in v10.0.0. See #2339. + + +# 2021-10-13, version 9.5.1 + +- Various improvements to the Typescript typings. + Thanks @joshhansen and @DianaTdr. + + +# 2021-09-22, version 9.5.0 + +- Implemented support for calculations with percentage, see #2303. + Thanks @rvramesh. +- Fix #2319: make the API of `Parser.evaluate` consistent with `math.evaluate`: + support a list with expressions as input. +- Improved documentation of function `setCartesian`. Thanks @fieldfoxWim. + + +# 2021-09-15, version 9.4.5 + +- Improved the performance of `Node.equals` by improving the internal + function `deepStrictEqual`. Thanks @tomlarkworthy. +- Fixes in the TypeScript definitions: + - Define `hasNumericValue`. Thanks @write2kcl. + - Define `MathNode.isRelationalNode`. Thanks @m93a. + - Fix typo in `MathNode.isConditionalNode`. Thanks @m93a. + + +# 2021-07-07, version 9.4.4 + +- Fixed `ArrayNode.toTex()`: remove the row delimiter on the last row, + see #2267. Thanks @davidtranhq. +- Fix #2269: `intersect` not returning `null` for matrix input. Thanks @m93a. +- Fix #2245: mathjs not working in IE11 anymore due to a missing polyfill for + `Symbol`. The browser bundle now includes the necessary polyfills (it is + larger now because of that, see also #2266). Thanks @m93a. +- Update dependencies (`complex.js@2.0.15`, `decimal.js@10.3.1`) +- Drop official support for node.js 10, which has reached end of life. + See #2258. + + +# 2021-06-23, version 9.4.3 + +- Fix #2222: mathjs polluting the `Decimal` prototype. Thanks @m93a. +- Fix #2253: expression parser throwing an error when accessing nested object + properties named `e`. +- Fixes in the TypeScript definitions: + - function `floor`, #2159, #2246. Thanks @write2kcl. + - function `simplify`, see #2252. Thanks @nitroin. +- Upgraded to `decimal.js@10.3.0` + + +# 2021-06-05, version 9.4.2 + +- Implemented iterative eigenvalue finder for `eigs`, making it much more + robust. See #2179, #2237. Thanks @m93a. +- Improved TypeScript definitions of function `parse`. Thanks @OpportunityLiu. + + +# 2021-05-24, version 9.4.1 + +- Fix #2100: add TypeScript declaration for `eigs`. Thanks @andrebianchessi. +- Fix #2220: add TypeScript files to published npm package. Thanks @dhritzkiv. +- Update readme regarding TypeScript definition files. Thanks @dhritzkiv. +- Update to `fraction.js@4.1.1` + + +# 2021-05-16, version 9.4.0 + +- Implemented support to use objects with a `Map` interface as scope, + see #2143, #2166. Thanks @jhugman. +- Extend `eigs` to support general complex matrices, see #1741. Thanks @m93a. +- DenseMatrix and SparseMatrix are now iterable, see #1184. Thanks @m93a. +- Implemented utility functions `matrixFromRows`, `matrixFromColumns`, and + `matrixFromFunction`, see #2155, #2153. Thanks @m93a. +- Added TypeScript definitions to the project, making it redundant to install + `@types/mathjs`, and making it easier to improve the definitions. See #2187, + #2192. Thanks @CatsMiaow. +- Upgraded dependencies + - `complex.js@2.0.13` (fixing #2211). Thanks @infusion + - `fraction.js@4.1.0` (`pow` now supporting rational exponents). +- Fix #2174: function `pickRandom` having no name. Thanks @HK-SHAO. +- Fix #2019: VSCode auto import keeps adding import { null } from 'mathjs'. +- Fix #2185: Fix TypeScript definition of unit division, which can also return + a number. +- Fix #2123: add type definitions for functions `row` and `column`. +- Fix some files not exposed in the package, see #2213. Thanks @javiermarinros. + + +# 2021-04-12, version 9.3.2 + +- Fix #2169: mathjs requesting `@babel/runtime` dependency. + Regression introduced in `v9.3.1`. + + +# 2021-04-10, version 9.3.1 + +- Fix #2133: strongly improved the performance of `isPrime`, see #2139. + Thanks @Yaffle. +- Fix #2150: give a clear error "Error: Undefined function ..." instead when + evaluating a non-existing function. +- Fix #660: expose internal functions `FunctionNode.onUndefinedFunction(name)` + and `SymbolNode.onUndefinedSymbol(name)`, allowing to override the behavior. + By default, an Error is thrown. + + +# 2021-03-10, version 9.3.0 + +- Implemented support for parsing non decimal numbers with radix point, + see #2122, #2121. Thanks @clnhlzmn. +- Fix #2128: typo in docs of `luSolveAll` and `usolveAll`. + + +# 2021-02-03, version 9.2.0 + +- Implemented function `count` to count the total elements in a matrix, + see #2085. Thanks @Josef37. +- Fix #2096: cleanup old reference to external dependency `crypto`. +- Some refactoring in the code to remove duplications, see #2093. + Thanks @Josef37. + + +# 2021-01-27, version 9.1.0 + +- Extended function `reshape` with support for a wildcard `-1` to automatically + calculate the remaining size, like `reshape([1, 2, 3, 4, 5, 6], [-1, 2])` + which will output `[[0, 1], [2, 3], [4, 5]]`. See #2075. Thanks @Josef37. +- Fix #2087: function `simplify` ignores second argument of `log`, for example + in `simplify('log(e, 9)')` . Thanks @quentintruong. + + +# 2021-01-16, version 9.0.0 + +- Improved support for bin, hex, and oct literals. See #1996. Thanks @clnhlzmn. + - **Breaking change**: parse literals with prefixes `0b`, `0c`, and `0x` are + now unsigned by default. To parse them as signed, you have to specify a + suffix specifying the word size such as `i16` or `i32`. + - Function `format` now supports more notations: `bin`, 'hex', and `oct`, + for example `format(255, {notation: "hex"})`. + - The functions `format`, `bin`, `hex`, `oct` now allow specifying a wordSize, + like `bin(10, 32)` and `format(10, {notation: "bin", wordSize: 32})`. + - BigNumber support for the bin, hex, and oct literals. +- Extended and improved the example rocket_trajectory_optimization.html. + Thanks @Josef37. + + +# 2020-12-30, version 8.1.1 + +- Improved the performance of parsing and evaluating units a lot, see #2065. + Thanks @flaviut. +- Upgraded dependency `fraction.js` to `v4.0.13`. +- Moved continuous integration testing from Travis CI to Github Workflow, + see #2024, #2041. Thanks @harrysarson. + + +# 2020-12-04, version 8.1.0 + +- Implemented units `kilogramforce` (`kgf`). Thanks @rnd-debug. +- Fix #2026: Implement a new option `fractionsLimit` for function `simplify`, + defaulting to `Infinity`. +- Improved the documentation of function `clone`. Thanks @redbar0n. + + +# 2020-11-09, version 8.0.1 + +- Fix #1979: missing "subset" dependency when using "mathjs/number" entry point. +- Fix #2022: update pretty printing with MathJax example to the latest version + of MathJax. Thanks @pkra. + + +# 2020-11-06, version 8.0.0 + +!!! BE CAREFUL: BREAKING CHANGES !!! + +- You can now use mathjs directly in node.js using ES modules without need for + a transpiler (see #1928, #1941, #1962). + Automatically loading either commonjs code or ES modules code is improved. + All generated code is moved under `/lib`: the browser bundle is moved from + `/dist` to `/lib/browser`, ES module files are moved to `/lib/esm`, + and commonjs files are moved to `/lib/cjs`. Thanks @GreenImp. +- Non-minified bundle `dist/math.js` is no longer provided. Either use the + minified bundle, or create a bundle yourself. +- Replaced random library `seed-random` with `seedrandom`, see #1955. + Thanks @poppinlp. +- Breaking changes in `pickRandom`, see #1990, #1976. + - Will no longer return the input matrix when the given number is greater + than the length of the provided possibles. Instead, the function always + returns results with the requested number of picks. + - Will now return a `Matrix` as output when input was a `Matrix`. + - Introduced a new syntax: + + ``` + math.pickRandom(array, { weights, number, elementWise }) + ``` + - Introduced a new option `elementWise`, which is `true` by default. + When setting `elementWise` to false, an array containing arrays will return + random pick of arrays instead of the elements inside of the nested arrays. + + +# 2020-11-02, version 7.6.0 + +- Implemented function `rotate(w, theta)`. See #1992, #1160. Thanks @rnd-debug. +- Implemented support for custom characters in Units via `Unit.isValidAlpha`. + See #1663, #2000. Thanks @rnd-debug. + + +# 2020-10-10, version 7.5.1 + +- Fix object pollution vulnerability in `math.config`. Thanks Snyk. + + +# 2020-10-07, version 7.5.0 + +- Function `pickRandom` now allows randomly picking elements from matrices + with 2 or more dimensions instead of only from a vector, see #1974. + Thanks @KonradLinkowski. + + +# 2020-10-07, version 7.4.0 + +- Implemented support for passing a precision in functions `ceil`, `floor`, + and `fix`, similar to `round`, see #1967, #1901. Thanks @rnd-debug. +- Implemented function `rotationMatrix`, see #1160, #1984. Thanks @rnd-debug. +- Implement a clear error message when using `sqrtm` with a matrix having + more than two dimensions. Thanks @KonradLinkowski. +- Update dependency `decimal.js` to `10.2.1`. + + +# 2020-09-26, version 7.3.0 + +- Implemented functions `usolveAll` and `lsolveAll`, see #1916. Thanks @m93a. +- Implemented support for units in functions `std` and `variance`, see #1950. + Thanks @rnd-debug. +- Implemented support for binary, octal, and hexadecimal notation in the + expression parser, and implemented functions `bin`, `oct`, and `hex` for + formatting. Thanks @clnhlzmn. +- Fix #1964: inconsistent calculation of negative dividend modulo for + `BigNumber` and `Fraction`. Thanks @ovk. + + +# 2020-08-24, version 7.2.0 + +- Implemented new function `diff`, see #1634, #1920. Thanks @Veeloxfire. +- Implemented support for norm 2 for matrices in function `norm`. + Thanks @rnd-debug. + + +# 2020-07-13, version 7.1.0 + +- Implement support for recursion (self-referencing) of typed-functions, + new in `typed-function@2.0.0`. This fixes #1885: functions which where + extended with a new data type did not always work. Thanks @nickewing. +- Fix #1899: documentation on expression trees still using old namespace + `math.expression.node.*` instead of `math.*`. + + +# 2020-06-24, version 7.0.2 + +- Fix #1882: have `DenseMatrix.resize` and `SparseMatrix.resize` accept + `DenseMatrix` and `SparseMatrix` as inputs too, not only `Array`. +- Fix functions `sum`, `prod`, `min`, and `max` not throwing a conversion error + when passing a single string, like `sum("abc")`. + + +# 2020-05-30, version 7.0.1 + +- Fix #1844: clarify the documentation of function `eigs`. Thanks @Lazersmoke. +- Fix #1855: Fix error in the documentation for `math.nthRoots(x)`. +- Fix #1856: make the library robust against Object prototype pollution. + + +# 2020-05-07, version 7.0.0 + +Breaking changes: + +- Improvements in calculation of the `dot` product of complex values. + The first argument is now conjugated. See #1761. Thanks @m93a. +- Dropped official support for Node.js v8 which has reached end of life. +- Removed all deprecation warnings introduced in v6. + To upgrade smoothly from v5 to v7 or higher, upgrade to v6 first + and resolve all deprecation warnings. + + +# 2020-05-04, version 6.6.5 + +- Fix #1834: value `Infinity` cannot be serialized and deserialized. + This is solved now with a new `math.replacer` function used as + `JSON.stringify(value, math.replacer)`. +- Fix #1842: value `Infinity` not turned into the latex symbol `\\infty`. + + +# 2020-04-15, version 6.6.4 + +- Fix published files containing Windows line endings (CRLF instead of LF). + + +# 2020-04-10, version 6.6.3 + +- Fix #1813: bug in engineering notation for numbers of function `format`, + sometimes resulting in needless trailing zeros. +- Fix #1808: methods `.toNumber()` and `.toNumeric()` not working on a + unitless unit. +- Fix #1645: not being able to use named operators `mod`, `and`, `not`, `or`, + `xor`, `to`, `in` as object keys. Thanks @Veeloxfire. +- Fix `eigs` not using `config.epsilon`. + + +# 2020-03-29, version 6.6.2 + +- Fix #1789: Function `eigs` not calculating with BigNumber precision + when input contains BigNumbers. +- Run the build script during npm `prepare`, so you can use the library + directly when installing directly from git. See #1751. Thanks @cinderblock. + + +# 2020-02-26, version 6.6.1 + +- Fix #1725: simplify `a/(b/c)`. Thanks @dbramwell. +- Fix examples in documentation of `row` and `column`. + + +# 2020-02-01, version 6.6.0 + +- Implemented function `eigs`, see #1705, #542 #1175. Thanks @arkajitmandal. +- Fixed #1727: validate matrix size when creating a `DenseMatrix` using + `fromJSON`. +- Fixed `DenseMatrix.map` copying the size and datatype from the original + matrix instead of checking the returned dimensions and type of the callback. +- Add a caret to dependencies (like) `^1.2.3`) to allow downstream updates + without having to await a new release of mathjs. + + +# 2020-01-08, version 6.5.0 + +- Implemented `baseName` option for `createUnit`, see #1707. + Thanks @ericman314. + + +# 2020-01-06, version 6.4.0 + +- Extended function `dimension` with support for n-dimensional points. + Thanks @Veeloxfire. + + +# 2019-12-31, version 6.3.0 + +- Improved performance of `factorial` for `BigNumber` up to a factor two, + see #1687. Thanks @kmdrGroch. + + +# 2019-11-20, version 6.2.5 + +- Fixed `IndexNode` using a hardcoded, one-based implementation of `index`, + making it impossible to instantiate a zero-based version of the expression + parser. See #782. + + +# 2019-11-20, version 6.2.4 + +- Fixed #1669: function 'qr' threw an error if the pivot was zero, + thanks @kevinkelleher12 and @harrysarson. +- Resolves #942: remove misleading assert in 'qr'. Thanks @harrysarson. +- Work around a bug in complex.js where `sign(0)` returns complex NaN. + Thanks @harrysarson. + + +# 2019-10-06, version 6.2.3 + +- Fixed #1640: function `mean` not working for units. Thanks @clintonc. +- Fixed #1639: function `min` listed twice in the "See also" section of the + embedded docs of function `std`. +- Improved performance of `isPrime`, see #1641. Thanks @arguiot. + + +# 2019-09-23, version 6.2.2 + +- Fixed methods `map` and `clone` not copying the `dotNotation` property of + `IndexNode`. Thanks @rianmcguire. +- Fixed a typo in the documentation of `toHTML`. Thanks @maytanthegeek. +- Fixed #1615: error in the docs of `isNumeric`. +- Fixed #1628: Cannot call methods on empty strings or numbers with value `0`. + + +# 2019-08-31, version 6.2.1 + +- Fixed #1606: function `format` not working for expressions. + + +# 2019-08-28, version 6.2.0 + +- Improved performance of `combinationsWithRep`. Thanks @waseemyusuf. +- Add unit aliases `bit` and `byte`. +- Fix docs referring to `bit` and `byte` instead of `bits` and `bytes`. +- Updated dependency `typed-function@1.1.1`. + + +# 2019-08-17, version 6.1.0 + +- Implemented function `combinationsWithRep` (see #1329). Thanks @waseemyusuf. + + +# 2019-08-05, version 6.0.4 + +- Fixed #1554, #1565: ES Modules where not transpiled to ES5, giving issues on + old browsers. Thanks @mockdeep for helping to find a solution. + + +# 2019-07-07, version 6.0.3 + +- Add `unpkg` and `jsdelivr` fields in package.json pointing to UMD build. + Thanks @tmcw. +- Fix #1550: nested user defined function not receiving variables of an + outer user defined function. + + +# 2019-06-11, version 6.0.2 + +- Fix not being able to set configuration after disabling function `import` + (regression since v6.0.0). + + +# 2019-06-09, version 6.0.1 + +- Fix function reference not published in npm library. +- Fix function `evaluate` and `parse` missing in generated docs. + + +# 2019-06-08, version 6.0.0 + +!!! BE CAREFUL: BREAKING CHANGES !!! + +### Most notable changes + +1. Full support for **ES modules**. Support for tree-shaking out of the box. + + Load all functions: + + ```js + import * as math from 'mathjs' + ``` + + Use a few functions: + + ```js + import { add, multiply } from 'mathjs' + ``` + + Load all functions with custom configuration: + + ```js + import { create, all } from 'mathjs' + const config = { number: 'BigNumber' } + const math = create(all, config) + ``` + + Load a few functions with custom configuration: + + ```js + import { create, addDependencies, multiplyDependencies } from 'mathjs' + const config = { number: 'BigNumber' } + const { add, multiply } = create({ + addDependencies, + multiplyDependencies + }, config) + ``` + +2. Support for **lightweight, number-only** implementations of all functions: + + ``` + import { add, multiply } from 'mathjs/number' + ``` + +3. New **dependency injection** solution used under the hood. + + +### Breaking changes + +- Node 6 is no longer supported. + +- Functions `config` and `import` are not available anymore in the global + context: + + ```js + // v5 + import * as mathjs from 'mathjs' + mathjs.config(...) // error in v6.0.0 + mathjs.import(...) // error in v6.0.0 + ``` + + Instead, create your own mathjs instance and pass config and imports + there: + + ```js + // v6 + import { create, all } from 'mathjs' + const config = { number: 'BigNumber' } + const mathjs = create(all, config) + mathjs.import(...) + ``` + +- Renamed function `typeof` to `typeOf`, `var` to `variance`, + and `eval` to `evaluate`. (the old function names are reserved keywords + which can not be used as a variable name). +- Deprecated the `Matrix.storage` function. Use `math.matrix` instead to create + a matrix. +- Deprecated function `math.expression.parse`, use `math.parse` instead. + Was used before for example to customize supported characters by replacing + `math.parse.isAlpha`. +- Moved all classes like `math.type.Unit` and `math.expression.Parser` to + `math.Unit` and `math.Parser` respectively. +- Fixed #1428: transform iterating over replaced nodes. New behavior + is that it stops iterating when a node is replaced. +- Dropped support for renaming factory functions when importing them. +- Dropped fake BigNumber support of function `erf`. +- Removed all index.js files used to load specific functions instead of all, like: + + ``` + // v5 + // ... set up empty instance of mathjs, then load a set of functions: + math.import(require('mathjs/lib/function/arithmetic')) + ``` + + Individual functions are now loaded simply like: + + ```js + // v6 + import { add, multiply } from 'mathjs' + ``` + + To set a specific configuration on the functions: + + ```js + // v6 + import { create, addDependencies, multiplyDependencies } from 'mathjs' + const config = { number: 'BigNumber' } + const math = create({ addDependencies, multiplyDependencies }, config) + ``` + + See example `advanced/custom_loading.js`. + +- Updated the values of all physical units to their latest official values. + See #1529. Thanks @ericman314. + +### Non breaking changes + +- Implemented units `t`, `tonne`, `bel`, `decibel`, `dB`, and prefixes + for `candela`. Thanks @mcvladthegoat. +- Fixed `epsilon` setting being applied globally to Complex numbers. +- Fix `math.simplify('add(2, 3)')` throwing an error. +- Fix #1530: number formatting first applied `lowerExp` and `upperExp` + and after that rounded the value instead of the other way around. +- Fix #1473: remove `'use strict'` in every file, not needed anymore. + + +# 2019-05-18, version 5.10.3 + +- Fixed dependency `del` being a dependency instead of devDependency. + + +# 2019-05-18, version 5.10.2 + +- Fix #1515, #1516, #1517: broken package due to a naming conflict in + the build folder of a util file `typeOf.js` and `typeof.js`. + Solved by properly cleaning all build folders before building. + + +# 2019-05-17, version 5.10.1 + +- Fix #1512: format using notation `engineering` can give wrong results + when the value has less significant digits than the number of digits in + the output. + + +# 2019-05-08, version 5.10.0 + +- Fix `lib/header.js` not having filled in date and version. Thanks @kevjin. +- Upgraded dependency `decimal.js@10.2.0`, fixing an issue on node.js 12. + + +# 2019-04-08, version 5.9.0 + +- Implemented functions `row` and `column` (see #1413). Thanks @SzechuanSage. +- Fixed #1459: `engineering` notation of function `format` not available + for `BigNumber`. +- Fixed #1465: `node.toHTML()` not correct for unary operators like + `factorial`. + + +# 2019-03-20, version 5.8.0 + +- Implemented new function `apply`. Thanks @bnlcas. +- Implemented passing an optional `dimension` argument to `std` and `var`. + Thanks @bnlcas. + + +# 2019-03-10, version 5.7.0 + +- Implemented support for `pow()` in `derivative`. Thanks @sam-19. +- Gracefully handle round-off errors in fix, ceil, floor, and range + (Fixes #1429, see also #1434, #1432). Thanks @ericman314. + + +# 2019-03-02, version 5.6.0 + +- Upgrade decimal.js to v10.1.1 (#1421). +- Fixed #1418: missing whitespace when stringifying an expression + containing "not". + + +# 2019-02-20, version 5.5.0 + +- Fixed #1401: methods `map` and `forEach` of `SparseMatrix` not working + correctly when indexes are unordered. +- Fixed #1404: inconsistent rounding of negative numbers. +- Upgrade tiny-emitter to v2.1.0 (#1397). + + +# 2019-01-25, version 5.4.2 + +- Fixed `math.format` not working for BigNumbers with a precision above + 1025 digits (see #1385). Thanks @ericman314. +- Fixed incorrect LaTeX output of `RelationalNode`. Thanks @rianmcguire. +- Fixed a bug the methods `map`, `forEach`, `traverse`, and `transform` + of `FunctionNode`. + + +# 2019-01-10, version 5.4.1 + +- Fix #1378: negative bignumbers not formatted correctly. +- Upgrade fraction.js to version 4.0.12 (#1369). + + +# 2018-12-09, version 5.4.0 + +- Extended sum.js to accept a dimension input to calculate the sum over a + specific axis. Thanks @bnlcas. +- Fix #1328: objects can't be written multi-line. Thanks @GHolk. +- Remove side effects caused by `Unit.format` and `Unit.toString`, + making changes to the unit on execution. Thanks @ericman314. + + +# 2018-12-03, version 5.3.1 + +- Fixed #1336: Unit.toSI() returning units with prefix like `mm` instead + of `m`. Thanks @ericman314. + + +# 2018-11-29, version 5.3.0 + +- Implemented function `hasNumericValue`. Thanks @Sathish-kumar-Subramani. +- Fix #1326: non-ascii character in print.js. +- Fix #1337: `math.format` not working correctly with `{ precision: 0 }`. + Thanks @dkenul. + + +# 2018-10-30, version 5.2.3 + +- Fixed #1293: non-unicode characters in `escape-latex` giving issues in some + specific cases. Thanks @dangmai. +- Fixed incorrect LaTeX output of function `bitNot`, see #1299. Thanks @FSMaxB. +- Fixed #1304: function `pow` not supporting inputs `pow(Unit, BigNumber)`. +- Upgraded dependencies (`escape-latex@1.2.0`) + + +# 2018-10-23, version 5.2.2 + +- Fixed #1286: Fixed unit base recognition and formatting for + user-defined units. Thanks @ericman314. + + +# 2018-10-18, version 5.2.1 + +- Fixed unit `rod` being defined as `5.02921` instead of `5.0292`. + Thanks @ericman314. +- Upgraded dependencies (`fraction.js@4.0.10`) +- Upgraded devDependencies (`@babel/core@7.1.2`, `nyc@13.1.0`, + `webpack@4.21.0`). + + +# 2018-10-05, version 5.2.0 + +- Implemented support for chained conditionals like `10 < x <= 50`. + Thanks @ericman314. +- Add an example showing a proof of concept of using `BigInt` in mathjs. +- Fixed #1269: Bugfix for BigNumber divided by unit. Thanks @ericman314. +- Fixed #1240: allow units having just a value and no unit. + Thanks @ericman314. + + +## 2018-09-09, version 5.1.2 + +- Fixed a typo in the docs of `parse`. Thanks @mathiasvr. +- Fixed #1222: a typo in the docs of `subset`. +- Fixed #1236: `quantileSeq` has inconsistent return. +- Fixed #1237: norm sometimes returning a complex number instead of + number. +- Upgraded dependencies (`fraction.js@4.0.9`) +- Upgraded devDependencies (`babel@7`, `karma-webpack@3.0.4`, + `nyc@13.0.1`, `standard@12.0.0`, `uglify-js@3.4.9`, `webpack@4.17.2`) + + +## 2018-08-21, version 5.1.1 + +- Function `isNumeric` now recognizes more types. +- Fixed #1214: functions `sqrt`, `max`, `min`, `var`, `std`, `mode`, `mad`, + `median`, and `partitionSelect` not neatly handling `NaN` inputs. In some + cases (`median`, `mad`, and `partitionSelect`) this resulted in an infinite + loop. +- Upgraded dependencies (`escape-latex@1.1.1`) +- Upgraded devDependencies (`webpack@4.17.0`) + + +## 2018-08-12, version 5.1.0 + +- Implemented support for strings enclosed in single quotes. + Thanks @jean-emmanuel. +- Implemented function `getMatrixDataType`. Thanks @JasonShin. +- Implemented new `options` argument in `simplify`. Thanks @paulobuchsbaum. +- Bug fixes in `rationalize`, see #1173. Thanks @paulobuchsbaum. + + +## 2018-07-22, version 5.0.4 + +- Strongly improved the performance of functions `factorial` for numbers. + This improves performance of functions `gamma`, `permutation`, and + `combination` too. See #1170. Thanks @honeybar. +- Strongly improved the performance of function `reshape`, thanks to a + friend of @honeybar. + + +## 2018-07-14, version 5.0.3 + +- Fixed many functions (for example `add` and `subtract`) not working + with matrices having a `datatype` defined. +- Fixed #1147: bug in `format` with `engineering` notation in outputting + the correct number of significant figures. Thanks @ericman314. +- Fixed #1162: transform functions not being cleaned up when overriding + it by importing a factory function with the same name. +- Fixed broken links in the documentation. Thanks @stropitek. +- Refactored the code of `parse` into a functional approach. + Thanks @harrysarson. +- Changed `decimal.js` import to ES6. Thanks @weinshel. + + +## 2018-07-07, version 5.0.2 + +- Fixed #1136: rocket trajectory example broken (since v4.0.0). +- Fixed #1137: `simplify` unnecessarily replacing implicit multiplication with + explicit multiplication. +- Fixed #1146: `rationalize` throwing exceptions for some input with decimals. + Thanks @maruta. +- Fixed #1088: function arguments not being passed to `rawArgs` functions. +- Fixed advanced example `add_new_datatypes`. +- Fixed mathjs core constants not working without complex numbers. + Thanks @ChristopherChudzicki. +- Fixed a broken link in the documentation on units. Thanks @stropitek. +- Upgraded dependencies (`typed-function@1.0.4`, `complex.js@2.0.11`). +- Upgraded devDependencies (`babel-loader@7.1.5 `, `uglify-js@3.4.3`, + `expr-eval@1.2.2`, `webpack@4.15.1`). + + +## 2018-07-01, version 5.0.1 + +- Improved error messaging when converting units. Thanks @gap777. +- Upgraded devDependencies (`kerma`, `uglify-js`, `webpack`). + + +## 2018-06-16, version 5.0.0 + +!!! BE CAREFUL: BREAKING CHANGES !!! + +- Implemented complex conjugate transpose `math.ctranspose`. See #1097. + Thanks @jackschmidt. +- Changed the behavior of `A'` (transpose) in the expression parser to + calculate the complex conjugate transpose. See #1097. Thanks @jackschmidt. +- Added support for `complex({abs: 1, arg: 1})`, and improved the docs on + complex numbers. Thanks @ssaket. +- Renamed `eye` to `identity`, see #1054. +- Math.js code can now contain ES6. The ES6 source code is moved from `lib` + to `src`, and `lib` now contains the compiled ES5 code. +- Upgraded dependencies: + - `decimal.js` from `9.0.1` to `10.0.1` + - Upgraded dev dependencies +- Changed code style to https://standardjs.com/, run linter on `npm test`. + See #1110. +- Dropped support for bower. Use npm or an other package manages instead. +- Dropped support for (non-primitive) instances of `Number`, `Boolean`, and + `String` from functions `clone` and `typeof`. +- Dropped official support for IE9 (probably still works, but it's not tested). +- Fixed #851: More consistent behavior of sqrt, nthRoot, and pow. + Thanks @dakotablair. +- Fixed #1103: Calling `toTex` on node that contains `derivative` causing + an exception. Thanks @joelhoover. + + +## 2018-06-02, version 4.4.2 + +- Drastically improved the performance of `det`. Thanks @ericman314. +- Fixed #1065, #1121: Fixed wrong documentation of function + `compareNatural` and clarified the behavior for strings. +- Fixed #1122 a regression in function `inv` (since `v4.4.1`). + Thanks @ericman314. + + +## 2018-05-29, version 4.4.1 + +- Fixed #1109: a bug in `inv` when dealing with values close to zero. + Thanks @ericman314. + + +## 2018-05-28, version 4.4.0 + +- Implemented functions `equalText` and `compareText`. See #1085. + + +## 2018-05-21, version 4.3.0 + +- Implemented matrix exponential `math.expm`. Thanks @ericman314. +- Fixed #1101: math.js bundle not working when loading in a WebWorker. +- Upgraded dependencies + - `complex.js` from `v2.0.2` to `v2.0.10`. + - `fraction.js` from `v4.0.4` to `v4.0.8`. +- Upgraded devDependencies (`mocha`, `uglify-js`, `webpack`). + + +## 2018-05-05, version 4.2.2 + +- Fixed calculating the Frobenius norm of complex matrices correctly, + see #1098. Thanks @jackschmidt. +- Fixed #1076: cannot use mathjs in React VR by updating to + `escape-latex@1.0.3`. + + +## 2018-05-02, version 4.2.1 + +- Fixed `dist/math.js` being minified. + + +## 2018-05-02, version 4.2.0 + +- Implemented function `math.sqrtm`. Thanks @ferrolho. +- Implemented functions `math.log2`, `math.log1p`, and `math.expm1`. + Thanks @BigFav and @harrysarson. +- Fixed some unit tests broken on nodejs v10. +- Upgraded development dependencies. +- Dropped integration testing on nodejs v4. + + +## 2018-04-18, version 4.1.2 + +- Fixed #1082: implemented support for unit plurals `decades`, `centuries`, + and `millennia`. +- Fixed #1083: units `decade` and `watt` having a wrong name when stringifying. + Thanks @ericman314. + + +## 2018-04-11, version 4.1.1 + +- Fixed #1063: derivative not working when resolving a variable with unary + minus like `math.derivative('-x', 'x')`. + + +## 2018-04-08, version 4.1.0 + +- Extended function `math.print` with support for arrays and matrices. + Thanks @jean-emmanuel. +- Fixed #1077: Serialization/deserialization to JSON with reviver not being + supported by nodes. +- Fixed #1016: Extended `math.typeof` with support for `ResultSet` and nodes + like `SymbolNode`. +- Fixed #1072: Added support for long and short prefixes for the unit `bar` + (i.e. `millibar` and `mbar`). + + +## 2018-03-17, version 4.0.1 + +- Fixed #1062: mathjs not working on ES5 browsers like IE11 and Safari 9.3. +- Fixed #1061: `math.unit` not accepting input like `1/s`. + + +## 2018-02-25, version 4.0.0 + +!!! BE CAREFUL: BREAKING CHANGES !!! + +Breaking changes (see also #682): + +- **New expression compiler** + + The compiler of the expression parser is replaced with one that doesn't use + `eval` internally. See #1019. This means: + + - a slightly improved performance on most browsers. + - less risk of security exploits. + - the code of the new compiler is easier to understand, maintain, and debug. + + Breaking change here: When using custom nodes in the expression parser, + the syntax of `_compile` has changed. This is an undocumented feature though. + +- **Parsed expressions** + + - The class `ConstantNode` is changed such that it just holds a value + instead of holding a stringified value and it's type. + `ConstantNode(valueStr, valueType`) is now `ConstantNode(value)` + Stringification uses `math.format`, which may result in differently + formatted numeric output. + + - The constants `true`, `false`, `null`, `undefined`, `NaN`, `Infinity`, + and `uninitialized` are now parsed as ConstantNodes instead of + SymbolNodes in the expression parser. See #833. + +- **Implicit multiplication** + + - Changed the behavior of implicit multiplication to have higher + precedence than explicit multiplication and division, except in + a number of specific cases. This gives a more natural behavior + for implicit multiplications. For example `24h / 6h` now returns `4`, + whilst `1/2 kg` evaluates to `0.5 kg`. Thanks @ericman314. See: #792. + Detailed documentation: https://github.com/josdejong/mathjs/blob/v4/docs/expressions/syntax.md#implicit-multiplication. + + - Immediately invoking a function returned by a function like `partialAdd(2)(3)` + is no longer supported, instead these expressions are evaluated as + an implicit multiplication `partialAdd(2) * (3)`. See #1035. + +- **String formatting** + + - In function `math.format`, the options `{exponential: {lower: number, upper: number}}` + (where `lower` and `upper` are values) are replaced with `{lowerExp: number, upperExp: number}` + (where `lowerExp` and `upperExp` are exponents). See #676. For example: + ```js + math.format(2000, {exponential: {lower: 1e-2, upper: 1e2}}) + ``` + is now: + ```js + math.format(2000, {lowerExp: -2, upperExp: 2}) + ``` + + - In function `math.format`, the option `notation: 'fixed'` no longer rounds to + zero digits when no precision is specified: it leaves the digits as is. + See #676. + +- **String comparison** + + Changed the behavior of relational functions (`compare`, `equal`, + `equalScalar`, `larger`, `largerEq`, `smaller`, `smallerEq`, `unequal`) + to compare strings by their numeric value they contain instead of + alphabetically. This also impacts functions `deepEqual`, `sort`, `min`, + `max`, `median`, and `partitionSelect`. Use `compareNatural` if you + need to sort an array with text. See #680. + +- **Angle units** + + Changed `rad`, `deg`, and `grad` to have short prefixes, + and introduced `radian`, `degree`, and `gradian` and their plurals + having long prefixes. See #749. + +- **Null** + + - `null` is no longer implicitly casted to a number `0`, so input like + `math.add(2, null)` is no longer supported. See #830, #353. + + - Dropped constant `uninitialized`, which was used to initialize + leave new entries undefined when resizing a matrix is removed. + Use `undefined` instead to indicate entries that are not explicitly + set. See #833. + +- **New typed-function library** + + - The `typed-function` library used to check the input types + of functions is completely rewritten and doesn't use `eval` under + the hood anymore. This means a reduced security risk, and easier + to debug code. The API is the same, but error messages may differ + a bit. Performance is comparable but may differ in specific + use cases and browsers. + +Non breaking changes: + +- Thanks to the new expression compiler and `typed-function` implementation, + mathjs doesn't use JavaScript's `eval` anymore under the hood. + This allows using mathjs in environments with security restrictions. + See #401. +- Implemented additional methods `isUnary()` and `isBinary()` on + `OperatorNode`. See #1025. +- Improved error messages for statistical functions. +- Upgraded devDependencies. +- Fixed #1014: `derivative` silently dropping additional arguments + from operator nodes with more than two arguments. + + +## 2018-02-07, version 3.20.2 + +- Upgraded to `typed-function@0.10.7` (bug-fix release). +- Fixed option `implicit` not being copied from an `OperatorNode` + when applying function `map`. Thanks @HarrySarson. +- Fixed #995: spaces and underscores not property being escaped + in `toTex()`. Thanks @FSMaxB. + + +## 2018-01-17, version 3.20.1 + +- Fixed #1018: `simplifyCore` failing in some cases with parentheses. + Thanks @firepick1. + + +## 2018-01-14, version 3.20.0 + +- Implement support for 3 or more arguments for operators `+` and `*` in + `derivative`. Thanks @HarrySarson. See #1002. +- Fixed `simplify` evalution of `simplify` of functions with more than two + arguments wrongly: `simplify('f(x, y, z)') evaluated to `f(f(x, y), z)` + instead of `f(x, y, z)`. Thanks @joelhoover. +- Fixed `simplify` throwing an error in some cases when simplifying unknown + functions, for example `simplify('f(4)')`. Thanks @joelhoover. +- Fixed #1013: `simplify` wrongly simplifing some expressions containing unary + minus, like `0 - -x`. Thanks @joelhoover. +- Fixed an error in an example in the documentation of `xor`. Thanks @denisx. + + +## 2018-01-06, version 3.19.0 + +- Extended functions `distance` and `intersect` with support for BigNumbers. + Thanks @ovk. +- Improvements in function `simplify`: added a rule that allows combining + of like terms in embedded quantities. Thanks @joelhoover. + + +## 2017-12-28, version 3.18.1 + +- Fixed #998: An issue with simplifying an expression containing a subtraction. + Thanks @firepick1. + + +## 2017-12-16, version 3.18.0 + +- Implemented function `rationalize`. Thanks @paulobuchsbaum. +- Upgraded dependencies: + ``` + decimal.js 7.2.3 → 9.0.1 (no breaking changes affecting mathjs) + fraction.js 4.0.2 → 4.0.4 + tiny-emitter 2.0.0 → 2.0.2 + ``` +- Upgraded dev dependencies. +- Fixed #975: a wrong example in the docs of lusolve. +- Fixed #983: `pickRandom` returning an array instead of single value + when input was an array with just one value. Clarified docs. +- Fixed #969: preven issues with yarn autoclean by renaming an + interally used folder "docs" to "embeddedDocs". + + +## 2017-11-18, version 3.17.0 + +- Improved `simplify` for nested exponentiations. Thanks @IvanVergiliev. +- Fixed a security issue in `typed-function` allowing arbitrary code execution + in the JavaScript engine by creating a typed function with JavaScript code + in the name. Thanks Masato Kinugawa. +- Fixed a security issue where forbidden properties like constructor could be + replaced by using unicode characters when creating an object. No known exploit, + but could possibly allow arbitrary code execution. Thanks Masato Kinugawa. + + +## 2017-10-18, version 3.16.5 + +- Fixed #954: Functions `add` and `multiply` not working when + passing three or more arrays or matrices. + + +## 2017-10-01, version 3.16.4 + +- Fixed #948, #949: function `simplify` returning wrong results or + running into an infinite recursive loop. Thanks @ericman314. +- Fixed many small issues in the embedded docs. Thanks @Schnark. + + +## 2017-08-28, version 3.16.3 + +- Fixed #934: Wrong simplification of unary minus. Thanks @firepick1. +- Fixed #933: function `simplify` reordering operations. Thanks @firepick1. +- Fixed #930: function `isNaN` returning wrong result for complex + numbers having just one of their parts (re/im) being `NaN`. +- Fixed #929: `FibonacciHeap.isEmpty` returning wrong result. + + +## 2017-08-20, version 3.16.2 + +- Fixed #924: a regression in `simplify` not accepting the signature + `simplify(expr, rules, scope)` anymore. Thanks @firepick1. +- Fixed missing parenthesis when stringifying expressions containing + implicit multiplications (see #922). Thanks @FSMaxB. + + +## 2017-08-12, version 3.16.1 + +- For security reasons, type checking is now done in a more strict + way using functions like `isComplex(x)` instead of duck type checking + like `x && x.isComplex === true`. +- Fixed #915: No access to property "name". +- Fixed #901: Simplify units when calling `unit.toNumeric()`. + Thanks @AlexanderBeyn. +- Fixed `toString` of a parsed expression tree containing an + immediately invoked function assignment not being wrapped in + parenthesis (for example `(f(x) = x^2)(4)`). + + +## 2017-08-06, version 3.16.0 + +- Significant performance improvements in `math.simplify`. + Thanks @firepick1. +- Improved API for `math.simplify`, optionally pass a scope with + variables which are resolved, see #907. Thanks @firepick1. +- Fixed #912: math.js didn't work on IE10 anymore (regression + since 3.15.0). + + +## 2017-07-29, version 3.15.0 + +- Added support for the dollar character `$` in symbol names (see #895). +- Allow objects with prototypes as scope again in the expression parser, + this was disabled for security reasons some time ago. See #888, #899. + Thanks @ThomasBrierley. +- Fixed #846: Issues in the functions `map`, `forEach`, and `filter` + when used in the expression parser: + - Not being able to use a function assignment as inline expression + for the callback function. + - Not being able to pass an inline expression as callback for `map` + and `forEach`. + - Index and original array/matrix not passed in `map` and `filter`. + + +## 2017-07-05, version 3.14.2 + +- Upgraded to `fraction.js@4.0.2` +- Fixed #891 using BigNumbers not working in browser environments. + + +## 2017-06-30, version 3.14.1 + +- Reverted to `fraction.js@4.0.0`, there is an issue with `4.0.1` + in the browser. + + +## 2017-06-30, version 3.14.0 + +- Implemented set methods `setCartesian`, `setDifference`, + `setDistinct`, `setIntersect`, `setIsSubset`, `setPowerset`, + `setSize`. Thanks @Nekomajin42. +- Implemented method `toHTML` on nodes. Thanks @Nekomajin42. +- Implemented `compareNatural` and `sort([...], 'natural')`. +- Upgraded dependencies to the latest versions: + - `complex.js@2.0.4` + - `decimal.js@7.2.3` + - `fraction.js@4.0.1` + - `tiny-emitter@2.0.0` + - And all devDependencies. +- Fixed #865: `splitUnit` can now deal with round-off errors. + Thanks @ericman314. +- Fixed #876: incorrect definition for unit `erg`. Thanks @pjhampton. +- More informative error message when using single quotes instead of + double quotes around a string. Thanks @HarrySarson. + + +## 2017-05-27, version 3.13.3 + +- Fixed a bug in function `intersection` of line and plane. + Thanks @viclai. +- Fixed security vulnerabilities. + + +## 2017-05-26, version 3.13.2 + +- Disabled function `chain` inside the expression parser for security + reasons (it's not needed there anyway). +- Fixed #856: function `subset` not returning non-primitive scalars + from Arrays correctly. (like `math.eval('arr[1]', {arr: [math.bignumber(2)]})`. +- Fixed #861: physical constants not available in the expression parser. + + +## 2017-05-12, version 3.13.1 + +- Fixed creating units with an alias not working within the expression + parser. +- Fixed security vulnerabilities. Thanks Sam. + + +## 2017-05-12, version 3.13.0 + +- Command line application can now evaluate inline expressions + like `mathjs 1+2`. Thanks @slavaGanzin. +- Function `derivative` now supports `abs`. Thanks @tetslee. +- Function `simplify` now supports BigNumbers. Thanks @tetslee. +- Prevent against endless loops in `simplify`. Thanks @tetslee. +- Fixed #813: function `simplify` converting small numbers to inexact + Fractions. Thanks @tetslee. +- Fixed #838: Function `simplify` now supports constants like `e`. + Thanks @tetslee. + + +## 2017-05-05, version 3.12.3 + +- Fixed security vulnerabilities. Thanks Dan and Sam. + + +## 2017-04-30, version 3.12.2 + +- Added a rocket trajectory optimization example. + + +## 2017-04-24, version 3.12.1 + +- Fixed #804 + - Improved handling of powers of `Infinity`. Thanks @HarrySarson. + - Fixed wrong formatting of complex NaN. +- Fixed security vulnerabilities in the expression parser. + Thanks Sam and Dan. + + +## 2017-04-17, version 3.12.0 + +- Implemented QR decomposition, function `math.qr`. Thanks @HarrySarson. +- Fixed #824: Calling `math.random()` freezes IE and node.js. + + +## 2017-04-08, version 3.11.5 + +- More security measures in the expression parser. + WARNING: the behavior of the expression parser is now more strict, + some undocumented features may not work any longer. + - Accessing and assigning properties is now only allowed on plain + objects, not on classes, arrays, and functions anymore. + - Accessing methods is restricted to a set of known, safe methods. + + +## 2017-04-03, version 3.11.4 + +- Fixed a security vulnerability in the expression parser. Thanks @xfix. + + +## 2017-04-03, version 3.11.3 + +- Fixed a security vulnerability in the expression parser. Thanks @xfix. + + +## 2017-04-03, version 3.11.2 + +- Fixed a security vulnerability in the expression parser. Thanks @xfix. + + +## 2017-04-02, version 3.11.1 + +- Fixed security vulnerabilities in the expression parser. + Thanks Joe Vennix and @xfix. + + +## 2017-04-02, version 3.11.0 + +- Implemented method Unit.toSI() to convert a unit to base SI units. + Thanks @ericman314. +- Fixed #821, #822: security vulnerabilities in the expression parser. + Thanks @comex and @xfix. + + +## 2017-03-31, version 3.10.3 + +- More security fixes related to the ones fixed in `v3.10.2`. + + +## 2017-03-31, version 3.10.2 + +- Fixed a security vulnerability in the expression parser allowing + execution of arbitrary JavaScript. Thanks @CapacitorSet and @denvit. + + +## 2017-03-26, version 3.10.1 + +- Fixed `xgcd` for negative values. Thanks @litmit. +- Fixed #807: function transform of existing functions not being removed when + overriding such a function. + + +## 2017-03-05, version 3.10.0 + +- Implemented function `reshape`. Thanks @patgrasso and @ericman314. +- Implemented configuration option `seedRandom` for deterministic random + numbers. Thanks @morsecodist. +- Small fixes in the docs. Thanks @HarrySarson. +- Dropped support for component package manager (which became deprecated about + one and a half year ago). + + +## 2017-02-22, version 3.9.3 + +- Fixed #797: issue with production builds of React Native projects. +- Fixed `math.round` not accepting inputs `NaN`, `Infinity`, `-Infinity`. +- Upgraded all dependencies. + + +## 2017-02-16, version 3.9.2 + +- Fixed #795: Parse error in case of a multi-line expression with just comments. + + +## 2017-02-06, version 3.9.1 + +- Fixed #789: Math.js not supporting conversion of `string` to `BigNumber`, + `Fraction`, or `Complex` number. +- Fixed #790: Expression parser did not pass function arguments of enclosing + functions via `scope` to functions having `rawArgs = true`. +- Small fixes in the docs. Thanks @HarrySarson. + + +## 2017-01-23, version 3.9.0 + +- Implemented support for algebra: powerful new functions `simplify` and + `derivative`. Thanks @ericman314, @tetslee, and @BigFav. +- Implemented Kronecker Product `kron`. Thanks @adamisntdead. +- Reverted `FunctionNode` not accepting a string as function name anymore. +- Fixed #765: `FunctionAssignmentNode.toString()` returning a string + incompatible with the function assignment syntax. + + +## 2016-12-15, version 3.8.1 + +- Implemented function `mad` (median absolute deviation). Thanks @ruhleder. +- Fixed #762: expression parser failing to invoke a function returned + by a function. + + +## 2016-11-18, version 3.8.0 + +- Functions `add` and `multiply` now accept more than two arguments. See #739. +- `OperatorNode` now supports more than two arguments. See #739. Thanks @FSMaxB. +- Implemented a method `Node.cloneDeep` for the expression nodes. See #745. +- Fixed a bug in `Node.clone()` not cloning implicit multiplication correctly. + Thanks @FSMaxB. +- Fixed #737: Improved algorithm determining the best prefix for units. + It will now retain the original unit like `1 cm` when close enough, + instead of returning `10 mm`. Thanks @ericman314. +- Fixed #732: Allow letter-like unicode characters like Ohm `\u2126`. +- Fixed #749: Units `rad`, `deg`, and `grad` can now have prefixes like `millirad`. +- Some fixes in the docs and comments of examples. Thanks @HarrySarson. + + +## 2016-11-05, version 3.7.0 + +- Implemented method `Node.equals(other)` for all nodes of the expression parser. +- Implemented BigNumber support in function `arg()`. +- Command Line Interface loads faster. +- Implicit conversions between Fractions and BigNumbers throw a neat error now + (See #710). + + +## 2016-10-21, version 3.6.0 + +- Implemented function `erf()`. THanks @patgrasso. +- Extended function `cross()` to support n-d vectors. Thanks @patgrasso. +- Extended function `pickRandom` with the option to pick multiple values from + an array and give the values weights: `pickRandom(possibles, number, weights)`. + Thanks @woylie. +- Parser now exposes test functions like `isAlpha` which can be replaced in + order to adjust the allowed characters in variables names (See #715). +- Fixed #727: Parser not throwing an error for invalid implicit multiplications + like `-2 2` and `2^3 4` (right after the second value of an operator). +- Fixed #688: Describe allowed variable names in the docs. + + +## 2016-09-21, version 3.5.3 + +- Some more fixes regarding numbers ending with a decimal mark (like `2.`). + + +## 2016-09-20, version 3.5.2 + +- Fixed numbers ending with a decimal mark (like `2.`) not being supported by + the parser, solved the underlying ambiguity in the parser. See #707, #711. + + +## 2016-09-12, version 3.5.1 + +- Removed a left over console.log statement. Thanks @eknkc. + + +## 2016-09-07, version 3.5.0 + +- Comments of expressions are are now stored in the parsed nodes. See #690. +- Fixed function `print` not accepting an Object with formatting options as + third parameter Thanks @ThomasBrierley. +- Fixed #707: The expression parser no longer accepts numbers ending with a dot + like `2.`. + + +## 2016-08-08, version 3.4.1 + +- Fixed broken bundle files (`dist/math.js`, `dist/math.min.js`). +- Fixed some layout issues in the function reference docs. + + +## 2016-08-07, version 3.4.0 + +- Implemented support for custom units using `createUnit`. Thanks @ericman314. +- Implemented function `splitUnits`. Thanks @ericman314. +- Implemented function `isPrime`. Thanks @MathBunny. + + +## 2016-07-05, version 3.3.0 + +- Implemented function `isNaN`. +- Function `math.filter` now passes three arguments to the callback function: + value, index, and array. +- Removed the check on the number of arguments from functions defined in the + expression parser (see #665). +- Fixed #665: functions `map`, `forEach`, and `filter` now invoke callbacks + which are a typed-function with the correct number of arguments. + + +## 2016-04-26, version 3.2.1 + +- Fixed #651: unable to perform calculations on "Unit-less" units. +- Fixed matrix.subset mutating the replacement matrix when unsqueezing it. + + +## 2016-04-16, version 3.2.0 + +- Implemented #644: method `Parser.getAll()` to retrieve all defined variables. +- Upgraded dependencies (decimal.js@5.0.8, fraction.js@3.3.1, + typed-function@0.10.4). +- Fixed #601: Issue with unnamed typed-functions by upgrading to + typed-function v0.10.4. +- Fixed #636: More strict `toTex` templates, reckon with number of arguments. +- Fixed #641: Bug in expression parser parsing implicit multiplication with + wrong precedence in specific cases. +- Fixed #645: Added documentation about `engineering` notation of function + `math.format`. + + +## 2016-04-03, version 3.1.4 + +- Using ES6 Math functions like `Math.sinh`, `Math.cbrt`, `Math.sign`, etc when + available. +- Fixed #631: unit aliases `weeks`, `months`, and `years` where missing. +- Fixed #632: problem with escaped backslashes at the end of strings. +- Fixed #635: `Node.toString` options where not passed to function arguments. +- Fixed #629: expression parser throws an error when passing a number with + decimal exponent instead of parsing them as implicit multiplication. +- Fixed #484, #555: inaccuracy of `math.sinh` for values between -1 and 1. +- Fixed #625: Unit `in` (`inch`) not always working due to ambiguity with + the operator `a in b` (alias of `a to b`). + + +## 2016-03-24, version 3.1.3 + +- Fix broken bundle. + + +## 2016-03-24, version 3.1.2 + +- Fix broken npm release. + + +## 2016-03-24, version 3.1.1 + +- Fixed #621: a bug in parsing implicit multiplications like `(2)(3)+4`. +- Fixed #623: `nthRoot` of zero with a negative root returned `0` instead of + `Infinity`. +- Throw an error when functions `min`, `max`, `mean`, or `median` are invoked + with multiple matrices as arguments (see #598). + + +## 2016-03-19, version 3.1.0 + +- Hide multiplication operator by default when outputting `toTex` and `toString` + for implicit multiplications. Implemented and option to output the operator. +- Implemented unit `kip` and alias `kips`. Thanks @hgupta9. +- Added support for prefixes for units `mol` and `mole`. Thanks @stu-blair. +- Restored support for implicit multiplications like `2(3+4)` and `(2+3)(4+5)`. +- Some improvements in the docs. +- Added automatic conversions from `boolean` and `null` to `Fraction`, + and conversions from `Fraction` to `Complex`. + + +## 2016-03-04, version 3.0.0 + +### breaking changes + +- More restricted support for implicit multiplication in the expression + parser: `(...)(...)` is now evaluated as a function invocation, + and `[...][...]` as a matrix subset. +- Matrix multiplication no longer squeezes scalar outputs to a scalar value, + but leaves them as they are: a vector or matrix containing a single value. + See #529. +- Assignments in the expression parser now return the assigned value rather + than the created or updated object (see #533). Example: + + ``` + A = eye(3) + A[1,1] = 2 # this assignment now returns 2 instead of A + ``` + +- Expression parser now supports objects. This involves a refactoring and + extension in expression nodes: + - Implemented new node `ObjectNode`. + - Refactored `AssignmentNode`, `UpdateNode`, and `IndexNode` are refactored + into `AccessorNode`, `AssignmentNode`, and `IndexNode` having a different API. +- Upgraded the used BigNumber library `decimal.js` to v5. Replaced the + trigonometric functions of math.js with those provided in decimal.js v5. + This can give slightly different behavior qua round-off errors. +- Replaced the internal `Complex.js` class with the `complex.js` library + created by @infusion. +- Entries in a matrix (typically numbers, BigNumbers, Units, etc) are now + considered immutable, they are no longer copied when performing operations on + the entries, improving performance. +- Implemented nearly equal comparison for relational functions (`equal`, + `larger`, `smaller`, etc.) when using BigNumbers. +- Changed the casing of the configuration options `matrix` (`Array` or `Matrix`) + and `number` (`number`, `BigNumber`, `Fraction`) such that they now match + the type returned by `math.typeof`. Wrong casing gives a console warning but + will still work. +- Changed the default config value for `epsilon` from `1e-14` to `1e-12`, + see #561. + +### non-breaking changes + +- Extended function `pow` to return the real root for cubic roots of negative + numbers. See #525, #482, #567. +- Implemented support for JSON objects in the expression parser and the + function `math.format`. +- Function `math.fraction` now supports `BigNumber`, and function + `math.bignumber` now supports `Fraction`. +- Expression parser now allows function and/or variable assignments inside + accessors and conditionals, like `A[x=2]` or `a > 2 ? b="ok" : b="fail"`. +- Command line interface: + - Outputs the variable name of assignments. + - Fixed not rounding BigNumbers to 14 digits like numbers. + - Fixed non-working autocompletion of user defined variables. +- Reorganized and extended docs, added docs on classes and more. Thanks @hgupta9. +- Added new units `acre`, `hectare`, `torr`, `bar`, `mmHg`, `mmH2O`, `cmH2O`, + and added new aliases `acres`, `hectares`, `sqfeet`, `sqyard`, `sqmile`, + `sqmiles`, `mmhg`, `mmh2o`, `cmh2o`. Thanks @hgupta9. +- Fixed a bug in the toString method of an IndexNode. +- Fixed angle units `deg`, `rad`, `grad`, `cycle`, `arcsec`, and `arcmin` not + being defined as BigNumbers when configuring to use BigNumbers. + + +## 2016-02-03, version 2.7.0 + +- Added more unit aliases for time: `secs`, `mins`, `hr`, `hrs`. See #551. +- Added support for doing operations with mixed `Fractions` and `BigNumbers`. +- Fixed #540: `math.intersect()` returning null in some cases. Thanks @void42. +- Fixed #546: Cannot import BigNumber, Fraction, Matrix, Array. + Thanks @brettjurgens. + + +## 2016-01-08, version 2.6.0 + +- Implemented (complex) units `VA` and `VAR`. +- Implemented time units for weeks, months, years, decades, centuries, and + millennia. Thanks @owenversteeg. +- Implemented new notation `engineering` in function `math.format`. + Thanks @johnmarinelli. +- Fixed #523: In some circumstances, matrix subset returned a scalar instead + of the correct subset. +- Fixed #536: A bug in an internal method used for sparse matrices. + + +## 2015-12-05, version 2.5.0 + +- Implemented support for numeric types `Fraction` and `BigNumber` in units. +- Implemented new method `toNumeric` for units. +- Implemented new units `arcsec`, `arcsecond`, `arcmin`, `arcminute`. + Thanks @devdevdata222. +- Implemented new unit `Herts` (`Hz`). Thanks @SwamWithTurtles. +- Fixed #485: Scoping issue with variables both used globally as well as in a + function definition. +- Fixed: Function `number` didn't support `Fraction` as input. + + +## 2015-11-14, version 2.4.2 + +- Fixed #502: Issue with `format` in some JavaScript engines. +- Fixed #503: Removed trailing commas and the use of keyword `import` as + property, as this gives issues with old JavaScript engines. + + +## 2015-10-29, version 2.4.1 + +- Fixed #480: `nthRoot` not working on Internet Explorer (up to IE 11). +- Fixed #490: `nthRoot` returning an error for negative values like + `nthRoot(-2, 3)`. +- Fixed #489: an issue with initializing a sparse matrix without data. + Thanks @Retsam. +- Fixed: #493: function `combinations` did not throw an exception for + non-integer values of `k`. +- Fixed: function `import` did not override typed functions when the option + override was set true. +- Fixed: added functions `math.sparse` and `math.index` to the reference docs, + they where missing. +- Fixed: removed memoization from `gamma` and `factorial` functions, this + could blow up memory. + + +## 2015-10-09, version 2.4.0 + +- Added support in the expression parser for mathematical alphanumeric symbols + in the expression parser: unicode range \u{1D400} to \u{1D7FF} excluding + invalid code points. +- Extended function `distance` with more signatures. Thanks @kv-kunalvyas. +- Fixed a bug in functions `sin` and `cos`, which gave wrong results for + BigNumber integer values around multiples of tau (i.e. `sin(bignumber(7))`). +- Fixed value of unit `stone`. Thanks @Esvandiary for finding the error. + + +## 2015-09-19, version 2.3.0 + +- Implemented function `distance`. Thanks @devanp92. +- Implemented support for Fractions in function `lcm`. Thanks @infusion. +- Implemented function `cbrt` for numbers, complex numbers, BigNumbers, Units. +- Implemented function `hypot`. +- Upgraded to fraction.js v3.0.0. +- Fixed #450: issue with non sorted index in sparse matrices. +- Fixed #463, #322: inconsistent handling of implicit multiplication. +- Fixed #444: factorial of infinity not returning infinity. + + +## 2015-08-30, version 2.2.0 + +- Units with powers (like `m^2` and `s^-1`) now output with the best prefix. +- Implemented support for units to `abs`, `cube`, `sign`, `sqrt`, `square`. + Thanks @ericman314. +- Implemented function `catalan` (Combinatorics). Thanks @devanp92. +- Improved the `canDefineProperty` check to return false in case of IE8, which + has a broken implementation of `defineProperty`. Thanks @golmansax. +- Fixed function `to` not working in case of a simplified unit. +- Fixed #437: an issue with row swapping in `lup`, also affecting `lusolve`. + + +## 2015-08-12, version 2.1.1 + +- Fixed wrong values of the physical constants `speedOfLight`, `molarMassC12`, + and `magneticFluxQuantum`. Thanks @ericman314 for finding two of them. + + +## 2015-08-11, version 2.1.0 + +- Implemented derived units (like `110 km/h in m/s`). Thanks @ericman314. +- Implemented support for electric units. Thanks @ericman314. +- Implemented about 50 physical constants like `speedOfLight`, `gravity`, etc. +- Implemented function `kldivergence` (Kullback-Leibler divergence). + Thanks @saromanov. +- Implemented function `mode`. Thanks @kv-kunalvyas. +- Added support for unicode characters in the expression parser: greek letters + and latin letters with accents. See #265. +- Internal functions `Unit.parse` and `Complex.parse` now throw an Error + instead of returning null when passing invalid input. + + +## 2015-07-29, version 2.0.1 + +- Fixed operations with mixed fractions and numbers be converted to numbers + instead of fractions. + + +## 2015-07-28, version 2.0.0 + +- Large internal refactoring: + - performance improvements. + - allows to create custom bundles + - functions are composed using `typed-function` and are extensible +- Implemented support for fractions, powered by the library `fraction.js`. +- Implemented matrix LU decomposition with partial pivoting and a LU based + linear equations solver (functions `lup` and `lusolve`). Thanks @rjbaucells. +- Implemented a new configuration option `predictable`, which can be set to + true in order to ensure predictable function output types. +- Implemented function `intersect`. Thanks @kv-kunalvyas. +- Implemented support for adding `toTex` properties to custom functions. + Thanks @FSMaxB. +- Implemented support for complex values to `nthRoot`. Thanks @gangachris. +- Implemented util functions `isInteger`, `isNegative`, `isNumeric`, + `isPositive`, and `isZero`. + +### breaking changes + +- String input is now converted to numbers by default for all functions. +- Adding two strings will no longer concatenate them, but will convert the + strings to numbers and add them. +- Function `index` does no longer accept an array `[start, end, step]`, but + instead accepts an array with arbitrary index values. It also accepts + a `Range` object as input. +- Function `typeof` no longer returns lower case names, but now returns lower + case names for primitives (like `number`, `boolean`, `string`), and + upper-camel-case for non-primitives (like `Array`, `Complex`, `Function`). +- Function `import` no longer supports a module name as argument. Instead, + modules can be loaded using require: `math.import(require('module-name'))`. +- Function `import` has a new option `silent` to ignore errors, and throws + errors on duplicates by default. +- Method `Node.compile()` no longer needs `math` to be passed as argument. +- Reintroduced method `Node.eval([scope])`. +- Function `sum` now returns zero when input is an empty array. Thanks @FSMAxB. +- The size of Arrays is no longer validated. Matrices will validate this on + creation. + + +## 2015-07-12, version 1.7.1 + +- Fixed #397: Inaccuracies in nthRoot for very large values, and wrong results + for very small values. (backported from v2) +- Fixed #405: Parser throws error when defining a function in a multiline + expression. + + +## 2015-05-31, version 1.7.0 + +- Implemented function `quantileSeq` and `partitionSelect`. Thanks @BigFav. +- Implemented functions `stirlingS2`, `bellNumbers`, `composition`, and + `multinomial`. Thanks @devanp92. +- Improved the performance of `median` (see #373). Thanks @BigFav. +- Extended the command line interface with a `mode` option to output either + the expressions result, string representation, or tex representation. + Thanks @FSMaxB. +- Fixed #309: Function median mutating the input matrix. Thanks @FSMaxB. +- Fixed `Node.transform` not recursing over replaced parts of the + node tree (see #349). +- Fixed #381: issue in docs of `randomInt`. + + +## 2015-04-22, version 1.6.0 + +- Improvements in `toTex`. Thanks @FSMaxB. +- Fixed #328: `abs(0 + 0i)` evaluated to `NaN`. +- Fixed not being able to override lazy loaded constants. + + +## 2015-04-09, version 1.5.2 + +- Fixed #313: parsed functions did not handle recursive calls correctly. +- Fixed #251: binary prefix and SI prefix incorrectly used for byte. Now + following SI standards (`1 KiB == 1024 B`, `1 kB == 1000 B`). +- Performance improvements in parsed functions. + + +## 2015-04-08, version 1.5.1 + +- Fixed #316: a bug in rounding values when formatting. +- Fixed #317, #319: a bug in formatting negative values. + + +## 2015-03-28, version 1.5.0 + +- Added unit `stone` (6.35 kg). +- Implemented support for sparse matrices. Thanks @rjbaucells. +- Implemented BigNumber support for function `atan2`. Thanks @BigFav. +- Implemented support for custom LaTeX representations. Thanks @FSMaxB. +- Improvements and bug fixes in outputting parentheses in `Node.toString` and + `Node.toTex` functions. Thanks @FSMaxB. +- Fixed #291: function `format` sometimes returning exponential notation when + it should return a fixed notation. + + +## 2015-02-28, version 1.4.0 + +- Implemented trigonometric functions: + `acosh`, `acoth`, `acsch`, `asech`, `asinh`, `atanh`, `acot`, `acsc`, `asec`. + Thanks @BigFav. +- Added BigNumber support for functions: `cot`, `csc`, `sec`, `coth`, + `csch`, `sech`. Thanks @BigFav. +- Implemented support for serialization and deserialization of math.js data + types. +- Fixed the calculation of `norm()` and `abs()` for large complex numbers. + Thanks @rjbaucells. +- Fixed #281: improved formatting complex numbers. Round the real or imaginary + part to zero when the difference is larger than the configured precision. + + +## 2015-02-09, version 1.3.0 + +- Implemented BigNumber implementations of most trigonometric functions: `sin`, + `cos`, `tan`, `asin`, `acos`, `atan`, `cosh`, `sinh`, `tanh`. Thanks @BigFav. +- Implemented function `trace`. Thanks @pcorey. +- Faster loading of BigNumber configuration with a high precision by lazy + loading constants like `pi` and `e`. +- Fixed constants `NaN` and `Infinity` not being BigNumber objects when + BigNumbers are configured. +- Fixed missing parentheses in the `toTex` representation of function + `permutations`. +- Some minor fixes in the docs. Thanks @KenanY. + + +## 2014-12-25, version 1.2.0 + +- Support for bitwise operations `bitAnd`, `bitNot`, `bitOr`, `bitXor`, + `leftShift`, `rightArithShift`, and `rightLogShift`. Thanks @BigFav. +- Support for boolean operations `and`, `not`, `or`, `xor`. Thanks @BigFav. +- Support for `gamma` function. Thanks @BigFav. +- Converting a unit without value will now result in a unit *with* value, + i.e. `inch in cm` will return `2.54 cm` instead of `cm`. +- Improved accuracy of `sinh` and complex `cos` and `sin`. Thanks @pavpanchekha. +- Renamed function `select` to `chain`. The old function `select` will remain + functional until math.js v2.0. +- Upgraded to decimal.js v4.0.1 (BigNumber library). + + +## 2014-11-22, version 1.1.1 + +- Fixed Unit divided by Number returning zero. +- Fixed BigNumber downgrading to Number for a negative base in `pow`. +- Fixed some typos in error messaging (thanks @andy0130tw) and docs. + + +## 2014-11-15, version 1.1.0 + +- Implemented functions `dot` (dot product), `cross` (cross product), and + `nthRoot`. +- Officially opened up the API of expression trees: + - Documented the API. + - Implemented recursive functions `clone`, `map`, `forEach`, `traverse`, + `transform`, and `filter` for expression trees. + - Parameter `index` in the callbacks of `map` and `forEach` are now cloned + for every callback. + - Some internal refactoring inside nodes to make the API consistent: + - Renamed `params` to `args` and vice versa to make things consistent. + - Renamed `Block.nodes` to `Block.blocks`. + - `FunctionNode` now has a `name: string` instead of a `symbol: SymbolNode`. + - Changed constructor of `RangeNode` to + `new RangeNode(start: Node, end: Node [, step: Node])`. + - Nodes for a `BlockNode` must now be passed via the constructor instead + of via a function `add`. +- Fixed `2e` giving a syntax error instead of being parsed as `2 * e`. + + +## 2014-09-12, version 1.0.1 + +- Disabled array notation for ranges in a matrix index in the expression parser + (it is confusing and redundant there). +- Fixed a regression in the build of function subset not being able to return + a scalar. +- Fixed some missing docs and broken links in the docs. + + +## 2014-09-04, version 1.0.0 + +- Implemented a function `filter(x, test)`. +- Removed `math.distribution` for now, needs some rethinking. +- `math.number` can convert units to numbers (requires a second argument) +- Fixed some precedence issues with the range and conversion operators. +- Fixed an zero-based issue when getting a matrix subset using an index + containing a matrix. + + +## 2014-08-21, version 0.27.0 + +- Implemented functions `sort(x [, compare])` and `flatten(x)`. +- Implemented support for `null` in all functions. +- Implemented support for "rawArgs" functions in the expression parser. Raw + functions are invoked with unevaluated parameters (nodes). +- Expressions in the expression parser can now be spread over multiple lines, + like '2 +\n3'. +- Changed default value of the option `wrap` of function `math.import` to false. +- Changed the default value for new entries in a resized matrix when to zero. + To leave new entries uninitialized, use the new constant `math.uninitialized` + as default value. +- Renamed transform property from `__transform__` to `transform`, and documented + the transform feature. +- Fixed a bug in `math.import` not applying options when passing a module name. +- A returned matrix subset is now only squeezed when the `index` consists of + scalar values, and no longer for ranges resolving into a single value. + + +## 2014-08-03, version 0.26.0 + +- A new instance of math.js can no longer be created like `math([options])`, + to prevent side effects from math being a function instead of an object. + Instead, use the function `math.create([options])` to create a new instance. +- Implemented `BigNumber` support for all constants: `pi`, `tau`, `e`, `phi`, + `E`, `LN2`, `LN10`, `LOG2E`, `LOG10E`, `PI`, `SQRT1_2`, and `SQRT2`. +- Implemented `BigNumber` support for functions `gcd`, `xgcd`, and `lcm`. +- Fixed function `gxcd` returning an Array when math.js was configured + as `{matrix: 'matrix'}`. +- Multi-line expressions now return a `ResultSet` instead of an `Array`. +- Implemented transforms (used right now to transform one-based indices to + zero-based for expressions). +- When used inside the expression parser, functions `concat`, `min`, `max`, + and `mean` expect an one-based dimension number. +- Functions `map` and `forEach` invoke the callback with one-based indices + when used from within the expression parser. +- When adding or removing dimensions when resizing a matrix, the dimensions + are added/removed from the inner side (right) instead of outer side (left). +- Improved index out of range errors. +- Fixed function `concat` not accepting a `BigNumber` for parameter `dim`. +- Function `squeeze` now squeezes both inner and outer singleton dimensions. +- Output of getting a matrix subset is not automatically squeezed anymore + except for scalar output. +- Renamed `FunctionNode` to `FunctionAssignmentNode`, and renamed `ParamsNode` + to `FunctionNode` for more clarity. +- Fixed broken auto completion in CLI. +- Some minor fixes. + + +## 2014-07-01, version 0.25.0 + +- The library now immediately returns a default instance of mathjs, there is + no need to instantiate math.js in a separate step unless one ones to set + configuration options: + + // instead of: + var mathjs = require('mathjs'), // load math.js + math = mathjs(); // create an instance + + // just do: + var math = require('mathjs'); +- Implemented support for implicit multiplication, like `math.eval('2a', {a:3})` + and `math.eval('(2+3)(1-3)')`. This changes behavior of matrix indexes as + well: an expression like `[...][...]` is not evaluated as taking a subset of + the first matrix, but as an implicit multiplication of two matrices. +- Removed utility function `ifElse`. This function is redundant now the + expression parser has a conditional operator `a ? b : c`. +- Fixed a bug with multiplying a number with a temperature, + like `math.eval('10 * celsius')`. +- Fixed a bug with symbols having value `undefined` not being evaluated. + + +## 2014-06-20, version 0.24.1 + +- Something went wrong with publishing on npm. + + +## 2014-06-20, version 0.24.0 + +- Added constant `null`. +- Functions `equal` and `unequal` support `null` and `undefined` now. +- Function `typeof` now recognizes regular expressions as well. +- Objects `Complex`, `Unit`, and `Help` now return their string representation + when calling `.valueOf()`. +- Changed the default number of significant digits for BigNumbers from 20 to 64. +- Changed the behavior of the conditional operator (a ? b : c) to lazy + evaluating. +- Fixed imported, wrapped functions not accepting `null` and `undefined` as + function arguments. + + +## 2014-06-10, version 0.23.0 + +- Renamed some functions (everything now has a logical, camel case name): + - Renamed functions `edivide`, `emultiply`, and `epow` to `dotDivide`, + `dotMultiply`, and `dotPow` respectively. + - Renamed functions `smallereq` and `largereq` to `smallerEq` and `largerEq`. + - Renamed function `unary` to `unaryMinus` and added support for strings. +- `end` is now a reserved keyword which cannot be used as function or symbol + name in the expression parser, and is not allowed in the scope against which + an expression is evaluated. +- Implemented function `unaryPlus` and unary plus operator. +- Implemented function `deepEqual` for matrix comparisons. +- Added constant `phi`, the golden ratio (`phi = 1.618...`). +- Added constant `version`, returning the version number of math.js as string. +- Added unit `drop` (`gtt`). +- Fixed not being able to load math.js using AMD/require.js. +- Changed signature of `math.parse(expr, nodes)` to `math.parse(expr, options)` + where `options: {nodes: Object.}` +- Removed matrix support from conditional function `ifElse`. +- Removed automatic assignment of expression results to variable `ans`. + This functionality can be restored by pre- or postprocessing every evaluation, + something like: + + function evalWithAns (expr, scope) { + var ans = math.eval(expr, scope); + if (scope) { + scope.ans = ans; + } + return ans; + } + + +## 2014-05-22, version 0.22.0 + +- Implemented support to export expressions to LaTeX. Thanks Niels Heisterkamp + (@nheisterkamp). +- Output of matrix multiplication is now consistently squeezed. +- Added reference documentation in the section /docs/reference. +- Fixed a bug in multiplying units without value with a number (like `5 * cm`). +- Fixed a bug in multiplying two matrices containing vectors (worked fine for + arrays). +- Fixed random functions not accepting Matrix as input, and always returning + a Matrix as output. + + +## 2014-05-13, version 0.21.1 + +- Removed `crypto` library from the bundle. +- Deprecated functions `Parser.parse` and `Parser.compile`. Use + `math.parse` and `math.compile` instead. +- Fixed function `add` not adding strings and matrices element wise. +- Fixed parser not being able to evaluate an exponent followed by a unary minus + like `2^-3`, and a transpose followed by an index like `[3]'[1]`. + + +## 2014-04-24, version 0.21.0 + +- Implemented trigonometric hyperbolic functions `cosh`, `coth`, `csch`, + `sech`, `sinh`, `tanh`. Thanks Rogelio J. Baucells (@rjbaucells). +- Added property `type` to all expression nodes in an expression tree. +- Fixed functions `log`, `log10`, `pow`, and `sqrt` not supporting complex + results from BigNumber input (like `sqrt(bignumber(-4))`). + + +## 2014-04-16, version 0.20.0 + +- Switched to module `decimal.js` for BigNumber support, instead of + `bignumber.js`. +- Implemented support for polar coordinates to the `Complex` datatype. + Thanks Finn Pauls (@finnp). +- Implemented BigNumber support for functions `exp`, `log`, and `log10`. +- Implemented conditional operator `a ? b : c` in expression parser. +- Improved floating point comparison: the functions now check whether values + are nearly equal, against a configured maximum relative difference `epsilon`. + Thanks Rogelio J. Baucells (@rjbaucells). +- Implemented function `norm`. Thanks Rogelio J. Baucells (@rjbaucells). +- Improved function `ifElse`, is now specified for special data types too. +- Improved function `det`. Thanks Bryan Cuccioli (@bcuccioli). +- Implemented `BigNumber` support for functions `det` and `diag`. +- Added unit alias `lbs` (pound mass). +- Changed configuration option `decimals` to `precision` (applies to BigNumbers + only). +- Fixed support for element-wise comparisons between a string and a matrix. +- Fixed: expression parser now trows IndexErrors with one-based indices instead + of zero-based. +- Minor bug fixes. + + +## 2014-03-30, version 0.19.0 + +- Implemented functions `compare`, `sum`, `prod`, `var`, `std`, `median`. +- Implemented function `ifElse` Thanks @mtraynham. +- Minor bug fixes. + + +## 2014-02-15, version 0.18.1 + +- Added unit `feet`. +- Implemented function `compile` (shortcut for parsing and then compiling). +- Improved performance of function `pow` for matrices. Thanks @hamadu. +- Fixed broken auto completion in the command line interface. +- Fixed an error in function `combinations` for large numbers, and + improved performance of both functions `combinations` and `permutations`. + + +## 2014-01-18, version 0.18.0 + +- Changed matrix index notation of expression parser from round brackets to + square brackets, for example `A[1, 1:3]` instead of `A(1, 1:3)`. +- Removed need to use the `function` keyword for function assignments in the + expression parser, you can define a function now like `f(x) = x^2`. +- Implemented a compilation step in the expression parser: expressions are + compiled into JavaScript, giving much better performance (easily 10x as fast). +- Renamed unit conversion function and operator `in` to `to`. Operator `in` is + still available in the expression parser as an alias for `to`. Added unit + `in`, an abbreviation for `inch`. Thanks Elijah Insua (@tmpvar). +- Added plurals and aliases for units. +- Implemented an argument `includeEnd` for function `range` (false by default). +- Ranges in the expression parser now support big numbers. +- Implemented functions `permutations` and `combinations`. + Thanks Daniel Levin (@daniel-levin). +- Added lower case abbreviation `l` for unit litre. + + +## 2013-12-19, version 0.17.1 + +- Fixed a bug with negative temperatures. +- Fixed a bug with prefixes of units squared meter `m2` and cubic meter `m3`. + + +## 2013-12-12, version 0.17.0 + +- Renamed and flattened configuration settings: + - `number.defaultType` is now `number`. + - `number.precision` is now `decimals`. + - `matrix.defaultType` is now `matrix`. +- Function `multiply` now consistently outputs a complex number on complex input. +- Fixed `mod` and `in` not working as function (only as operator). +- Fixed support for old browsers (IE8 and older), compatible when using es5-shim. +- Fixed support for Java's ScriptEngine. + + +## 2013-11-28, version 0.16.0 + +- Implemented BigNumber support for arbitrary precision calculations. + Added settings `number.defaultType` and `number.precision` to configure + big numbers. +- Documentation is extended. +- Removed utility functions `isScalar`, `toScalar`, `isVector`, `toVector` + from `Matrix` and `Range`. Use `math.squeeze` and `math.size` instead. +- Implemented functions `get` and `set` on `Matrix`, for easier and faster + retrieval/replacement of elements in a matrix. +- Implemented function `resize`, handling matrices, scalars, and strings. +- Functions `ones` and `zeros` now return an empty matrix instead of a + number 1 or 0 when no arguments are provided. +- Implemented functions `min` and `max` for `Range` and `Index`. +- Resizing matrices now leaves new elements undefined by default instead of + filling them with zeros. Function `resize` now has an extra optional + parameter `defaultValue`. +- Range operator `:` in expression parser has been given a higher precedence. +- Functions don't allow arguments of unknown type anymore. +- Options be set when constructing a math.js instance or using the new function + `config(options`. Options are no longer accessible via `math.options`. +- Renamed `scientific` notation to `exponential` in function `format`. +- Function `format` outputs exponential notation with positive exponents now + always with `+` sign, so outputs `2.1e+3` instead of `2.1e3`. +- Fixed function `squeeze` not being able squeeze into a scalar. +- Some fixes and performance improvements in the `resize` and `subset` + functions. +- Function `size` now adheres to the option `matrix.defaultType` for scalar + input. +- Minor bug fixes. + + +## 2013-10-26, version 0.15.0 + +- Math.js must be instantiated now, static calls are no longer supported. Usage: + - node.js: `var math = require('mathjs')();` + - browser: `var math = mathjs();` +- Implemented support for multiplying vectors with matrices. +- Improved number formatting: + - Function `format` now support various options: precision, different + notations (`fixed`, `scientific`, `auto`), and more. + - Numbers are no longer rounded to 5 digits by default when formatted. + - Implemented a function `format` for `Matrix`, `Complex`, `Unit`, `Range`, + and `Selector` to format using options. + - Function `format` does only stringify values now, and has a new parameter + `precision` to round to a specific number of digits. + - Removed option `math.options.precision`, + use `math.format(value [, precision])` instead. + - Fixed formatting numbers as scientific notation in some cases returning + a zero digit left from the decimal point. (like "0.33333e8" rather than + "3.3333e7"). Thanks @husayt. +- Implemented a function `print` to interpolate values in a template string, + this functionality was moved from the function `format`. +- Implemented statistics function `mean`. Thanks Guillermo Indalecio Fernandez + (@guillermobox). +- Extended and changed `max` and `min` for multi dimensional matrices: they now + return the maximum and minimum of the flattened array. An optional second + argument `dim` allows to calculate the `max` or `min` for specified dimension. +- Renamed option `math.options.matrix.default` to + `math.options.matrix.defaultType`. +- Removed support for comparing complex numbers in functions `smaller`, + `smallereq`, `larger`, `largereq`. Complex numbers cannot be ordered. + + +## 2013-10-08, version 0.14.0 + +- Introduced an option `math.options.matrix.default` which can have values + `matrix` (default) or `array`. This option is used by the functions `eye`, + `ones`, `range`, and `zeros`, to determine the type of matrix output. +- Getting a subset of a matrix will automatically squeeze the resulting subset, + setting a subset of a matrix will automatically unsqueeze the given subset. +- Removed concatenation of nested arrays in the expression parser. + You can now input nested arrays like in JavaScript. Matrices can be + concatenated using the function `concat`. +- The matrix syntax `[...]` in the expression parser now creates 1 dimensional + matrices by default. `math.eval('[1,2,3,4]')` returns a matrix with + size `[4]`, `math.eval('[1,2;3,4]')` returns a matrix with size `[2,2]`. +- Documentation is restructured and extended. +- Fixed non working operator `mod` (modulus operator). + + +## 2013-09-03, version 0.13.0 + +- Implemented support for booleans in all relevant functions. +- Implemented functions `map` and `forEach`. Thanks Sebastien Piquemal (@sebpic). +- All construction functions can be used to convert the type of variables, + also element-wise for all elements in an Array or Matrix. +- Changed matrix indexes of the expression parser to one-based with the + upper-bound included, similar to most math applications. Note that on a + JavaScript level, math.js uses zero-based indexes with excluded upper-bound. +- Removed support for scalars in the function `subset`, it now only supports + Array, Matrix, and String. +- Removed the functions `get` and `set` from a selector, they are a duplicate + of the function `subset`. +- Replaced functions `get` and `set` of `Matrix` with a single function + `subset`. +- Some moving around with code and namespaces: + - Renamed namespace `math.expr` to `math.expression` (contains Scope, Parser, + node objects). + - Renamed namespace `math.docs` to `math.expression.docs`. + - Moved `math.expr.Selector` to `math.chaining.Selector`. +- Fixed some edge cases in functions `lcm` and `xgcd`. + + +## 2013-08-22, version 0.12.1 + +- Fixed outdated version of README.md. +- Fixed a broken unit test. + + +## 2013-08-22, version 0.12.0 + +- Implemented functions `random([min, max])`, `randomInt([min, max])`, + `pickRandom(array)`. Thanks Sebastien Piquemal (@sebpic). +- Implemented function `distribution(name)`, generating a distribution object + with functions `random`, `randomInt`, `pickRandom` for different + distributions. Currently supporting `uniform` and `normal`. +- Changed the behavior of `range` to exclude the upper bound, so `range(1, 4)` + now returns `[1, 2, 3]` instead of `[1, 2, 3, 4]`. +- Changed the syntax of `range`, which is now `range(start, end [, step])` + instead of `range(start, [step, ] end)`. +- Changed the behavior of `ones` and `zeros` to geometric dimensions, for + example `ones(3)` returns a vector with length 3, filled with ones, and + `ones(3,3)` returns a 2D array with size [3, 3]. +- Changed the return type of `ones` and `zeros`: they now return an Array when + arguments are Numbers or an Array, and returns a Matrix when the argument + is a Matrix. +- Change matrix index notation in parser from round brackets to square brackets, + for example `A[0, 0:3]`. +- Removed the feature introduced in v0.10.0 to automatically convert a complex + value with an imaginary part equal to zero to a number. +- Fixed zeros being formatted as null. Thanks @TimKraft. + + +## 2013-07-23, version 0.11.1 + +- Fixed missing development dependency + + +## 2013-07-23, version 0.11.0 + +- Changed math.js from one-based to zero-based indexes. + - Getting and setting matrix subset is now zero-based. + - The dimension argument in function `concat` is now zero-based. +- Improvements in the string output of function help. +- Added constants `true` and `false`. +- Added constructor function `boolean`. +- Fixed function `select` not accepting `0` as input. + Thanks Elijah Manor (@elijahmanor). +- Parser now supports multiple unary minus operators after each other. +- Fixed not accepting empty matrices like `[[], []]`. +- Some fixes in the end user documentation. + + +## 2013-07-08, version 0.10.0 + +- For complex calculations, all functions now automatically replace results + having an imaginary part of zero with a Number. (`2i * 2i` now returns a + Number `-4` instead of a Complex `-4 + 0i`). +- Implemented support for injecting custom node handlers in the parser. Can be + used for example to implement a node handler for plotting a graph. +- Implemented end user documentation and a new `help` function. +- Functions `size` and `squeeze` now return a Matrix instead of an Array as + output on Matrix input. +- Added a constant tau (2 * pi). Thanks Zak Zibrat (@palimpsests). +- Renamed function `unaryminus` to `unary`. +- Fixed a bug in determining node dependencies in function assignments. + + +## 2013-06-14, version 0.9.1 + +- Implemented element-wise functions and operators: `emultiply` (`x .* y`), + `edivide` (`x ./ y`), `epow` (`x .^ y`). +- Added constants `Infinity` and `NaN`. +- Removed support for Workspace to keep the library focused on its core task. +- Fixed a bug in the Complex constructor, not accepting NaN values. +- Fixed division by zero in case of pure complex values. +- Fixed a bug in function multiply multiplying a pure complex value with + Infinity. + + +## 2013-05-29, version 0.9.0 + +- Implemented function `math.parse(expr [,scope])`. Optional parameter scope can + be a plain JavaScript Object containing variables. +- Extended function `math.expr(expr [, scope])` with an additional parameter + `scope`, similar to `parse`. Example: `math.eval('x^a', {x:3, a:2});`. +- Implemented function `subset`, to get or set a subset from a matrix, string, + or other data types. +- Implemented construction functions number and string (mainly useful inside + the parser). +- Improved function `det`. Thanks Bryan Cuccioli (@bcuccioli). +- Moved the parse code from prototype math.expr.Parser to function math.parse, + simplified Parser a little bit. +- Strongly simplified the code of Scope and Workspace. +- Fixed function mod for negative numerators, and added error messages in case + of wrong input. + + +## 2013-05-18, version 0.8.2 + +- Extended the import function and some other minor improvements. +- Fixed a bug in merging one dimensional vectors into a matrix. +- Fixed a bug in function subtract, when subtracting a complex number from a + real number. + + +## 2013-05-10, version 0.8.1 + +- Fixed an npm warning when installing mathjs globally. + + +## 2013-05-10, version 0.8.0 + +- Implemented a command line interface. When math.js is installed globally via + npm, the application is available on your system as 'mathjs'. +- Implemented `end` keyword for index operator, and added support for implicit + start and end (expressions like `a(2,:)` and `b(2:end,3:end-1)` are supported + now). +- Function math.eval is more flexible now: it supports variables and multi-line + expressions. +- Removed the read-only option from Parser and Scope. +- Fixed non-working unequal operator != in the parser. +- Fixed a bug in resizing matrices when replacing a subset. +- Fixed a bug in updating a subset of a non-existing variable. +- Minor bug fixes. + + +## 2013-05-04, version 0.7.2 + +- Fixed method unequal, which was checking for equality instead of inequality. + Thanks @FJS2. + + +## 2013-04-27, version 0.7.1 + +- Improvements in the parser: + - Added support for chained arguments. + - Added support for chained variable assignments. + - Added a function remove(name) to remove a variable from the parsers scope. + - Renamed nodes for more consistency and to resolve naming conflicts. + - Improved stringification of an expression tree. + - Some simplifications in the code. + - Minor bug fixes. +- Fixed a bug in the parser, returning NaN instead of throwing an error for a + number with multiple decimal separators like `2.3.4`. +- Fixed a bug in Workspace.insertAfter. +- Fixed: math.js now works on IE 6-8 too. + + +## 2013-04-20, version 0.7.0 + +- Implemented method `math.eval`, which uses a readonly parser to evaluate + expressions. +- Implemented method `xgcd` (extended eucledian algorithm). Thanks Bart Kiers + (@bkiers). +- Improved math.format, which now rounds values to a maximum number of digits + instead of decimals (default is 5 digits, for example `math.format(math.pi)` + returns `3.1416`). +- Added examples. +- Changed methods square and cube to evaluate matrices element wise (consistent + with all other methods). +- Changed second parameter of method import to an object with options. +- Fixed method math.typeof on IE. +- Minor bug fixes and improvements. + + +## 2013-04-13, version 0.6.0 + +- Implemented chained operations via method math.select(). For example + `math.select(3).add(4).subtract(2).done()` will return `5`. +- Implemented methods gcd and lcm. +- Implemented method `Unit.in(unit)`, which creates a clone of the unit with a + fixed representation. For example `math.unit('5.08 cm').in('inch')` will + return a unit which string representation always is in inch, thus `2 inch`. + `Unit.in(unit)` is the same as method `math.in(x, unit)`. +- Implemented `Unit.toNumber(unit)`, which returns the value of the unit when + represented with given unit. For example + `math.unit('5.08 cm').toNumber('inch')` returns the number `2`, as the + representation of the unit in inches has 2 as value. +- Improved: method `math.in(x, unit)` now supports a string as second parameter, + for example `math.in(math.unit('5.08 cm'), 'inch')`. +- Split the end user documentation of the parser functions from the source + files. +- Removed function help and the built-in documentation from the core library. +- Fixed constant i being defined as -1i instead of 1i. +- Minor bug fixes. + + +## 2013-04-06, version 0.5.0 + +- Implemented data types Matrix and Range. +- Implemented matrix methods clone, concat, det, diag, eye, inv, ones, size, + squeeze, transpose, zeros. +- Implemented range operator `:`, and transpose operator `'` in parser. +- Changed: created construction methods for easy object creation for all data + types and for the parser. For example, a complex value is now created + with `math.complex(2, 3)` instead of `new math.Complex(2, 3)`, and a parser + is now created with `math.parser()` instead of `new math.parser.Parser()`. +- Changed: moved all data types under the namespace math.type, and moved the + Parser, Workspace, etc. under the namespace math.expr. +- Changed: changed operator precedence of the power operator: + - it is now right associative instead of left associative like most scripting + languages. So `2^3^4` is now calculated as `2^(3^4)`. + - it has now higher precedence than unary minus most languages, thus `-3^2` is + now calculated as `-(3^2)`. +- Changed: renamed the parsers method 'put' into 'set'. +- Fixed: method 'in' did not check for units to have the same base. + + +## 2013-03-16, version 0.4.0 + +- Implemented Array support for all methods. +- Implemented Array support in the Parser. +- Implemented method format. +- Implemented parser for units, math.Unit.parse(str). +- Improved parser for complex values math.Complex.parse(str); +- Improved method help: it now evaluates the examples. +- Fixed: a scoping issue with the Parser when defining functions. +- Fixed: method 'typeof' was not working well with minified and mangled code. +- Fixed: errors in determining the best prefix for a unit. + + +## 2013-03-09, version 0.3.0 + +- Implemented Workspace +- Implemented methods cot, csc, sec. +- Implemented Array support for methods with one parameter. + + +## 2013-02-25, version 0.2.0 + +- Parser, Scope, and expression tree with Nodes implemented. +- Implemented method import which makes it easy to extend math.js. +- Implemented methods arg, conj, cube, equal, factorial, im, largereq, + log(x, base), log10, mod, re, sign, smallereq, square, unequal. + + +## 2013-02-18, version 0.1.0 + +- Reached full compatibility with Javascripts built-in Math library. +- More functions implemented. +- Some bugfixes. + + +## 2013-02-16, version 0.0.2 + +- All constants of Math implemented, plus the imaginary unit i. +- Data types Complex and Unit implemented. +- First set of functions implemented. + + +## 2013-02-15, version 0.0.1 + +- First publish of the mathjs package. (package is still empty) diff --git a/node_modules/mathjs/LICENSE b/node_modules/mathjs/LICENSE new file mode 100644 index 0000000..9cf8c11 --- /dev/null +++ b/node_modules/mathjs/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/node_modules/mathjs/NOTICE b/node_modules/mathjs/NOTICE new file mode 100644 index 0000000..3da7407 --- /dev/null +++ b/node_modules/mathjs/NOTICE @@ -0,0 +1,16 @@ +math.js +https://github.com/josdejong/mathjs + +Copyright (C) 2013-2022 Jos de Jong + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/mathjs/README.md b/node_modules/mathjs/README.md new file mode 100644 index 0000000..8a88a1b --- /dev/null +++ b/node_modules/mathjs/README.md @@ -0,0 +1,197 @@ +![math.js](https://raw.github.com/josdejong/mathjs/master/misc/img/mathjs.png) + +[https://mathjs.org](https://mathjs.org) + +Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with different data types like numbers, big numbers, complex numbers, fractions, units, and matrices. Powerful and easy to use. + +[![Version](https://img.shields.io/npm/v/mathjs.svg)](https://www.npmjs.com/package/mathjs) +[![Downloads](https://img.shields.io/npm/dm/mathjs.svg)](https://www.npmjs.com/package/mathjs) +[![Build Status](https://github.com/josdejong/mathjs/workflows/Node.js%20CI/badge.svg)](https://github.com/josdejong/mathjs/actions) +[![Maintenance](https://img.shields.io/maintenance/yes/2022.svg)](https://github.com/josdejong/mathjs/graphs/commit-activity) +[![License](https://img.shields.io/github/license/josdejong/mathjs.svg)](https://github.com/josdejong/mathjs/blob/master/LICENSE) +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fjosdejong%2Fmathjs.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fjosdejong%2Fmathjs?ref=badge_shield) +[![Codecov](https://codecov.io/gh/josdejong/mathjs/branch/develop/graph/badge.svg)](https://codecov.io/gh/josdejong/mathjs) +[![Github Sponsor](https://camo.githubusercontent.com/7d9333b097b2f54a8957d126ab82937811489c9b75c3850f609985cf94cd29fe/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f2532302d53706f6e736f722532306d652532306f6e2532304769744875622d6f72616e6765)](https://github.com/sponsors/josdejong) + +## Features + +- Supports numbers, big numbers, complex numbers, fractions, units, strings, arrays, and matrices. +- Is compatible with JavaScript's built-in Math library. +- Contains a flexible expression parser. +- Does symbolic computation. +- Comes with a large set of built-in functions and constants. +- Can be used as a command line application as well. +- Runs on any JavaScript engine. +- Is easily extensible. +- Open source. + +## Usage + +Math.js can be used in both node.js and in the browser. + +Install math.js using [npm](https://www.npmjs.com/package/mathjs): + + npm install mathjs + +Or download mathjs via one of the CDN's listed on the downloads page: + +    [https://mathjs.org/download.html](https://mathjs.org/download.html#download) + +Math.js can be used similar to JavaScript's built-in Math library. Besides that, +math.js can evaluate +[expressions](https://mathjs.org/docs/expressions/index.html) +and supports +[chained operations](https://mathjs.org/docs/core/chaining.html). + +```js +import { + atan2, chain, derivative, e, evaluate, log, pi, pow, round, sqrt +} from 'mathjs' + +// functions and constants +round(e, 3) // 2.718 +atan2(3, -3) / pi // 0.75 +log(10000, 10) // 4 +sqrt(-4) // 2i +pow([[-1, 2], [3, 1]], 2) // [[7, 0], [0, 7]] +derivative('x^2 + x', 'x') // 2 * x + 1 + +// expressions +evaluate('12 / (2.3 + 0.7)') // 4 +evaluate('12.7 cm to inch') // 5 inch +evaluate('sin(45 deg) ^ 2') // 0.5 +evaluate('9 / 3 + 2i') // 3 + 2i +evaluate('det([-1, 2; 3, 1])') // -7 + +// chaining +chain(3) + .add(4) + .multiply(2) + .done() // 14 +``` + +See the [Getting Started](https://mathjs.org/docs/getting_started.html) for a more detailed tutorial. + + +## Browser support + +Math.js works on any ES5 compatible JavaScript engine: node.js, Chrome, Firefox, Safari, Edge, and IE11. + + +## Documentation + +- [Getting Started](https://mathjs.org/docs/getting_started.html) +- [Examples](https://mathjs.org/examples/index.html) +- [Overview](https://mathjs.org/docs/index.html) +- [History](https://mathjs.org/history.html) + + +## Build + +First clone the project from github: + + git clone git://github.com/josdejong/mathjs.git + cd mathjs + +Install the project dependencies: + + npm install + +Then, the project can be build by executing the build script via npm: + + npm run build + +This will build ESM output, CommonJS output, and the bundle math.js +from the source files and put them in the folder lib. + + +## Develop + +When developing new features for mathjs, it is good to be aware of the following background information. + +### Code + +The code of `mathjs` is written in ES modules, and requires all files to have a real, relative path, meaning the files must have a `*.js` extension. Please configure adding file extensions on auto import in your IDE. + +### Architecture + +What mathjs tries to achieve is to offer an environment where you can do calculations with mixed data types, +like multiplying a regular `number` with a `Complex` number or a `BigNumber`, and work with all of those in matrices. +Mathjs also allows to add a new data type, like say `BigInt`, with little effort. + +The solution that mathjs uses has two main ingredients: + +- **Typed functions**. All functions are created using [`typed-function`](https://github.com/josdejong/typed-function/). This makes it easier to (dynamically) create and extend a single function with new data types, automatically do type conversions on function inputs, etc. So, if you create function multiply for two `number`s, you can extend it with support for multiplying two `BigInts`. If you define a conversion from `BigInt` to `number`, the typed-function will automatically allow you to multiply a `BigInt` with a `number`. + +- **Dependency injection**. When we have a function `multiply` with support for `BigInt`, thanks to the dependency injection, other functions using `multiply` under the hood, like `prod`, will automatically support `BigInt` too. This also works the other way around: if you don't need the heavyweight `multiply` (which supports BigNumbers, matrices, etc), and you just need a plain and simple number support, you can use a lightweight implementation of `multiply` just for numbers, and inject that in `prod` and other functions. + +At the lowest level, mathjs has immutable factory functions which create immutable functions. The core function `math.create(...)` creates a new instance having functions created from all passed factory functions. A mathjs instance is a collection of created functions. It contains a function like `math.import` to allow extending the instance with new functions, which can then be used in the expression parser. + +### Build scripts + +The build script currently generates two types of output: + +- **any**, generate entry points to create full versions of all functions +- **number**: generating and entry points to create lightweight functions just supporting `number` + +For each function, an object is generated containing the factory functions of all dependencies of the function. This allows to just load a specific set of functions, and not load or bundle any other functionality. So for example, to just create function `add` you can do `math.create(addDependencies)`. + + +## Test + +To execute tests for the library, install the project dependencies once: + + npm install + +Then, the tests can be executed: + + npm test + +Additionally, the tests can be run on FireFox using [headless mode](https://developer.mozilla.org/en-US/Firefox/Headless_mode): + + npm run test:browser + +To run the tests remotely on BrowserStack, first set the environment variables `BROWSER_STACK_USERNAME` and `BROWSER_STACK_ACCESS_KEY` with your username and access key and then execute: + + npm run test:browserstack + +You can separately run the code linter, though it is also executed with `npm test`: + + npm run lint + +To automatically fix linting issue, run: + + npm run format + +To test code coverage of the tests: + + npm run coverage + +To see the coverage results, open the generated report in your browser: + + ./coverage/lcov-report/index.html + + +### Continuous integration testing + +Continuous integration tests are run on [Github Actions](https://github.com/josdejong/mathjs/actions) and [BrowserStack](https://www.browserstack.com) every time a commit is pushed to github. Github Actions runs the tests for different versions of node.js, and BrowserStack runs the tests on all major browsers. + +[![BrowserStack](https://raw.github.com/josdejong/mathjs/master/misc/browserstack.png)](https://www.browserstack.com) + +Thanks Github Actions and BrowserStack for the generous free hosting of this open source project! + +## License + +Copyright (C) 2013-2022 Jos de Jong + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/mathjs/bin/cli.js b/node_modules/mathjs/bin/cli.js new file mode 100755 index 0000000..618006d --- /dev/null +++ b/node_modules/mathjs/bin/cli.js @@ -0,0 +1,432 @@ +#!/usr/bin/env node +/** + * math.js + * https://github.com/josdejong/mathjs + * + * Math.js is an extensive math library for JavaScript and Node.js, + * It features real and complex numbers, units, matrices, a large set of + * mathematical functions, and a flexible expression parser. + * + * Usage: + * + * mathjs [scriptfile(s)] {OPTIONS} + * + * Options: + * + * --version, -v Show application version + * --help, -h Show this message + * --tex Generate LaTeX instead of evaluating + * --string Generate string instead of evaluating + * --parenthesis= Set the parenthesis option to + * either of "keep", "auto" and "all" + * + * Example usage: + * mathjs Open a command prompt + * mathjs 1+2 Evaluate expression + * mathjs script.txt Run a script file + * mathjs script1.txt script2.txt Run two script files + * mathjs script.txt > results.txt Run a script file, output to file + * cat script.txt | mathjs Run input stream + * cat script.txt | mathjs > results.txt Run input stream, output to file + * + * @license + * Copyright (C) 2013-2022 Jos de Jong + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +const fs = require('fs') +const path = require('path') +const { createEmptyMap } = require('../lib/cjs/utils/map.js') +let scope = createEmptyMap() + +const PRECISION = 14 // decimals + +/** + * "Lazy" load math.js: only require when we actually start using it. + * This ensures the cli application looks like it loads instantly. + * When requesting help or version number, math.js isn't even loaded. + * @return {*} + */ +function getMath () { + return require('../lib/cjs/defaultInstance.js').default +} + +/** + * Helper function to format a value. Regular numbers will be rounded + * to 14 digits to prevent round-off errors from showing up. + * @param {*} value + */ +function format (value) { + const math = getMath() + + return math.format(value, { + fn: function (value) { + if (typeof value === 'number') { + // round numbers + return math.format(value, PRECISION) + } else { + return math.format(value) + } + } + }) +} + +/** + * auto complete a text + * @param {String} text + * @return {[Array, String]} completions + */ +function completer (text) { + const math = getMath() + let matches = [] + let keyword + const m = /[a-zA-Z_0-9]+$/.exec(text) + if (m) { + keyword = m[0] + + // scope variables + for (const def in scope.keys()) { + if (def.indexOf(keyword) === 0) { + matches.push(def) + } + } + + // commandline keywords + ['exit', 'quit', 'clear'].forEach(function (cmd) { + if (cmd.indexOf(keyword) === 0) { + matches.push(cmd) + } + }) + + // math functions and constants + const ignore = ['expr', 'type'] + for (const func in math.expression.mathWithTransform) { + if (hasOwnProperty(math.expression.mathWithTransform, func)) { + if (func.indexOf(keyword) === 0 && ignore.indexOf(func) === -1) { + matches.push(func) + } + } + } + + // units + const Unit = math.Unit + for (const name in Unit.UNITS) { + if (hasOwnProperty(Unit.UNITS, name)) { + if (name.indexOf(keyword) === 0) { + matches.push(name) + } + } + } + for (const name in Unit.PREFIXES) { + if (hasOwnProperty(Unit.PREFIXES, name)) { + const prefixes = Unit.PREFIXES[name] + for (const prefix in prefixes) { + if (hasOwnProperty(prefixes, prefix)) { + if (prefix.indexOf(keyword) === 0) { + matches.push(prefix) + } else if (keyword.indexOf(prefix) === 0) { + const unitKeyword = keyword.substring(prefix.length) + for (const n in Unit.UNITS) { + if (hasOwnProperty(Unit.UNITS, n)) { + if (n.indexOf(unitKeyword) === 0 && + Unit.isValuelessUnit(prefix + n)) { + matches.push(prefix + n) + } + } + } + } + } + } + } + } + + // remove duplicates + matches = matches.filter(function (elem, pos, arr) { + return arr.indexOf(elem) === pos + }) + } + + return [matches, keyword] +} + +/** + * Run stream, read and evaluate input and stream that to output. + * Text lines read from the input are evaluated, and the results are send to + * the output. + * @param input Input stream + * @param output Output stream + * @param mode Output mode + * @param parenthesis Parenthesis option + */ +function runStream (input, output, mode, parenthesis) { + const readline = require('readline') + const rl = readline.createInterface({ + input: input || process.stdin, + output: output || process.stdout, + completer: completer + }) + + if (rl.output.isTTY) { + rl.setPrompt('> ') + rl.prompt() + } + + // load math.js now, right *after* loading the prompt. + const math = getMath() + + // TODO: automatic insertion of 'ans' before operators like +, -, *, / + + rl.on('line', function (line) { + const expr = line.trim() + + switch (expr.toLowerCase()) { + case 'quit': + case 'exit': + // exit application + rl.close() + break + case 'clear': + // clear memory + scope = createEmptyMap() + console.log('memory cleared') + + // get next input + if (rl.output.isTTY) { + rl.prompt() + } + break + default: + if (!expr) { + break + } + switch (mode) { + case 'evaluate': + // evaluate expression + try { + let node = math.parse(expr) + let res = node.evaluate(scope) + + if (math.isResultSet(res)) { + // we can have 0 or 1 results in the ResultSet, as the CLI + // does not allow multiple expressions separated by a return + res = res.entries[0] + node = node.blocks + .filter(function (entry) { return entry.visible }) + .map(function (entry) { return entry.node })[0] + } + + if (node) { + if (math.isAssignmentNode(node)) { + const name = findSymbolName(node) + if (name !== null) { + const value = scope.get(name) + scope.set('ans', value) + console.log(name + ' = ' + format(value)) + } else { + scope.set('ans', res) + console.log(format(res)) + } + } else if (math.isHelp(res)) { + console.log(res.toString()) + } else { + scope.set('ans', res) + console.log(format(res)) + } + } + } catch (err) { + console.log(err.toString()) + } + break + + case 'string': + try { + const string = math.parse(expr).toString({ parenthesis: parenthesis }) + console.log(string) + } catch (err) { + console.log(err.toString()) + } + break + + case 'tex': + try { + const tex = math.parse(expr).toTex({ parenthesis: parenthesis }) + console.log(tex) + } catch (err) { + console.log(err.toString()) + } + break + } + } + + // get next input + if (rl.output.isTTY) { + rl.prompt() + } + }) + + rl.on('close', function () { + console.log() + process.exit(0) + }) +} + +/** + * Find the symbol name of an AssignmentNode. Recurses into the chain of + * objects to the root object. + * @param {AssignmentNode} node + * @return {string | null} Returns the name when found, else returns null. + */ +function findSymbolName (node) { + const math = getMath() + let n = node + + while (n) { + if (math.isSymbolNode(n)) { + return n.name + } + n = n.object + } + + return null +} + +/** + * Output application version number. + * Version number is read version from package.json. + */ +function outputVersion () { + fs.readFile(path.join(__dirname, '/../package.json'), function (err, data) { + if (err) { + console.log(err.toString()) + } else { + const pkg = JSON.parse(data) + const version = pkg && pkg.version ? pkg.version : 'unknown' + console.log(version) + } + process.exit(0) + }) +} + +/** + * Output a help message + */ +function outputHelp () { + console.log('math.js') + console.log('https://mathjs.org') + console.log() + console.log('Math.js is an extensive math library for JavaScript and Node.js. It features ') + console.log('real and complex numbers, units, matrices, a large set of mathematical') + console.log('functions, and a flexible expression parser.') + console.log() + console.log('Usage:') + console.log(' mathjs [scriptfile(s)|expression] {OPTIONS}') + console.log() + console.log('Options:') + console.log(' --version, -v Show application version') + console.log(' --help, -h Show this message') + console.log(' --tex Generate LaTeX instead of evaluating') + console.log(' --string Generate string instead of evaluating') + console.log(' --parenthesis= Set the parenthesis option to') + console.log(' either of "keep", "auto" and "all"') + console.log() + console.log('Example usage:') + console.log(' mathjs Open a command prompt') + console.log(' mathjs 1+2 Evaluate expression') + console.log(' mathjs script.txt Run a script file') + console.log(' mathjs script.txt script2.txt Run two script files') + console.log(' mathjs script.txt > results.txt Run a script file, output to file') + console.log(' cat script.txt | mathjs Run input stream') + console.log(' cat script.txt | mathjs > results.txt Run input stream, output to file') + console.log() + process.exit(0) +} + +/** + * Process input and output, based on the command line arguments + */ +const scripts = [] // queue of scripts that need to be processed +let mode = 'evaluate' // one of 'evaluate', 'tex' or 'string' +let parenthesis = 'keep' +let version = false +let help = false + +process.argv.forEach(function (arg, index) { + if (index < 2) { + return + } + + switch (arg) { + case '-v': + case '--version': + version = true + break + + case '-h': + case '--help': + help = true + break + + case '--tex': + mode = 'tex' + break + + case '--string': + mode = 'string' + break + + case '--parenthesis=keep': + parenthesis = 'keep' + break + + case '--parenthesis=auto': + parenthesis = 'auto' + break + + case '--parenthesis=all': + parenthesis = 'all' + break + + // TODO: implement configuration via command line arguments + + default: + scripts.push(arg) + } +}) + +if (version) { + outputVersion() +} else if (help) { + outputHelp() +} else if (scripts.length === 0) { + // run a stream, can be user input or pipe input + runStream(process.stdin, process.stdout, mode, parenthesis) +} else { + fs.stat(scripts[0], function (e, f) { + if (e) { + console.log(getMath().evaluate(scripts.join(' ')).toString()) + } else { + // work through the queue of scripts + scripts.forEach(function (arg) { + // run a script file + runStream(fs.createReadStream(arg), process.stdout, mode, parenthesis) + }) + } + }) +} + +// helper function to safely check whether an object as a property +// copy from the function in object.js which is ES6 +function hasOwnProperty (object, property) { + return object && Object.hasOwnProperty.call(object, property) +} diff --git a/node_modules/mathjs/bin/package.json b/node_modules/mathjs/bin/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/mathjs/bin/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/mathjs/bin/repl.js b/node_modules/mathjs/bin/repl.js new file mode 100644 index 0000000..21c9b11 --- /dev/null +++ b/node_modules/mathjs/bin/repl.js @@ -0,0 +1,10 @@ +#!/usr/bin/env node + +/* + * This simply preloads mathjs and drops you into a REPL to + * help interactive debugging. + **/ +global.math = require('../lib/cjs/defaultInstance.js').default +const repl = require('repl') + +repl.start({ useGlobal: true }) diff --git a/node_modules/mathjs/dist/math.js b/node_modules/mathjs/dist/math.js new file mode 100644 index 0000000..b01e410 --- /dev/null +++ b/node_modules/mathjs/dist/math.js @@ -0,0 +1,3 @@ +// TODO: deprecated since v8, remove this deprecation warning in v9 +throw new Error('The non-minified file "mathjs/dist/math.js" has removed since mathjs@8.0.0. ' + + 'Please use the minified bundle "mathjs/lib/browser/math.js" instead.') diff --git a/node_modules/mathjs/dist/math.min.js b/node_modules/mathjs/dist/math.min.js new file mode 100644 index 0000000..2a2391f --- /dev/null +++ b/node_modules/mathjs/dist/math.min.js @@ -0,0 +1,3 @@ +// TODO: deprecated since v8, remove this deprecation warning in v9 +throw new Error('The file "mathjs/dist/math.min.js" has been moved to "mathjs/lib/browser/math.js" since mathjs@8.0.0. ' + + 'Please load the bundle via the new path.') diff --git a/node_modules/mathjs/dist/package.json b/node_modules/mathjs/dist/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/mathjs/dist/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/mathjs/docs/command_line_interface.md b/node_modules/mathjs/docs/command_line_interface.md new file mode 100644 index 0000000..1287e7b --- /dev/null +++ b/node_modules/mathjs/docs/command_line_interface.md @@ -0,0 +1,87 @@ +# Command Line Interface (CLI) + +When math.js is installed globally using npm, its expression parser can be used +from the command line. To install math.js globally: + +```bash +$ npm install -g mathjs +``` + +Normally, a global installation must be run with admin rights (precede the +command with `sudo`). After installation, the application `mathjs` is available +via the command line: + +```bash +$ mathjs +> 12 / (2.3 + 0.7) +4 +> 12.7 cm to inch +5 inch +> sin(45 deg) ^ 2 +0.5 +> 9 / 3 + 2i +3 + 2i +> det([-1, 2; 3, 1]) +-7 +``` + +The command line interface can be used to open a prompt, to execute a script, +or to pipe input and output streams: + +```bash +$ mathjs # Open a command prompt +$ mathjs script.txt # Run a script file, output to console +$ mathjs script1.txt script2.txt # Run two script files +$ mathjs script.txt > results.txt # Run a script file, output to file +$ cat script.txt | mathjs # Run input stream, output to console +$ cat script.txt | mathjs > results.txt # Run input stream, output to file +``` + +You can also use it to create LaTeX from or sanitize your expressions using the +`--tex` and `--string` options: + +```bash +$ mathjs --tex +> 1/2 +\frac{1}{2} +``` + +```bash +$ mathjs --string +> (1+1+1) +(1 + 1 + 1) +``` + +To change the parenthesis option use the `--parenthesis=` flag: + +```bash +$ mathjs --string --parenthesis=auto +> (1+1+1) +1 + 1 + 1 +``` + +```bash +$ mathjs --string --parenthesis=all +> (1+1+1) +(1 + 1) + 1 +``` + +# Command line debugging (REPL) + +For debugging purposes, `bin/repl.js` provides a REPL (Read Evaluate Print Loop) +for interactive testing of mathjs without having to build new build files after every +little change to the source files. You can either start it directly (`./bin/repl.js`) or +via node (`node bin/repl.js`). + +You can exit using either [ctrl]-[C] or [ctrl]-[D]. + +```bash +$ ./bin/repl.js +> math.parse('1+1') +{ op: '+', + fn: 'add', + args: + [ { value: '1', valueType: 'number' }, + { value: '1', valueType: 'number' } ] } +> +``` diff --git a/node_modules/mathjs/docs/core/chaining.md b/node_modules/mathjs/docs/core/chaining.md new file mode 100644 index 0000000..c97bcc5 --- /dev/null +++ b/node_modules/mathjs/docs/core/chaining.md @@ -0,0 +1,41 @@ +# Chaining + +Math.js supports chaining operations by wrapping a value into a `Chain`. +A chain can be created with the function `math.chain(value)` +(formerly `math.select(value)`). +All functions available in the math namespace can be executed via the chain. +The functions will be executed with the chain's value as the first argument, +followed by extra arguments provided by the function call itself. + +```js +math.chain(3) + .add(4) + .subtract(2) + .done() // 5 + +math.chain( [[1, 2], [3, 4]] ) + .subset(math.index(0, 0), 8) + .multiply(3) + .done() // [[24, 6], [9, 12]] +``` + +### API + +A `Chain` is constructed as: + +```js +math.chain() +math.chain(value) +``` + +The `Chain` has all functions available in the `math` namespace, and has +a number of special functions: + + - `done()` + Finalize the chain and return the chain's value. + - `valueOf()` + The same as `done()`, returns the chain's value. + - `toString()` + Executes `math.format(value)` onto the chain's value, returning + a string representation of the value. + diff --git a/node_modules/mathjs/docs/core/configuration.md b/node_modules/mathjs/docs/core/configuration.md new file mode 100644 index 0000000..3365794 --- /dev/null +++ b/node_modules/mathjs/docs/core/configuration.md @@ -0,0 +1,144 @@ +# Configuration + +Math.js contains a number of configuration options. +These options can be applied on a created mathjs instance and changed afterwards. + +```js +import { create, all } from 'mathjs' + +// create a mathjs instance with configuration +const config = { + epsilon: 1e-12, + matrix: 'Matrix', + number: 'number', + precision: 64, + predictable: false, + randomSeed: null +} +const math = create(all, config) + +// read the applied configuration +console.log(math.config()) + +// change the configuration +math.config({ + number: 'BigNumber' +}) +``` + +The following configuration options are available: + +- `epsilon`. The minimum relative difference used to test equality between two + compared values. This value is used by all relational functions. + Default value is `1e-12`. + +- `matrix`. The default type of matrix output for functions. + Available values are: `'Matrix'` (default) or `'Array'`. + Where possible, the type of matrix output from functions is determined from + the function input: An array as input will return an Array, a Matrix as input + will return a Matrix. In case of no matrix as input, the type of output is + determined by the option `matrix`. In case of mixed matrix + inputs, a matrix will be returned always. + +- `number`. The type of numeric output for functions which cannot + determine the numeric type from the inputs. For most functions though, + the type of output is determined from the the input: + a number as input will return a number as output, + a BigNumber as input returns a BigNumber as output. + + For example the functions `math.evaluate('2+3')`, `math.parse('2+3')`, + `math.range('1:10')`, and `math.unit('5cm')` use the `number` configuration + setting. But `math.sqrt(4)` will always return the number `2` + regardless of the `number` configuration, because the input is a number. + + Available values are: `'number'` (default), `'BigNumber'`, or `'Fraction'`. + [BigNumbers](../datatypes/bignumbers.js) have higher precision than the default + numbers of JavaScript, and [`Fractions`](../datatypes/fractions.js) store + values in terms of a numerator and denominator. + +- `precision`. The maximum number of significant digits for BigNumbers. + This setting only applies to BigNumbers, not to numbers. + Default value is `64`. + +- `predictable`. Predictable output type of functions. When true, output type + depends only on the input types. When false (default), output type can vary + depending on input values. For example `math.sqrt(-4)` returns `complex('2i')` when + predictable is false, and returns `NaN` when true. + Predictable output can be needed when programmatically handling the result of + a calculation, but can be inconvenient for users when evaluating dynamic + equations. + +- `randomSeed`. Set this option to seed pseudo random number generation, making it deterministic. The pseudo random number generator is reset with the seed provided each time this option is set. For example, setting it to `'a'` will cause `math.random()` to return `0.43449421599986604` upon the first call after setting the option every time. Set to `null` to seed the pseudo random number generator with a random seed. Default value is `null`. + + +## Examples + +This section shows a number of configuration examples. + +### node.js + +```js +import { create, all } from 'mathjs' + +const config = { + matrix: 'Array' // Choose 'Matrix' (default) or 'Array' +} +const math = create(all, config) + +// range will output an Array +math.range(0, 4) // Array [0, 1, 2, 3] + +// change the configuration from Arrays to Matrices +math.config({ + matrix: 'Matrix' // Choose 'Matrix' (default) or 'Array' +}) + +// range will output a Matrix +math.range(0, 4) // Matrix [0, 1, 2, 3] + +// create an instance of math.js with BigNumber configuration +const bigmath = create(all, { + number: 'BigNumber', // Choose 'number' (default), 'BigNumber', or 'Fraction' + precision: 32 // 64 by default, only applicable for BigNumbers +}) + +// parser will parse numbers as BigNumber now: +bigmath.evaluate('1 / 3') // BigNumber, 0.33333333333333333333333333333333 +``` + +### browser + + +```html + + + + + + + + + +``` diff --git a/node_modules/mathjs/docs/core/extension.md b/node_modules/mathjs/docs/core/extension.md new file mode 100644 index 0000000..5a2fff3 --- /dev/null +++ b/node_modules/mathjs/docs/core/extension.md @@ -0,0 +1,263 @@ +# Extension + +The library can easily be extended with functions and variables using the +[`import`](../reference/functions/import.md) function. The `import` function is available on a mathjs instance, which can be created using the `create` function. + +```js +import { create, all } from 'mathjs' + +const math = create(all) + +math.import(/* ... */) +``` + +The function `import` accepts an object with functions and variables, or an array with factory functions. It has the following syntax: + +```js +math.import(functions: Object [, options: Object]) +``` + +Where: + +- `functions` is an object or array containing the functions and/or values to be + imported. `import` support regular values and functions, typed functions + (see section [Typed functions](#typed-functions)), and factory functions + (see section [Factory functions](#factory-functions)). + An array is only applicable when it contains factory functions. + +- `options` is an optional second argument with options. + The following options are available: + + - `{boolean} override` + If `true`, existing functions will be overwritten. The default value is `false`. + - `{boolean} silent` + If `true`, the function will not throw errors on duplicates or invalid + types. Default value is `false`. + - `{boolean} wrap` + If `true`, the functions will be wrapped in a wrapper function which + converts data types like Matrix to primitive data types like Array. + The wrapper is needed when extending math.js with libraries which do not + support the math.js data types. The default value is `false`. + +The following code example shows how to import a function and a value into math.js: + +```js +// define new functions and variables +math.import({ + myvalue: 42, + hello: function (name) { + return 'hello, ' + name + '!' + } +}) + +// defined functions can be used in both JavaScript as well as the parser +math.myvalue * 2 // 84 +math.hello('user') // 'hello, user!' + +const parser = math.parser() +parser.evaluate('myvalue + 10') // 52 +parser.evaluate('hello("user")') // 'hello, user!' +``` + +## Import external libraries + +External libraries like +[numbers.js](https://github.com/sjkaliski/numbers.js) and +[numeric.js](https://github.com/sloisel/numeric) can be imported as follows. +The libraries must be installed using npm: + + $ npm install numbers + $ npm install numeric + +The libraries can be easily imported into math.js using `import`. +In order to convert math.js specific data types like `Matrix` to primitive types +like `Array`, the imported functions can be wrapped by enabling `{wrap: true}`. + +```js +import { create, all } from 'mathjs' +import * as numbers from 'numbers' +import * as numeric from 'numeric' + +// create a mathjs instance and import the numbers.js and numeric.js libraries +const math = create(all) +math.import(numbers, {wrap: true, silent: true}) +math.import(numeric, {wrap: true, silent: true}) + +// use functions from numbers.js +math.fibonacci(7) // 13 +math.evaluate('fibonacci(7)') // 13 + +// use functions from numeric.js +math.evaluate('eig([1, 2; 4, 3])').lambda.x // [5, -1] +``` + + +## Typed functions + +Typed functions can be created using `math.typed`. A typed function is a function +which does type checking on the input arguments. It can have multiple signatures. +And can automatically convert input types where needed. + +A typed function can be created like: + +```js +const max = typed('max', { + 'number, number': function (a, b) { + return Math.max(a, b) + }, + + 'BigNumber, BigNumber': function (a, b) { + return a.greaterThan(b) ? a : b + } +}) +``` + +Typed functions can be merged as long as there are no conflicts in the signatures. +This allows for extending existing functions in math.js with support for new +data types. + +```js +// create a new data type +function MyType (value) { + this.value = value +} +MyType.prototype.isMyType = true +MyType.prototype.toString = function () { + return 'MyType:' + this.value +} + +// define a new datatype +math.typed.addType({ + name: 'MyType', + test: function (x) { + // test whether x is of type MyType + return x && x.isMyType + } +}) + +// use the type in a new typed function +const add = typed('add', { + 'MyType, MyType': function (a, b) { + return new MyType(a.value + b.value) + } +}) + +// import in math.js, extend the existing function `add` with support for MyType +math.import({add: add}) + +// use the new type +const ans = math.add(new MyType(2), new MyType(3)) // returns MyType(5) +console.log(ans) // outputs 'MyType:5' +``` + +Detailed information on typed functions is available here: +[https://github.com/josdejong/typed-function](https://github.com/josdejong/typed-function) + + + + +## Factory functions + +Regular JavaScript functions can be imported in math.js using `math.import`: + +```js +math.import({ + myFunction: function (a, b) { + // ... + } +}) +``` + +The function can be stored in a separate file: + +```js +export function myFunction (a, b) { + // ... +} +``` + +Which can be imported like: + +```js +import { myFunction } from './myFunction.js' + +math.import({ + myFunction +}) +``` + +An issue arises when `myFunction` needs functionality from math.js: +it doesn't have access to the current instance of math.js when in a separate file. +Factory functions can be used to solve this issue. A factory function allows to inject dependencies into a function when creating it. + +A syntax of factory function is: + +```js +factory(name: string, dependencies: string[], create: function, meta?: Object): function +``` + +where: + +- `name` is the name of the created function. +- `dependencies` is an array with names of the dependent functions. +- `create` is a function which creates the function. + An object with the dependencies is passed as first argument. +- `meta` An optional object which can contain any meta data you want. + This will be attached as a property `meta` on the created function. + Known meta data properties used by the mathjs instance are: + - `isClass: boolean` If true, the created function is supposed to be a + class, and for example will not be exposed in the expression parser + for security reasons. + - `lazy: boolean`. By default, everything is imported lazily by `import`. + only as soon as the imported function or constant is actually used, it + will be constructed. A function can be forced to be created immediately + by setting `lazy: false` in the meta data. + - `isTransformFunction: boolean`. If true, the created function is imported + as a transform function. It will not be imported in `math` itself, only + in the internal `mathWithTransform` namespace that is used by the + expression parser. + - `recreateOnConfigChange: boolean`. If true, the imported factory will be + created again when there is a change in the configuration. This is for + example used for the constants like `pi`, which is different depending + on the configsetting `number` which can be numbers or BigNumbers. + +Here an example of a factory function which depends on `multiply`: + +```js +import { factory, create, all } from 'mathjs' + +// create a factory function +const name = 'negativeSquare' +const dependencies = ['multiply', 'unaryMinus'] +const createNegativeSquare = factory(name, dependencies, function ({ multiply, unaryMinus }) { + return function negativeSquare (x) { + return unaryMinus(multiply(x, x)) + } + }) + +// create an instance of the function yourself: +const multiply = (a, b) => a * b +const unaryMinus = (a) => -a +const negativeSquare = createNegativeSquare({ multiply, unaryMinus }) +console.log(negativeSquare(3)) // -9 + +// or import the factory in a mathjs instance and use it there +const math = create(all) +math.import(createNegativeSquare) +console.log(math.negativeSquare(4)) // -16 +console.log(math.evaluate('negativeSquare(5)')) // -25 +``` + +You may wonder why you would inject functions `multiply` and `unaryMinus` +instead of just doing these calculations inside the function itself. The +reason is that this makes the factory function `negativeSquare` work for +different implementations: numbers, BigNumbers, units, etc. + +```js +import { Decimal } from 'decimal.js' + +// create an instance of our negativeSquare supporting BigNumbers instead of numbers +const multiply = (a, b) => a.mul(b) +const unaryMinus = (a) => new Decimal(0).minus(a) +const negativeSquare = createNegativeSquare({ multiply, unaryMinus }) +``` \ No newline at end of file diff --git a/node_modules/mathjs/docs/core/index.md b/node_modules/mathjs/docs/core/index.md new file mode 100644 index 0000000..3e2b089 --- /dev/null +++ b/node_modules/mathjs/docs/core/index.md @@ -0,0 +1,21 @@ +# Core + +## Usage + +The core of math.js is the `math` namespace containing all functions and constants. There are three ways to do calculations in math.js: + +- Doing regular function calls like `math.add(math.sqrt(4), 2)`. +- Evaluating expressions like `math.evaluate('sqrt(4) + 2')` +- Chaining operations like `math.chain(4).sqrt().add(2)`. + +## Configuration + +math.js can be configured using the `math.config()`, see page [Configuration](configuration.md). + +## Extension + +math.js can be extended with new functions and constants using the function `math.import()`, see page [Extension](extension.md). + +## Serialization + +To persist or exchange data structures like matrices and units, the data types of math.js can be stringified as JSON. This is explained on the page [Serialization](serialization.md). diff --git a/node_modules/mathjs/docs/core/serialization.md b/node_modules/mathjs/docs/core/serialization.md new file mode 100644 index 0000000..afab6a7 --- /dev/null +++ b/node_modules/mathjs/docs/core/serialization.md @@ -0,0 +1,50 @@ +# Serialization + +Math.js has a number of data types like `Matrix`, `Complex`, and `Unit`. These +types are instantiated JavaScript objects. To be able to store these data types +or send them between processes, they must be serialized. The data types of +math.js can be serialized to JSON. Use cases: + +- Store data in a database or on disk. +- Interchange of data between a server and a client. +- Interchange of data between a web worker and the browser. + +Math.js types can be serialized using JavaScript's built-in `JSON.stringify` +function: + +```js +const x = math.complex('2 + 3i') +const str = JSON.stringify(x, math.replacer) +console.log(str) +// outputs a string '{"mathjs":"Complex","re":2,"im":3}' +``` + +> IMPORTANT: in most cases works, serialization correctly without +> passing the `math.replacer` function as second argument. This is because +> in most cases we can rely on the default behavior of JSON.stringify, which +> uses the `.toJSON` method on classes like `Unit` and `Complex` to correctly +> serialize them. However, there are a few special cases like the +> number `Infinity` which does require the replacer function in order to be +> serialized without losing information: without it, `Infinity` will be +> serialized as `"null"` and cannot be deserialized correctly. +> +> So, it's best to always pass the `math.replacer` function to prevent +> weird edge cases. + +In order to deserialize a string, containing math.js data types, `JSON.parse` +can be used. In order to recognize the data types of math.js, `JSON.parse` must +be called with the reviver function of math.js: + +```js +const json = '{"mathjs":"Unit","value":5,"unit":"cm","fixPrefix":false}' +const x = JSON.parse(json, math.reviver) // Unit 5 cm +``` + +Note that if math.js is used in conjunction with other data types, it is +possible to use multiple reviver functions at the same time by cascading them: + +```js +const reviver = function (key, value) { + return reviver1(key, reviver2(key, value)) +} +``` diff --git a/node_modules/mathjs/docs/custom_bundling.md b/node_modules/mathjs/docs/custom_bundling.md new file mode 100644 index 0000000..55b1d54 --- /dev/null +++ b/node_modules/mathjs/docs/custom_bundling.md @@ -0,0 +1,116 @@ +# Custom bundling + +Math.js is a large library containing many data types and functions. +It is well possible that you only need a small portion of the library. +Math.js allows for picking just the functions and data types you need. +This gives faster load times and smaller browser bundles. Math.js uses +ES modules, and creating small bundles using tree-shaking works out of +the box when using Webpack for example. + +This page describes: + +- How to use just a few functions for faster load times and smaller bundles. +- How to use light-weight, number only implementations of functions. +- What to expect from bundle sizes when using tree-shaking. + +## Using just a few functions + +Using the function `create`, a mathjs instance can be created. +The `all` object contains all functionality available in mathjs, +and a mathjs instance containing everything can be created like: + +```js +import { create, all } from 'mathjs' + +const math = create(all) +``` + +To create an instance with just a few functions, you have to pass the +factory functions of the functions you need, and all their dependencies. +For example the function `add` depends on the functions `addScalar`, +`equalScalar`, classes `DenseMatrix` and `SparseMatrix`, and more. +Because it is hard to figure out what the dependencies of a function are, +and the dependencies of the dependencies, mathjs provides ready made +collections of all dependencies for every function. For example all +factory functions of function `add` and its dependencies are available +as `addDependencies`. + +Here is a full example of loading just a few functions in a mathjs instance: + +```js +// file: custom_loading.js + +import { + create, + fractionDependencies, + addDependencies, + divideDependencies, + formatDependencies +} from 'mathjs' + +const config = { + // optionally, you can specify configuration +} + +// Create just the functions we need +const { fraction, add, divide, format } = create({ + fractionDependencies, + addDependencies, + divideDependencies, + formatDependencies +}, config) + +// Use the created functions +const a = fraction(1, 3) +const b = fraction(3, 7) +const c = add(a, b) +const d = divide(a, b) +console.log('c =', format(c)) // outputs "c = 16/21" +console.log('d =', format(d)) // outputs "d = 7/9" +``` + +This example can be bundled using for example Webpack: + +``` +npx webpack custom_loading.js -o custom_loading.bundle.js --mode=production +``` + +Only the used parts of mathjs will be bundled thanks to tree-shaking. + + +## Numbers only + +The functions of mathjs support multiple data types out of the box, like +numbers, bignumbers, complex numbers, units, and matrices. Quite commonly however, +only support for numbers is needed and the other data-types are overkill. + +To accomodate for this use case of only numbers only, mathjs offers light-weight, +number only implementations of all relevant functions. These are available by +importing from `'mathjs/number'` instead of `'mathjs'`: + +```js +// use light-weight, numbers only implementations of functions +import { create, all } from 'mathjs/number' + +const math = create(all) +console.log(add(2, 3)) // 5 +``` + +## Bundle size + +When using just a few functions of mathjs instead of the whole library, +you may expect the size of the bundle to be just a small fraction of the +complete library. However, to create the function `add` supporting all data +types, all these data types must be included: Unit, BigNumber, Complex, +DenseMatrix, SparseMatrix, etc. A rough idea of the size of different parts of +mathjs: + +- About 5% is coming from core functionality like `create`, `import`, `factory`, + `typed-function`, etc. +- About 30% of the bundle size comes from the data classes `Complex`, `BigNumber`, `Fraction`, `Unit`, `SparseMatrix`, `DenseMatrix`. +- About 25% of the bundle size comes from the expression parser. + Half of this comes from the embedded docs. +- About 40% comes from the about 200 built-in functions and some constants. + +To get a better insight in what is in your JavaScript bundle, you can use +a tool like [source-map-explorer](https://github.com/danvk/source-map-explorer). diff --git a/node_modules/mathjs/docs/datatypes/bignumbers.md b/node_modules/mathjs/docs/datatypes/bignumbers.md new file mode 100644 index 0000000..e2874a7 --- /dev/null +++ b/node_modules/mathjs/docs/datatypes/bignumbers.md @@ -0,0 +1,102 @@ +# BigNumbers + +For calculations with an arbitrary precision, math.js supports a `BigNumber` +datatype. BigNumber support is powered by +[decimal.js](https://github.com/MikeMcl/decimal.js/). + +## Usage + +A BigNumber can be created using the function `bignumber`: + +```js +math.bignumber('2.3e+500') // BigNumber, 2.3e+500 +``` + +Most functions can determine the type of output from the type of input: +a number as input will return a number as output, a BigNumber as input returns +a BigNumber as output. Functions which cannot determine the type of output +from the input (for example `math.evaluate`) use the default number type `number`, +which can be configured when instantiating math.js. To configure the use of +BigNumbers instead of [numbers](numbers.md) by default, configure math.js like: + +```js +math.config({ + number: 'BigNumber', // Default type of number: + // 'number' (default), 'BigNumber', or 'Fraction' + precision: 64 // Number of significant digits for BigNumbers +}) + +// use math +math.evaluate('0.1 + 0.2') // BigNumber, 0.3 +``` + +The default precision for BigNumber is 64 digits, and can be configured with +the option `precision`. + + +## Support + +Most functions in math.js support BigNumbers, but not all of them. +For example the function `random` doesn't support BigNumbers. + + +## Round-off errors + +Calculations with BigNumber are much slower than calculations with Number, +but they can be executed with an arbitrary precision. By using a higher +precision, it is less likely that round-off errors occur: + +```js +// round-off errors with numbers +math.add(0.1, 0.2) // Number, 0.30000000000000004 +math.divide(0.3, 0.2) // Number, 1.4999999999999998 + +// no round-off errors with BigNumbers :) +math.add(math.bignumber(0.1), math.bignumber(0.2)) // BigNumber, 0.3 +math.divide(math.bignumber(0.3), math.bignumber(0.2)) // BigNumber, 1.5 +``` + + +## Limitations + +It's important to realize that BigNumbers do not solve *all* problems related +to precision and round-off errors. Numbers with an infinite number of digits +cannot be represented with a regular number nor a BigNumber. Though a BigNumber +can store a much larger number of digits, the amount of digits remains limited +if only to keep calculations fast enough to remain practical. + +```js +const one = math.bignumber(1) +const three = math.bignumber(3) +const third = math.divide(one, three) +console.log(third.toString()) +// outputs 0.3333333333333333333333333333333333333333333333333333333333333333 + +const ans = math.multiply(third, three) +console.log(ans.toString()) +// outputs 0.9999999999999999999999999999999999999999999999999999999999999999 +// this should be 1 again, but `third` is rounded to a limited number of digits 3 +``` + + +## Conversion + +BigNumbers can be converted to numbers and vice versa using the functions +`number` and `bignumber`. When converting a BigNumber to a number, the high +precision of the BigNumber will be lost. When a BigNumber is too large to be represented +as Number, it will be initialized as `Infinity`. + +```js +// converting numbers and BigNumbers +const a = math.number(0.3) // number, 0.3 +const b = math.bignumber(a) // BigNumber, 0.3 +const c = math.number(b) // number, 0.3 + +// exceeding the maximum of a number +const d = math.bignumber('1.2e500') // BigNumber, 1.2e+500 +const e = math.number(d) // number, Infinity + +// loosing precision when converting to number +const f = math.bignumber('0.2222222222222222222') // BigNumber, 0.2222222222222222222 +const g = math.number(f) // number, 0.2222222222222222 +``` diff --git a/node_modules/mathjs/docs/datatypes/complex_numbers.md b/node_modules/mathjs/docs/datatypes/complex_numbers.md new file mode 100644 index 0000000..1b98698 --- /dev/null +++ b/node_modules/mathjs/docs/datatypes/complex_numbers.md @@ -0,0 +1,168 @@ +# Complex Numbers + +Math.js supports the creation, manipulation, and calculations with complex numbers. +Support of complex numbers is powered by the library [complex.js](https://github.com/infusion/Complex.js). + +In mathematics, a complex number is an expression of the form `a + bi`, +where `a` and `b` are real numbers and `i` represents the imaginary number +defined as `i^2 = -1`. (In other words, `i` is the square root of `-1`.) +The real number `a` is called the real part of the complex number, +and the real number `b` is the imaginary part. For example, `3 + 2i` is a +complex number, having real part `3` and imaginary part `2`. +Complex numbers are often used in applied mathematics, control theory, +signal analysis, fluid dynamics and other fields. + +## Usage + +A complex number is created using the function `math.complex`. This function +accepts: + +- two numbers representing the real and imaginary part of the value, +- a single string containing a complex value in the form `a + bi` where `a` + and `b` respectively represent the real and imaginary part of the complex number. +- an object with either properties `re` and `im` for the real and imaginary + part of the value, or two properties `r` and `phi` containing the polar + coordinates of a complex value. +The function returns a `Complex` object. + +Syntax: + +```js +math.complex(re: number) : Complex +math.complex(re: number, im: number) : Complex +math.complex(complex: Complex) : Complex +math.complex({re: Number, im: Number}) : Complex +math.complex({r: number, phi: number}) : Complex +math.complex({abs: number, arg: number}) : Complex +math.complex(str: string) : Complex +``` + +Examples: + +```js +const a = math.complex(2, 3) // Complex 2 + 3i +a.re // Number 2 +a.im // Number 3 + +const b = math.complex('4 - 2i') // Complex 4 - 2i +b.re = 5 // Number 5 +b // Complex 5 - 2i +``` + +## Calculations + +Most functions of math.js support complex numbers. Complex and real numbers +can be used together. + +```js +const a = math.complex(2, 3) // Complex 2 + 3i +const b = math.complex('4 - 2i') // Complex 4 - 2i + +math.re(a) // Number 2 +math.im(a) // Number 3 +math.conj(a) // Complex 2 - 3i + +math.add(a, b) // Complex 6 + i +math.multiply(a, 2) // Complex 4 + 6i +math.sqrt(-4) // Complex 2i +``` + +## API +A `Complex` object created by `math.complex` contains the following properties and functions: + +### complex.re + +A number containing the real part of the complex number. Can be read and replaced. + +### complex.im + +A number containing the imaginary part of the complex number. Can be read and replaced. + +### complex.clone() + +Create a clone of the complex number. + +### complex.equals(other) + +Test whether a complex number equals another complex value. + + Two complex numbers are equal when both their real and imaginary parts are + equal. + +### complex.neg() + +Returns a complex number with a real part and an imaginary part equal in magnitude but opposite in sign to the current complex number. + +### complex.conjugate() + +Returns a complex number with an equal real part and an imaginary part equal in magnitude but opposite in sign to the current complex number. + +### complex.inverse() + +Returns a complex number that is inverse of the current complex number. + +### complex.toVector() + +Get the vector representation of the current complex number. Returns an array of size 2. + +### complex.toJSON() + +Returns a JSON representation of the complex number, with signature + `{mathjs: 'Complex', re: number, im: number}`. + Used when serializing a complex number, see [Serialization](../core/serialization.md). + +### complex.toPolar() + +Get the polar coordinates of the complex number, returns + an object with properties `r` and `phi`. + +### complex.toString() + +Returns a string representation of the complex number, formatted + as `a + bi` where `a` is the real part and `b` the imaginary part. + + +### complex.format([precision: number]) + +Get a string representation of the complex number, + formatted as `a + bi` where `a` is the real part and `b` the imaginary part. + If precision is defined, the units value will be rounded to the provided + number of digits. + +## Static methods +The following static methods can be accessed using `math.Complex` + + +### Complex.fromJSON(json) + +Revive a complex number from a JSON object. Accepts + An object `{mathjs: 'Complex', re: number, im: number}`, where the property + `mathjs` is optional. + Used when deserializing a complex number, see [Serialization](../core/serialization.md). + +### Complex.fromPolar(r: number, phi: number) + +Create a complex number from polar coordinates. + + +### Complex.compare(a: Complex, b: Complex) + +Returns the comparision result of two complex number: + +- Returns 1 when the real part of `a` is larger than the real part of `b` +- Returns -1 when the real part of `a` is smaller than the real part of `b` +- Returns 1 when the real parts are equal + and the imaginary part of `a` is larger than the imaginary part of `b` +- Returns -1 when the real parts are equal + and the imaginary part of `a` is smaller than the imaginary part of `b` +- Returns 0 when both real and imaginary parts are equal. + +Example: +```js +const a = math.complex(2, 3) // Complex 2 + 3i +const b = math.complex(2, 1) // Complex 2 + 1i +math.Complex.compare(a,b) // returns 1 + +//create from json +const c = math.Complex.fromJSON({mathjs: 'Complex', re: 4, im: 3}) // Complex 4 + 3i +``` diff --git a/node_modules/mathjs/docs/datatypes/fractions.md b/node_modules/mathjs/docs/datatypes/fractions.md new file mode 100644 index 0000000..fa73de4 --- /dev/null +++ b/node_modules/mathjs/docs/datatypes/fractions.md @@ -0,0 +1,75 @@ +# Fractions + +For calculations with fractions, math.js supports a `Fraction` data type. +Fraction support is powered by [fraction.js](https://github.com/infusion/Fraction.js). +Unlike [numbers](numbers.md) and [BigNumbers](./bignumbers.md), fractions can +store numbers with infinitely repeating decimals, for example `1/3 = 0.3333333...`, +which can be represented as `0.(3)`, or `2/7` which can be represented as `0.(285714)`. + + +## Usage + +A Fraction can be created using the function `fraction`: + +```js +math.fraction('1/3') // Fraction, 1/3 +math.fraction(2, 3) // Fraction, 2/3 +math.fraction('0.(3)') // Fraction, 1/3 +``` + +And can be used in functions like `add` and `multiply` like: + +```js +math.add(math.fraction('1/3'), math.fraction('1/6')) // Fraction, 1/2 +math.multiply(math.fraction('1/4'), math.fraction('1/2')) // Fraction, 1/8 +``` + +Note that not all functions support fractions. For example trigonometric +functions doesn't support fractions. When not supported, the functions +will convert the input to numbers and return a number as result. + +Most functions will determine the type of output from the type of input: +a number as input will return a number as output, a Fraction as input returns +a Fraction as output. Functions which cannot determine the type of output +from the input (for example `math.evaluate`) use the default number type `number`, +which can be configured when instantiating math.js. To configure the use of +fractions instead of [numbers](numbers.md) by default, configure math.js like: + +```js +// Configure the default type of number: 'number' (default), 'BigNumber', or 'Fraction' +math.config({ + number: 'Fraction' +}) + +// use the expression parser +math.evaluate('0.32 + 0.08') // Fraction, 2/5 +``` + +## Support + +The following functions support fractions: + +- Arithmetic functions: `abs`, `add`, `ceil`, `cube`, `divide`, `dotDivide`, `dotMultiply`, `fix`, `floor`, `gcd`, `mod`, `multiply`, `round`, `sign`, `square`, `subtract`, `unaryMinus`, `unaryPlus`. +- Construction functions: `fraction`. +- Relational functions: `compare`, `deepEqual`, `equal`, `larger`, `largerEq`, `smaller`, `smallerEq`, `unequal`. +- Utils functions: `format`. + + +## Conversion + +Fractions can be converted to numbers and vice versa using the functions +`number` and `fraction`. When converting a Fraction to a number, precision +may be lost when the value cannot represented in 16 digits. + +```js +// converting numbers and fractions +const a = math.number(0.3) // number, 0.3 +const b = math.fraction(a) // Fraction, 3/10 +const c = math.number(b) // number, 0.3 + +// loosing precision when converting to number: a fraction can represent +// a number with an infinite number of repeating decimals, a number just +// stores about 16 digits and cuts consecutive digits. +const d = math.fraction('2/5') // Fraction, 2/5 +const e = math.number(d) // number, 0.4 +``` diff --git a/node_modules/mathjs/docs/datatypes/index.md b/node_modules/mathjs/docs/datatypes/index.md new file mode 100644 index 0000000..5f3cd2e --- /dev/null +++ b/node_modules/mathjs/docs/datatypes/index.md @@ -0,0 +1,67 @@ +# Data Types + +The functions of math.js support multiple data types, both native JavaScript +types as well as more advanced types implemented in math.js. The data types can +be mixed together in calculations, for example by adding a Number to a +Complex number or Array. + +The supported data types are: + +- Boolean +- [Number](numbers.md) +- [BigNumber](bignumbers.md) +- [Complex](complex_numbers.md) +- [Fraction](fractions.md) +- [Array](matrices.md) +- [Matrix](matrices.md) +- [Unit](units.md) +- String + +Function [`math.typeOf(x)`](../reference/functions/typeOf.md) can be used to get +the type of a variable. + +Example usage: + +```js +// use numbers +math.subtract(7.1, 2.3) // 4.8 +math.round(math.pi, 3) // 3.142 +math.sqrt(4.41e2) // 21 + +// use BigNumbers +math.add(math.bignumber(0.1), math.bignumber(0.2)) // BigNumber, 0.3 + +// use Fractions +math.add(math.fraction(1), math.fraction(3)) // Fraction, 0.(3) + +// use strings +math.add('hello ', 'world') // 'hello world' +math.max('A', 'D', 'C') // 'D' + +// use complex numbers +const a = math.complex(2, 3) // 2 + 3i +a.re // 2 +a.im // 3 +const b = math.complex('4 - 2i') // 4 - 2i +math.add(a, b) // 6 + i +math.sqrt(-4) // 2i + +// use arrays +const array = [1, 2, 3, 4, 5] +math.factorial(array) // Array, [1, 2, 6, 24, 120] +math.add(array, 3) // Array, [3, 5, 6, 7, 8] + +// use matrices +const matrix = math.matrix([1, 4, 9, 16, 25]) // Matrix, [1, 4, 9, 16, 25] +math.sqrt(matrix) // Matrix, [1, 2, 3, 4, 5] + +// use units +const a = math.unit(55, 'cm') // 550 mm +const b = math.unit('0.1m') // 100 mm +math.add(a, b) // 0.65 m + +// check the type of a variable +math.typeOf(2) // 'number' +math.typeOf(math.unit('2 inch')) // 'Unit' +math.typeOf(math.sqrt(-4)) // 'Complex' +``` diff --git a/node_modules/mathjs/docs/datatypes/matrices.md b/node_modules/mathjs/docs/datatypes/matrices.md new file mode 100644 index 0000000..a931376 --- /dev/null +++ b/node_modules/mathjs/docs/datatypes/matrices.md @@ -0,0 +1,358 @@ +# Matrices + +Math.js supports multi dimensional matrices and arrays. Matrices can be +created, manipulated, and used in calculations. Both regular JavaScript +arrays as well as the matrix type implemented by math.js can be used +interchangeably in all relevant math.js functions. math.js supports both +dense and sparse matrices. + + +## Arrays and matrices + +Math.js supports two types of matrices: + +- `Array`, a regular JavaScript array. A multi dimensional array can be created + by nesting arrays. +- `Matrix`, a matrix implementation by math.js. A `Matrix` is an object wrapped + around a regular JavaScript `Array`, providing utility functions for easy + matrix manipulation such as `subset`, `size`, `resize`, `clone`, and more. + +In most cases, the type of matrix output from functions is determined by the +function input: An `Array` as input will return an `Array`, a `Matrix` as input +will return a `Matrix`. In case of mixed input, a `Matrix` is returned. +For functions where the type of output cannot be determined from the +input, the output is determined by the configuration option `matrix`, +which can be a string `'Matrix'` (default) or `'Array'`. + +```js +// create an array and a matrix +const array = [[2, 0], [-1, 3]] // Array +const matrix = math.matrix([[7, 1], [-2, 3]]) // Matrix + +// perform a calculation on an array and matrix +math.square(array) // Array, [[4, 0], [1, 9]] +math.square(matrix) // Matrix, [[49, 1], [4, 9]] + +// perform calculations with mixed array and matrix input +math.add(array, matrix) // Matrix, [[9, 1], [-3, 6]] +math.multiply(array, matrix) // Matrix, [[14, 2], [-13, 8]] + +// create a matrix. Type of output of function ones is determined by the +// configuration option `matrix` +math.ones(2, 3) // Matrix, [[1, 1, 1], [1, 1, 1]] +``` + + +## Creation + +A matrix can be created from an array using the function `math.matrix`. The +provided array can contain nested arrays in order to create a multi-dimensional matrix. When called without arguments, an empty matrix will be +created. + +```js +// create matrices +math.matrix() // Matrix, size [0] +math.matrix([0, 1, 2]) // Matrix, size [3] +math.matrix([[0, 1], [2, 3], [4, 5]]) // Matrix, size [3, 2] +``` + +Math.js supports regular Arrays. Multiple dimensions can be created +by nesting Arrays in each other. + +```js +// create arrays +[] // Array, size [0] +[0, 1, 2] // Array, size [3] +[[0, 1], [2, 3], [4, 5]] // Array, size [3, 2] +``` + +Matrices can contain different types of values: numbers, complex numbers, +units, or strings. Different types can be mixed together in a single matrix. + +```js +// create a matrix with mixed types +const a = math.matrix([2.3, 'hello', math.complex(3, -4), math.unit('5.2 mm')]) +a.subset(math.index(1)) // 'hello' +``` + + +There are a number of functions to create a matrix with a specific size and +content: `ones`, `zeros`, `identity`. + +```js +// zeros creates a matrix filled with zeros +math.zeros(3) // Matrix, size [3], [0, 0, 0] +math.zeros(3, 2) // Matrix, size [3, 2], [[0, 0], [0, 0], [0, 0]] +math.zeros(2, 2, 2) // Matrix, size [2, 2, 2], + // [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] + +// ones creates a matrix filled with ones +math.ones(3) // Matrix, size [3], [1, 1, 1] +math.multiply(math.ones(2, 2), 5) // Matrix, size [2, 2], [[5, 5], [5, 5]] + +// identity creates an identity matrix +math.identity(3) // Matrix, size [3, 3], [[1, 0, 0], [0, 1, 0], [0, 0, 1]] +math.identity(2, 3) // Matrix, size [2, 3], [[1, 0, 0], [0, 1, 0]] +``` + + +The functions `ones`, `zeros`, and `identity` also accept a single array +or matrix containing the dimensions for the matrix. When the input is an Array, +the functions will output an Array. When the input is a Matrix, the output will +be a Matrix. Note that in case of numbers as arguments, the output is +determined by the option `matrix` as discussed in section +[Arrays and matrices](#arrays-and-matrices). + +```js +// Array as input gives Array as output +math.ones([2, 3]) // Array, size [3, 2], [[1, 1, 1], [1, 1, 1]] +math.ones(math.matrix([2, 3])) // Matrix, size [3, 2], [[1, 1, 1], [1, 1, 1]] +``` + +Ranges can be created using the function `range`. The function `range` is +called with parameters start and end, and optionally a parameter step. +The start of the range is included, the end of the range is excluded. + +```js +math.range(0, 4) // [0, 1, 2, 3] +math.range(0, 8, 2) // [0, 2, 4, 6] +math.range(3, -1, -1) // [3, 2, 1, 0] +``` + + +## Calculations + +All relevant functions of math.js support matrices and arrays. + +```js +// perform a calculation on a matrix +const a = math.matrix([1, 4, 9, 16, 25]) // Matrix, [1, 4, 9, 16, 25] +math.sqrt(a) // Matrix, [1, 2, 3, 4, 5] + +// perform a calculation on an array +const b = [1, 2, 3, 4, 5] +math.factorial(b) // Array, [1, 2, 6, 24, 120] + +// multiply an array with a matrix +const c = [[2, 0], [-1, 3]] // Array +const d = math.matrix([[7, 1], [-2, 3]]) // Matrix +math.multiply(c, d) // Matrix, [[14, 2], [-13, 8]] + +// add a number to a matrix +math.add(c, 2) // Array, [[4, 2], [1, 5]] + +// calculate the determinant of a matrix +math.det(c) // 6 +math.det(d) // 23 +``` + + +## Size and Dimensions + +Math.js uses geometric dimensions: + +- A scalar is zero-dimensional. +- A vector is one-dimensional. +- A matrix is two or multi-dimensional. + +The size of a matrix can be calculated with the function `size`. Function `size` +returns a `Matrix` or `Array`, depending on the configuration option `matrix`. +Furthermore, matrices have a function `size` as well, which always returns +an Array. + +```js +// get the size of a scalar +math.size(2.4) // Matrix, [] +math.size(math.complex(3, 2)) // Matrix, [] +math.size(math.unit('5.3 mm')) // Matrix, [] + +// get the size of a one-dimensional matrix (a vector) and a string +math.size([0, 1, 2, 3]) // Array, [4] +math.size('hello world') // Matrix, [11] + +// get the size of a two-dimensional matrix +const a = [[0, 1, 2, 3]] // Array +const b = math.matrix([[0, 1, 2], [3, 4, 5]]) // Matrix +math.size(a) // Array, [1, 4] +math.size(b) // Matrix, [2, 3] + +// matrices have a function size (always returns an Array) +b.size() // Array, [2, 3] + +// get the size of a multi-dimensional matrix +const c = [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]] +math.size(c) // Array, [2, 2, 3] +``` + +Note that the dimensions themselves do not have a meaning attached. +When creating and printing a two dimensional matrix, the first dimension is +normally rendered as the _column_, and the second dimension is rendered as +the _row_. For example: + +```js +console.table(math.zeros([2, 4])) +// 0 0 0 0 +// 0 0 0 0 +``` + +If you have a matrix where the first dimension means `x` and the second +means `y`, this will look confusing since `x` is printed as _column_ +(vertically) and `y` as _row_ (horizontally). + + +## Resizing + +Matrices can be resized using their `resize` function. This function is called +with an Array with the new size as the first argument, and accepts an optional +default value. By default, new entries will be set to `0`, but it is possible +to pass a different default value like `null` to clearly indicate that +the entries haven't been explicitly set. + +```js +const a = math.matrix() // Matrix, size [0], [] +a.resize([2, 3]) // Matrix, size [2, 3], [[0, 0, 0], [0, 0, 0]] +a.resize([2, 2, 2]) // Matrix, size [2, 2, 2], + // [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] + +const b = math.matrix() +b.resize([3], 7) // Matrix, size [3], [7, 7, 7] +b.resize([5], 9) // Matrix, size [5], [7, 7, 7, 9, 9] +b.resize([2]) // Matrix, size [2], [7, 7] +``` + + +Outer dimensions of a matrix can be squeezed using the function `squeeze`. When +getting or setting a subset in a matrix, the subset is automatically squeezed +or unsqueezed. + +```js +// squeeze a matrix +const a = [[[0, 1, 2]]] +math.squeeze(a) // [0, 1, 2] +math.squeeze([[3]]) // 3 + +// subsets are automatically squeezed +const b = math.matrix([[0, 1], [2, 3]]) +b.subset(math.index(1, 0)) // 2 +``` + + +## Getting or replacing subsets + +Subsets of a matrix can be retrieved or replaced using the function `subset`. +Matrices have a `subset` function, which is applied to the matrix itself: +`Matrix.subset(index [, replacement])`. For both matrices and arrays, +the static function `subset(matrix, index [, replacement])` can be used. +When parameter `replacement` is provided, the function will replace a subset +in the matrix, and if not, a subset of the matrix will be returned. + +A subset can be defined using an `Index`. An `Index` contains a single value +or a set of values for each dimension of a matrix. An `Index` can be +created using the function `index`. +Matrix indexes in math.js are zero-based, like most programming languages +including JavaScript itself. + +Note that mathematical applications like Matlab and Octave work differently, +as they use one-based indexes. + +```js +// create some matrices +const a = [0, 1, 2, 3] +const b = [[0, 1], [2, 3]] +const c = math.zeros(2, 2) +const d = math.matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) +const e = math.matrix() + +// get a subset +math.subset(a, math.index(1)) // 1 +math.subset(a, math.index([2, 3])) // Array, [2, 3] +math.subset(a, math.index(math.range(0,4))) // Array, [0, 1, 2, 3] +math.subset(b, math.index(1, 0)) // 2 +math.subset(b, math.index(1, [0, 1])) // Array, [2, 3] +math.subset(b, math.index([0, 1], 0)) // Matrix, [[0], [2]] + +// get a subset +d.subset(math.index([1, 2], [0, 1])) // Matrix, [[3, 4], [6, 7]] +d.subset(math.index(1, 2)) // 5 + +// replace a subset. The subset will be applied to a clone of the matrix +math.subset(b, math.index(1, 0), 9) // Array, [[0, 1], [9, 3]] +math.subset(b, math.index(2, [0, 1]), [4, 5]) // Array, [[0, 1], [2, 3], [4, 5]] + +// replace a subset. The subset will be applied to the matrix itself +c.subset(math.index(0, 1),1) // Matrix, [[0, 1], [0, 0]] +c.subset(math.index(1, [0, 1]), [2, 3]) // Matrix, [[0, 1], [2, 3]] +e.resize([2, 3], 0) // Matrix, [[0, 0, 0], [0, 0, 0]] +e.subset(math.index(1, 2), 5) // Matrix, [[0, 0, 0], [0, 0, 5]] +``` + +## Iterating + +Matrices contain functions `map` and `forEach` to iterate over all elements of +the (multidimensional) matrix. The callback function of `map` and `forEach` has +three parameters: `value` (the value of the currently iterated element), +`index` (an array with the index value for each dimension), and `matrix` (the +matrix being iterated). This syntax is similar to the `map` and `forEach` +functions of native JavaScript Arrays, except that the index is no number but +an Array with numbers for each dimension. + +```js +const a = math.matrix([[0, 1], [2, 3], [4, 5]]) + +// The iteration below will output the following in the console: +// value: 0 index: [0, 0] +// value: 1 index: [0, 1] +// value: 2 index: [1, 0] +// value: 3 index: [1, 1] +// value: 4 index: [2, 0] +// value: 5 index: [2, 1] +a.forEach(function (value, index, matrix) { + console.log('value:', value, 'index:', index) +}) + +// Apply a transformation on the matrix +const b = a.map(function (value, index, matrix) { + return math.multiply(math.sin(value), math.exp(math.abs(value))) +}) +console.log(b.format(5)) // [[0, 2.2874], [6.7188, 2.8345], [-41.32, -142.32]] + +// Create a matrix with the cumulative of all elements +let count = 0 +const cum = a.map(function (value, index, matrix) { + count += value + return count +}) +console.log(cum.toString()) // [[0, 1], [3, 6], [10, 15]] +``` + +## Storage types + +Math.js supports both dense matrices as well as sparse matrices. Sparse matrices are efficient for matrices largely containing zeros. In that case they save a lot of memory, and calculations can be much faster than for dense matrices. + +Math.js supports two type of matrices: + +- Dense matrix (`'dense'`, `default`) A regular, dense matrix, supporting multi-dimensional matrices. This is the default matrix type. +- Sparse matrix (`'sparse'`): A two dimensional sparse matrix implementation. + +The type of matrix can be selected when creating a matrix using the construction functions `matrix`, `diag`, `identity`, `ones`, and `zeros`. + +```js +// create sparse matrices +const m1 = math.matrix([[0, 1], [0, 0]], 'sparse') +const m2 = math.identity(1000, 1000, 'sparse') +``` + +## API + +All relevant functions in math.js support Matrices and Arrays. Functions like `math.add` and `math.subtract`, `math.sqrt` handle matrices element wise. There is a set of functions specifically for creating or manipulating matrices, such as: + +- Functions like `math.matrix` and `math.sparse`, `math.ones`, `math.zeros`, and `math.identity` to create a matrix. +- Functions like `math.subset` and `math.index` to get or replace a part of a matrix +- Functions like `math.transpose` and `math.diag` to manipulate matrices. + +A full list of matrix functions is available on the [functions reference page](../reference/functions.md#matrix-functions). + +Two types of matrix classes are available in math.js, for storage of dense and sparse matrices. Although they contain public functions documented as follows, using the following API directly is *not* recommended. Prefer using the functions in the "math" namespace wherever possible. + +- [DenseMatrix](../reference/classes/densematrix.md) +- [SparseMatrix](../reference/classes/sparsematrix.md) diff --git a/node_modules/mathjs/docs/datatypes/numbers.md b/node_modules/mathjs/docs/datatypes/numbers.md new file mode 100644 index 0000000..29e7534 --- /dev/null +++ b/node_modules/mathjs/docs/datatypes/numbers.md @@ -0,0 +1,106 @@ +# Numbers + +Math.js supports three types of numbers: + +- Number for fast floating point arithmetic, described on this page. +- BigNumber for arbitrary precision arithmetic, described on the page + [BigNumbers](bignumbers.md). +- Fraction, which stores numbers in terms of a numerator and denominators, + described on the page [Fractions](fractions.md). + + +## Configuration + +Most functions can determine the type of output from the type of input: +a number as input will return a number as output, a BigNumber as input returns +a BigNumber as output. Functions which cannot determine the type of output +from the input (for example `math.evaluate`) use the default number type, which +can be configured when instantiating math.js: + +```js +math.config({ + number: 'number' // Default type of number: + // 'number' (default), 'BigNumber', or 'Fraction' +}) +``` + +## Round-off errors + +Math.js uses the built-in JavaScript Number type. A Number is a floating point +number with a limited precision of 64 bits, about 16 digits. The largest integer +number which can be represented by a JavaScript Number +is `+/- 9007199254740992` (`+/- 2^53`). Because of the limited precision of +floating point numbers round-off errors can occur during calculations. +This can be easily demonstrated: + +```js +// a round-off error +0.1 + 0.2 // 0.30000000000000004 +math.add(0.1, 0.2) // 0.30000000000000004 +``` + +In most cases, round-off errors don't matter: they have no significant +impact on the results. However, it looks ugly when displaying output to a user. +A solution is to limit the precision just below the actual precision of 16 +digits in the displayed output: + +```js +// prevent round-off errors showing up in output +const ans = math.add(0.1, 0.2) // 0.30000000000000004 +math.format(ans, {precision: 14}) // '0.3' +``` + +Alternatives are to use [Fractions](fractions.md) which store a number as a numerator and denominator, or [BigNumbers](bignumbers.md), which store a number with a higher precision. + + +## Minimum and maximum + +A Number can store values between `5e-324` and `1.7976931348623157e+308`. +Values smaller than the minimum are stored as `0`, and values larger than the +maximum are stored as `+/- Infinity`. + +```js +// exceeding the maximum and minimum number +console.log(1e309) // Infinity +console.log(1e-324) // 0 +``` + +## Equality + +Because of rounding errors in calculations, it is unsafe to compare JavaScript +Numbers. For example executing `0.1 + 0.2 == 0.3` in JavaScript will return +false, as the addition `0.1 + 0.2` introduces a round-off error and does not +return exactly `0.3`. + +To solve this problem, the relational functions of math.js check whether the +relative difference between the compared values is smaller than the configured +option `epsilon`. In pseudo code (without exceptions for 0, Infinity and NaN): + + diff = abs(x - y) + nearlyEqual = (diff <= max(abs(x), abs(y)) * EPSILON) OR (diff < DBL_EPSILON) + +where: + + - `EPSILON` is the relative difference between x and y. Epsilon is configurable + and is `1e-12` by default. See [Configuration](../core/configuration.md). + - `DBL_EPSILON` is the minimum positive floating point number such that + `1.0 + DBL_EPSILON !== 1.0`. This is a constant with a value of approximately + `2.2204460492503130808472633361816e-16`. + +Note that the relational functions cannot be used to compare small values +(`< 2.22e-16`). These values are all considered equal to zero. + +Examples: + +```js +// compare values having a round-off error +console.log(0.1 + 0.2 === 0.3) // false +console.log(math.equal(0.1 + 0.2, 0.3)) // true + +// small values (< 2.22e-16) cannot be compared +console.log(3e-20 === 3.1e-20) // false +console.log(math.equal(3e-20, 3.1e-20)) // true +``` + +The available relational functions are: `compare`, `equal`, `larger`, +`largerEq`, `smaller`, `smallerEq`, `unequal`. diff --git a/node_modules/mathjs/docs/datatypes/units.md b/node_modules/mathjs/docs/datatypes/units.md new file mode 100644 index 0000000..1d7cf86 --- /dev/null +++ b/node_modules/mathjs/docs/datatypes/units.md @@ -0,0 +1,444 @@ +# Units + +Math.js supports units. Units can be used to do calculations and to perform +conversions. + +## Usage + +Units can be created using the function `math.unit`. This function accepts +either a single string argument containing a value and unit, or two arguments, +the first being a numeric value and the second a string containing a unit. +Most units support prefixes like `k` or `kilo`, and many units have both a +full name and an abbreviation. The returned object is a `Unit`. + +Syntax: + +```js +math.unit(value: number, name: string) : Unit +math.unit(unit: string) : Unit +math.unit(unit: Unit) : Unit +``` + +Example usage: + +```js +const a = math.unit(45, 'cm') // Unit 450 mm +const b = math.unit('0.1 kilogram') // Unit 100 gram +const c = math.unit('2 inch') // Unit 2 inch +const d = math.unit('90 km/h') // Unit 90 km/h +const e = math.unit('101325 kg/(m s^2)') // Unit 101325 kg / (m s^2) + +const d = c.to('cm') // Unit 5.08 cm +b.toNumber('gram') // Number 100 +math.number(b, 'gram') // Number 100 + +c.equals(a) // false +c.equals(d) // true +c.equalBase(a) // true +c.equalBase(b) // false + +d.toString() // String "5.08 cm" +``` + +Use care when creating a unit with multiple terms in the denominator. Implicit multiplication has the same operator precedence as explicit multiplication and division, which means these three expressions are identical: + +```js +// These three are identical +const correct1 = math.unit('8.314 m^3 Pa / mol / K') // Unit 8.314 (m^3 Pa) / (mol K) +const correct2 = math.unit('8.314 (m^3 Pa) / (mol K)') // Unit 8.314 (m^3 Pa) / (mol K) +const correct3 = math.unit('8.314 (m^3 * Pa) / (mol * K)') // Unit 8.314 (m^3 Pa) / (mol K) +``` +But this expression, which omits the second `/` between `mol` and `K`, results in the wrong value: + +```js +// Missing the second '/' between 'mol' and 'K' +const incorrect = math.unit('8.314 m^3 Pa / mol K') // Unit 8.314 (m^3 Pa K) / mol +``` + +## Calculations + +The operations that support units are `add`, `subtract`, `multiply`, `divide`, `pow`, `abs`, `sqrt`, `square`, `cube`, and `sign`. +Trigonometric functions like `cos` are also supported when the argument is an angle. + +```js +const a = math.unit(45, 'cm') // Unit 450 mm +const b = math.unit('0.1m') // Unit 100 mm +math.add(a, b) // Unit 0.65 m +math.multiply(b, 2) // Unit 200 mm + +const c = math.unit(45, 'deg') // Unit 45 deg +math.cos(c) // Number 0.7071067811865476 + +// Kinetic energy of average sedan on highway +const d = math.unit('80 mi/h') // Unit 80 mi/h +const e = math.unit('2 tonne') // Unit 2 tonne +const f = math.multiply(0.5, math.multipy(math.pow(d, 2), e)) + // 1.2790064742399996 MJ +``` + +Operations with arrays are supported too: + +```js +// Force on a charged particle moving through a magnetic field +const B = math.evaluate('[1, 0, 0] T') // [1 T, 0 T, 0 T] +const v = math.evaluate('[0, 1, 0] m/s') // [0 m / s, 1 m / s, 0 m / s] +const q = math.evaluate('1 C') // 1 C + +const F = math.multiply(q, math.cross(v, B)) // [0 N, 0 N, -1 N] +``` + +All arithmetic operators act on the value of the unit as it is represented in SI units. +This may lead to surprising behavior when working with temperature scales like `celsius` (or `degC`) and `fahrenheit` (or `degF`). +In general you should avoid calculations using `celsius` and `fahrenheit`. Rather, use `kelvin` (or `K`) and `rankine` (or `degR`) instead. +This example highlights some problems when using `celsius` and `fahrenheit` in calculations: + +```js +const T_14F = math.unit('14 degF') // Unit 14 degF (263.15 K) +const T_28F = math.multiply(T1, 2) // Unit 487.67 degF (526.3 K), not 28 degF + +const Tnegative = math.unit(-13, 'degF') // Unit -13 degF (248.15 K) +const Tpositive = math.abs(T1) // Unit -13 degF (248.15 K), not 13 degF + +const Trate1 = math.evaluate('5 (degC/hour)') // Unit 5 degC/hour +const Trate2 = math.evaluate('(5 degC)/hour') // Unit 278.15 degC/hour +``` + +The expression parser supports units too. This is described in the section about +units on the page [Syntax](../expressions/syntax.md#units). + +## User-Defined Units + +You can add your own units to Math.js using the `math.createUnit` function. The following example defines a new unit `furlong`, then uses the user-defined unit in a calculation: + +```js +math.createUnit('furlong', '220 yards') +math.evaluate('1 mile to furlong') // 8 furlong +``` + +If you cannot express the new unit in terms of any existing unit, then the second argument can be omitted. In this case, a new *base unit* is created: + +```js +// A 'foo' cannot be expressed in terms of any other unit. +math.createUnit('foo') +math.evaluate('8 foo * 4 feet') // 32 foo feet +``` + +The second argument to `createUnit` can also be a configuration object consisting of the following properties: + +* **definition** A `string` or `Unit` which defines the user-defined unit in terms of existing built-in or user-defined units. If omitted, a new base unit is created. +* **prefixes** A `string` indicating which prefixes math.js should use with the new unit. Possible values are `'none'`, `'short'`, `'long'`, `'binary_short'`, or `'binary_long'`. Default is `'none'`. +* **offset** A value applied when converting to the unit. This is very helpful for temperature scales that do not share a zero with the absolute temperature scale. For example, if we were defining fahrenheit for the first time, we would use: `math.createUnit('fahrenheit', {definition: '0.555556 kelvin', offset: 459.67})` +* **aliases** An array of strings to alias the new unit. Example: `math.createUnit('knot', {definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts']})` +* **baseName** A `string` that specifies the name of the new dimension in case one needs to be created. Every unit in math.js has a dimension: length, time, velocity, etc. If the unit's `definition` doesn't match any existing dimension, or it is a new base unit, then `createUnit` will create a new dimension with the name `baseName` and assign it to the new unit. The default is to append `'_STUFF'` to the unit's name. If the unit already matches an existing dimension, this option has no effect. + +An optional `options` object can also be supplied as the last argument to `createUnits`. Currently only the `override` option is supported: + +```js +// Redefine the mile (would not be the first time in history) +math.createUnit('mile', '1609.347218694 m', {override: true}) +``` +Base units created without specifying a definition cannot be overridden. + +### Create several units at once +Multiple units can defined using a single call to `createUnit` by passing an object map as the first argument, where each key in the object is the name of a new unit and the value is either a string defining the unit, or an object with the configuration properties listed above. If the value is an empty string or an object lacking a definition property, a new base unit is created. + +For example: + +```js +math.createUnit( { + foo: { + prefixes: 'long', + baseName: 'essence-of-foo' + }, + bar: '40 foo', + baz: { + definition: '1 bar/hour', + prefixes: 'long' + } +}, +{ + override: true +}) +math.evaluate('50000 kilofoo/s') // 4.5 gigabaz +``` + +### Return Value +`createUnit` returns the created unit, or, when multiple units are created, the last unit created. Since `createUnit` is also compatible with the expression parser, this allows you to do things like this: + +```js +math.evaluate('45 mile/hour to createUnit("knot", "0.514444m/s")') +// 39.103964668651976 knot +``` + +### Support of custom characters in unit names +Per default, the name of a new unit: +- should start by a latin (A-Z or a-z) character +- should contain only numeric (0-9) or latin characters + +It is possible to allow the usage of special characters (such as Greek alphabet, cyrillic alphabet, any Unicode symbols, etc.) by overriding the `Unit.isValidAlpha` static method. For example: +```js +const isAlphaOriginal = math.Unit.isValidAlpha +const isGreekLowercaseChar = function (c) { + const charCode = c.charCodeAt(0) + return charCode > 944 && charCode < 970 +} +math.Unit.isValidAlpha = function (c) { + return isAlphaOriginal(c) || isGreekLowercaseChar(c) +} + +math.createUnit('θ', '1 rad') +math.evaluate('1θ + 3 deg').toNumber('deg') // 60.29577951308232 +``` + +## API +A `Unit` object contains the following functions: + +### unit.clone() +Clone the unit, returns a new unit with the same parameters. + +### unit.equalBase(unit) +Test whether a unit has the same base as an other unit: +length, mass, etc. + +### unit.equals(unit) +Test whether a unit equals an other unit. Units are equal +when they have the same base and same value when normalized to SI units. + +### unit.format([options]) +Get a string representation of the unit. The function +will determine the best fitting prefix for the unit. See the [Format](../reference/functions/format.md) +page for available options. + +### unit.fromJSON(json) +Revive a unit from a JSON object. Accepts +An object `{mathjs: 'Unit', value: number, unit: string, fixPrefix: boolean}`, +where the property `mathjs` and `fixPrefix` are optional. +Used when deserializing a unit, see [Serialization](../core/serialization.md). + +### unit.splitUnit(parts) +Split a unit into the specified parts. For example: + +```js +const u = math.unit(1, 'm') +u.splitUnit(['ft', 'in']) // 3 feet,3.3700787401574765 inch +``` + +### unit.to(unitName) +Convert the unit to a specific unit name. Returns a clone of +the unit with a fixed prefix and unit. + +### unit.toJSON() +Returns a JSON representation of the unit, with signature +`{mathjs: 'Unit', value: number, unit: string, fixPrefix: boolean}`. +Used when serializing a unit, see [Serialization](../core/serialization.md). + +### unit.toNumber(unitName) +Get the value of a unit when converted to the +specified unit (a unit with optional prefix but without value). +The type of the returned value is always `number`. + +### unit.toNumeric(unitName) +Get the value of a unit when converted to the +specified unit (a unit with optional prefix but without value). +The type of the returned value depends on how the unit was created and +can be `number`, `Fraction`, or `BigNumber`. + +### unit.toSI() +Returns a clone of a unit represented in SI units. Works with units with or without a value. + +### unit.toString() +Get a string representation of the unit. The function will +determine the best fitting prefix for the unit. + +## Unit reference + +This section lists all available units, prefixes, and physical constants. These can be used via the Unit object, or via `math.evaluate()`. + +## Reference + +Math.js comes with the following built-in units. + +Base | Unit +------------------- | --- +Length | meter (m), inch (in), foot (ft), yard (yd), mile (mi), link (li), rod (rd), chain (ch), angstrom, mil +Surface area | m2, sqin, sqft, sqyd, sqmi, sqrd, sqch, sqmil, acre, hectare +Volume | m3, litre (l, L, lt, liter), cc, cuin, cuft, cuyd, teaspoon, tablespoon +Liquid volume | minim (min), fluiddram (fldr), fluidounce (floz), gill (gi), cup (cp), pint (pt), quart (qt), gallon (gal), beerbarrel (bbl), oilbarrel (obl), hogshead, drop (gtt) +Angles | rad (radian), deg (degree), grad (gradian), cycle, arcsec (arcsecond), arcmin (arcminute) +Time | second (s, secs, seconds), minute (mins, minutes), hour (h, hr, hrs, hours), day (days), week (weeks), month (months), year (years), decade (decades), century (centuries), millennium (millennia) +Frequency | hertz (Hz) +Mass | gram(g), tonne, ton, grain (gr), dram (dr), ounce (oz), poundmass (lbm, lb, lbs), hundredweight (cwt), stick, stone +Electric current | ampere (A) +Temperature | kelvin (K), celsius (degC), fahrenheit (degF), rankine (degR) +Amount of substance | mole (mol) +Luminous intensity | candela (cd) +Force | newton (N), dyne (dyn), poundforce (lbf), kip +Energy | joule (J), erg, Wh, BTU, electronvolt (eV) +Power | watt (W), hp +Pressure | Pa, psi, atm, torr, bar, mmHg, mmH2O, cmH2O +Electricity and magnetism | ampere (A), coulomb (C), watt (W), volt (V), ohm, farad (F), weber (Wb), tesla (T), henry (H), siemens (S), electronvolt (eV) +Binary | bits (b), bytes (B) + +Note: all time units are based on the Julian year, with one month being 1/12th of a Julian year, a year being one Julian year, a decade being 10 Julian years, a century being 100, and a millennium being 1000. + +Note that all relevant units can also be written in plural form, for example `5 meters` instead of `5 meter` or `10 seconds` instead of `10 second`. + +Surface and volume units can alternatively be expressed in terms of length units raised to a power, for example `100 in^2` instead of `100 sqin`. + +### Prefixes + +The following decimal prefixes are available. + +Name | Abbreviation | Value +------- | ------------- | ----- +deca | da | 1e1 +hecto | h | 1e2 +kilo | k | 1e3 +mega | M | 1e6 +giga | G | 1e9 +tera | T | 1e12 +peta | P | 1e15 +exa | E | 1e18 +zetta | Z | 1e21 +yotta | Y | 1e24 + +Name | Abbreviation | Value +------ | ------------- | ----- +deci | d | 1e-1 +centi | c | 1e-2 +milli | m | 1e-3 +micro | u | 1e-6 +nano | n | 1e-9 +pico | p | 1e-12 +femto | f | 1e-15 +atto | a | 1e-18 +zepto | z | 1e-21 +yocto | y | 1e-24 + +The following binary prefixes are available. +They can be used with units `bits` (`b`) and `bytes` (`B`). + +Name | Abbreviation | Value +---- | ------------ | ----- +kibi | Ki | 1024 +mebi | Mi | 1024^2 +gibi | Gi | 1024^3 +tebi | Ti | 1024^4 +pebi | Pi | 1024^5 +exi | Ei | 1024^6 +zebi | Zi | 1024^7 +yobi | Yi | 1024^8 + +Name | Abbreviation | Value +----- | ------------ | ----- +kilo | k | 1e3 +mega | M | 1e6 +giga | G | 1e9 +tera | T | 1e12 +peta | P | 1e15 +exa | E | 1e18 +zetta | Z | 1e21 +yotta | Y | 1e24 + + +### Physical Constants + +Math.js includes the following physical constants. See [Wikipedia](https://en.wikipedia.org/wiki/Physical_constants) for more information. + + +#### Universal constants + +Name | Symbol | Value | Unit +----------------------|--------------------------------------------------------|-------------------|------------------------------------------------------- +speedOfLight | c | 299792458 | m · s-1 +gravitationConstant | G | 6.6738480e-11 | m3 · kg-1 · s-2 +planckConstant | h | 6.626069311e-34 | J · s +reducedPlanckConstant | h | 1.05457172647e-34 | J · s + + +#### Electromagnetic constants + +Name | Symbol | Value | Unit +--------------------------|--------------------------------------------------|-----------------------|---------------------------------------- +magneticConstant | μ0 | 1.2566370614e-6 | N · A-2 +electricConstant | ε0 | 8.854187817e-12 | F · m-1 +vacuumImpedance | Z0 | 376.730313461 | Ω +coulomb | κ | 8.9875517873681764e9 | N · m2 · C-2 +elementaryCharge | e | 1.60217656535e-19 | C +bohrMagneton | μB | 9.2740096820e-24 | J · T-1 +conductanceQuantum | G0 | 7.748091734625e-5 | S +inverseConductanceQuantum | G0-1 | 12906.403721742 | Ω +magneticFluxQuantum | f0 | 2.06783375846e-15 | Wb +nuclearMagneton | μN | 5.0507835311e-27 | J · T-1 +klitzing | RK | 25812.807443484 | Ω + + + + +#### Atomic and nuclear constants + +Name | Symbol | Value | Unit +------------------------|------------------------------|-----------------------|---------------------------------- +bohrRadius | a0 | 5.291772109217e-11 | m +classicalElectronRadius | re | 2.817940326727e-15 | m +electronMass | me | 9.1093829140e-31 | kg +fermiCoupling | GF | 1.1663645e-5 | GeV-2 +fineStructure | α | 7.297352569824e-3 | - +hartreeEnergy | Eh | 4.3597443419e-18 | J +protonMass | mp | 1.67262177774e-27 | kg +deuteronMass | md | 3.3435830926e-27 | kg +neutronMass | mn | 1.6749271613e-27 | kg +quantumOfCirculation | h / (2me) | 3.636947552024e-4 | m2 · s-1 +rydberg | R | 10973731.56853955 | m-1 +thomsonCrossSection | | 6.65245873413e-29 | m2 +weakMixingAngle | | 0.222321 | - +efimovFactor | | 22.7 | - + + +#### Physico-chemical constants + +Name | Symbol | Value | Unit +--------------------|------------------------------|---------------------|-------------------------------------------- +atomicMass | mu | 1.66053892173e-27 | kg +avogadro | NA | 6.0221412927e23 | mol-1 +boltzmann | k | 1.380648813e-23 | J · K-1 +faraday | F | 96485.336521 | C · mol-1 +firstRadiation | c1 | 3.7417715317e-16 | W · m2 +loschmidt | n0 | 2.686780524e25 | m-3 +gasConstant | R | 8.314462175 | J · K-1 · mol-1 +molarPlanckConstant | NA · h| 3.990312717628e-10| J · s · mol-1 +molarVolume | Vm | 2.241396820e-10 | m3 · mol-1 +sackurTetrode | | -1.164870823 | - +secondRadiation | c2 | 1.438777013e-2 | m · K +stefanBoltzmann | σ | 5.67037321e-8 | W · m-2 · K-4 +wienDisplacement | b | 2.897772126e-3 | m · K + + + +Note that the values of `loschmidt` and `molarVolume` are at `T = 273.15 K` and `p = 101.325 kPa`. +The value of `sackurTetrode` is at `T = 1 K` and `p = 101.325 kPa`. + + +#### Adopted values + +Name | Symbol | Value | Unit +--------------|------------------------------|---------|------------------------- +molarMass | Mu | 1e-3 | kg · mol-1 +molarMassC12 | M(12C) | 1.2e-2 | kg · mol-1 +gravity | gn | 9.80665 | m · s-2 +atm | atm | 101325 | Pa + + +#### Natural units + +Name | Symbol | Value | Unit +------------------|-----------------------|--------------------|----- +planckLength | lP | 1.61619997e-35 | m +planckMass | mP | 2.1765113e-8 | kg +planckTime | tP | 5.3910632e-44 | s +planckCharge | qP | 1.87554595641e-18 | C +planckTemperature | TP | 1.41683385e+32 | K diff --git a/node_modules/mathjs/docs/expressions/algebra.md b/node_modules/mathjs/docs/expressions/algebra.md new file mode 100644 index 0000000..943680c --- /dev/null +++ b/node_modules/mathjs/docs/expressions/algebra.md @@ -0,0 +1,110 @@ +# Algebra (symbolic computation) + +math.js has built-in support for symbolic computation ([CAS](https://www.wikiwand.com/en/Computer_algebra_system)). It can parse expressions into an expression tree and do algebraic operations like simplification and derivation on the tree. + +> It's worth mentioning an excellent extension on math.js here: [mathsteps](https://github.com/socraticorg/mathsteps), a step-by-step math solver library that is focused on pedagogy (how best to teach). The math problems it focuses on are pre-algebra and algebra problems involving simplifying expressions. + + +## Simplify + +The function [`math.simplify`](../reference/functions/simplify.md) simplifies an expression tree: + +```js +// simplify an expression +console.log(math.simplify('3 + 2 / 4').toString()) // '7 / 2' +console.log(math.simplify('2x + 3x').toString()) // '5 * x' +console.log(math.simplify('x^2 + x + 3 + x^2').toString()) // '2 * x ^ 2 + x + 3' +console.log(math.simplify('x * y * -x / (x ^ 2)').toString()) // '-y' +``` + +The function accepts either a string or an expression tree (`Node`) as input, and outputs a simplified expression tree (`Node`). This node tree can be transformed and evaluated as described in detail on the page [Expression trees](expression_trees.md). + +```js +// work with an expression tree, evaluate results +const f = math.parse('2x + x') +const simplified = math.simplify(f) +console.log(simplified.toString()) // '3 * x' +console.log(simplified.evaluate({x: 4})) // 12 +``` + +Note that `simplify` has an optional argument `scope` that allows the definitions of variables in the expression (as numeric values, or as further expressions) to be specified and used in the simplification, e.g. continuing the previous example, + +```js +console.log(math.simplify(f, {x: 4}).toString()) // 12 +console.log(math.simplify(f, {x: math.parse('y+z')}).toString()) // '3*(y+z)' +``` + +In general, simplification is an inherently dfficult problem; in fact, for certain classes of expressions and algebraic equivalences, it is undecidable whether a given expression is equivalent to zero. Moreover, simplification generally depends on the properties of the operations involved; since multiplication (for example) may have different properties (e.g., it might or might not be commutative) depending on the domain under consideration, different simplifications might be appropriate. + +As a result, `simplify()` has an additional optional argument, `options`, which controls its behavior. This argument is an object specifying any of various properties concerning the simplification process. See the [detailed documentation](../reference/functions/simplify.md) for a complete list, but currently the two most important properties are as follows. Note that the `options` argument may only be specified if the `scope` is as well. + +- `exactFractions` - a boolean which specifies whether non-integer numerical constants should be simplified to rational numbers when possible (true), or always converted to decimal notation (false). +- `context` - an object whose keys are the names of operations ('add', 'multiply', etc.) and whose values specify algebraic properties of the corresponding operation (currently any of 'total', 'trivial', 'commutative', and 'associative'). Simplifications will only be performed if the properties they rely on are true in the given context. For example, +```js +const expr = math.parse('x*y-y*x') +console.log(math.simplify(expr).toString()) // 0; * is commutative by default +console.log(math.simplify(expr, {}, {context: {multiply: {commutative: false}}})) + // 'x*y-y*x'; the order of the right multiplication can't be reversed. +``` + +Note that the default context is very permissive (allows a lot of simplifications) but that there is also a `math.simplify.realContext` that only allows simplifications that are guaranteed to preserve the value of the expression on all real numbers: +```js +const rational = math.parse('(x-1)*x/(x-1)') +console.log(math.simplify(expr, {}, {context: math.simplify.realContext}) + // '(x-1)*x/(x-1)'; canceling the 'x-1' makes the expression defined at 1 +``` + +For more details on the theory of expression simplification, see: + +- [Strategies for simplifying math expressions (Stackoverflow)](https://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions) +- [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification) + + +## Derivative + +The function [`math.derivative`](../reference/functions/derivative.md) finds the symbolic derivative of an expression: + +```js +// calculate a derivative +console.log(math.derivative('2x^2 + 3x + 4', 'x').toString()) // '4 * x + 3' +console.log(math.derivative('sin(2x)', 'x').toString()) // '2 * cos(2 * x)' +``` + +Similar to the function `math.simplify`, `math.derivative` accepts either a string or an expression tree (`Node`) as input, and outputs a simplified expression tree (`Node`). + +```js +// work with an expression tree, evaluate results +const h = math.parse('x^2 + x') +const x = math.parse('x') +const dh = math.derivative(h, x) +console.log(dh.toString()) // '2 * x + 1' +console.log(dh.evaluate({x: 3})) // '7' +``` + +The rules used by `math.derivative` can be found on Wikipedia: + +- [Differentiation rules (Wikipedia)](https://en.wikipedia.org/wiki/Differentiation_rules) + + +## Rationalize + +The function [`math.transform`](../reference/functions/transform.md) transforms a rationalizable expression in a rational fraction. +If rational fraction is one variable polynomial then converts the numerator and denominator in canonical form, with decreasing exponents, returning the coefficients of numerator. + +```js + +math.rationalize('2x/y - y/(x+1)') + // (2*x^2-y^2+2*x)/(x*y+y) +math.rationalize('(2x+1)^6') + // 64*x^6+192*x^5+240*x^4+160*x^3+60*x^2+12*x+1 +math.rationalize('2x/( (2x-1) / (3x+2) ) - 5x/ ( (3x+4) / (2x^2-5) ) + 3') + // -20*x^4+28*x^3+104*x^2+6*x-12)/(6*x^2+5*x-4) + +math.rationalize('x+x+x+y',{y:1}) // 3*x+1 +math.rationalize('x+x+x+y',{}) // 3*x+y + +const ret = math.rationalize('x+x+x+y',{},true) + // ret.expression=3*x+y, ret.variables = ["x","y"] +const ret = math.rationalize('-2+5x^2',{},true) + // ret.expression=5*x^2-2, ret.variables = ["x"], ret.coefficients=[-2,0,5] +``` \ No newline at end of file diff --git a/node_modules/mathjs/docs/expressions/customization.md b/node_modules/mathjs/docs/expressions/customization.md new file mode 100644 index 0000000..20895b2 --- /dev/null +++ b/node_modules/mathjs/docs/expressions/customization.md @@ -0,0 +1,379 @@ +# Customization + +Besides parsing and evaluating expressions, the expression parser supports +a number of features to customize processing and evaluation of expressions +and outputting expressions. + +On this page: + +- [Function transforms](#function-transforms) +- [Custom argument parsing](#custom-argument-parsing) +- [Custom LaTeX handlers](#custom-latex-handlers) +- [Custom HTML, LaTeX and string output](#custom-html-latex-and-string-output) +- [Customize supported characters](#customize-supported-characters) + +## Function transforms + +It is possible to preprocess function arguments and post process a functions +return value by writing a *transform* for the function. A transform is a +function wrapping around a function to be transformed or completely replaces +a function. + +For example, the functions for math.js use zero-based matrix indices (as is +common in programing languages), but the expression parser uses one-based +indices. To enable this, all functions dealing with indices have a transform, +which changes input from one-based to zero-based, and transforms output (and +error message) from zero-based to one-based. + +```js +// using plain JavaScript, indices are zero-based: +const a = [[1, 2], [3, 4]] // a 2x2 matrix +math.subset(a, math.index(0, 1)) // returns 2 + +// using the expression parser, indices are transformed to one-based: +const a = [[1, 2], [3, 4]] // a 2x2 matrix +let scope = { + a: a +} +math.evaluate('subset(a, index(1, 2))', scope) // returns 2 +``` + +To create a transform for a function, the transform function must be attached +to the function as property `transform`: + +```js +import { create, all } from 'mathjs' +const math = create(all) + +// create a function +function addIt(a, b) { + return a + b +} + +// attach a transform function to the function addIt +addIt.transform = function (a, b) { + console.log('input: a=' + a + ', b=' + b) + // we can manipulate input here before executing addIt + + const res = addIt(a, b) + + console.log('result: ' + res) + // we can manipulate result here before returning + + return res +} + +// import the function into math.js +math.import({ + addIt: addIt +}) + +// use the function via the expression parser +console.log('Using expression parser:') +console.log('2+4=' + math.evaluate('addIt(2, 4)')) +// This will output: +// +// input: a=2, b=4 +// result: 6 +// 2+4=6 + +// when used via plain JavaScript, the transform is not invoked +console.log('') +console.log('Using plain JavaScript:') +console.log('2+4=' + math.addIt(2, 4)) +// This will output: +// +// 6 +``` + +Functions with a transform must be imported in the `math` namespace, as they +need to be processed at compile time. They are not supported when passed via a +scope at evaluation time. + + +## Custom argument parsing + +The expression parser of math.js has support for letting functions +parse and evaluate arguments themselves, instead of calling them with +evaluated arguments. This is useful for example when creating a function +like `plot(f(x), x)` or `integrate(f(x), x, start, end)`, where some of the +arguments need to be processed in a special way. In these cases, the expression +`f(x)` will be evaluated repeatedly by the function, and `x` is not evaluated +but used to specify the variable looping over the function `f(x)`. + +Functions having a property `rawArgs` with value `true` are treated in a special +way by the expression parser: they will be invoked with unevaluated arguments, +allowing the function to process the arguments in a customized way. Raw +functions are called as: + +``` +rawFunction(args: Node[], math: Object, scope: Object) +``` + +Where : + +- `args` is an Array with nodes of the parsed arguments. +- `math` is the math namespace against which the expression was compiled. +- `scope` is a shallow _copy_ of the `scope` object provided when evaluating + the expression, optionally extended with nested variables like a function + parameter `x` of in a custom defined function like `f(x) = x^2`. + +Raw functions must be imported in the `math` namespace, as they need to be +processed at compile time. They are not supported when passed via a scope +at evaluation time. + +A simple example: + +```js +function myFunction(args, math, scope) { + // get string representation of the arguments + const str = args.map(function (arg) { + return arg.toString() + }) + + // evaluate the arguments + const res = args.map(function (arg) { + return arg.compile().evaluate(scope) + }) + + return 'arguments: ' + str.join(',') + ', evaluated: ' + res.join(',') +} + +// mark the function as "rawArgs", so it will be called with unevaluated arguments +myFunction.rawArgs = true + +// import the new function in the math namespace +math.import({ + myFunction: myFunction +}) + +// use the function +math.evaluate('myFunction(2 + 3, sqrt(4))') +// returns 'arguments: 2 + 3, sqrt(4), evaluated: 5, 2' +``` + +## Custom LaTeX handlers + +You can attach a `toTex` property to your custom functions before importing them to define their LaTeX output. This +`toTex` property can be a handler in the format described in the next section 'Custom LaTeX and String conversion' +or a template string similar to ES6 templates. + +### Template syntax + +- `${name}`: Gets replaced by the name of the function +- `${args}`: Gets replaced by a comma separated list of the arguments of the function. +- `${args[0]}`: Gets replaced by the first argument of a function +- `$$`: Gets replaced by `$` + +#### Example + +```js +const customFunctions = { + plus: function (a, b) { + return a + b + }, + minus: function (a, b) { + return a - b + }, + binom: function (n, k) { + return 1 + } +} + +customFunctions.plus.toTex = '${args[0]}+${args[1]}' //template string +customFunctions.binom.toTex = '\\mathrm{${name}}\\left(${args}\\right)' //template string +customFunctions.minus.toTex = function (node, options) { //handler function + return node.args[0].toTex(options) + node.name + node.args[1].toTex(options) +} + +math.import(customFunctions) + +math.parse('plus(1,2)').toTex() // '1+2' +math.parse('binom(1,2)').toTex() // '\\mathrm{binom}\\left(1,2\\right)' +math.parse('minus(1,2)').toTex() // '1minus2' +``` + +## Custom HTML, LaTeX and string output + +All expression nodes have a method `toTex` and `toString` to output an expression respectively in HTML or LaTex format or as regular text . +The functions `toHTML`, `toTex` and `toString` accept an `options` argument to customise output. This object is of the following form: + +```js +{ + parenthesis: 'keep', // parenthesis option + handler: someHandler, // handler to change the output + implicit: 'hide' // how to treat implicit multiplication +} +``` + +### Parenthesis + +The `parenthesis` option changes the way parentheses are used in the output. There are three options available: + +- `keep` Keep the parentheses from the input and display them as is. This is the default. +- `auto` Only display parentheses that are necessary. Mathjs tries to get rid of as much parentheses as possible. +- `all` Display all parentheses that are given by the structure of the node tree. This makes the output precedence unambiguous. + +There's two ways of passing callbacks: + +1. Pass an object that maps function names to callbacks. Those callbacks will be used for FunctionNodes with +functions of that name. +2. Pass a function to `toTex`. This function will then be used for every node. + +```js +const expression = math.parse('(1+1+1)') + +expression.toString() // (1 + 1 + 1) +expression.toString({parenthesis: 'keep'}) // (1 + 1 + 1) +expression.toString({parenthesis: 'auto'}) // 1 + 1 + 1 +expression.toString({parenthesis: 'all'}) // (1 + 1) + 1 +``` + +### Handler + +You can provide the `toTex` and `toString` functions of an expression with your own custom handlers that override the internal behaviour. This is especially useful to provide LaTeX/string output for your own custom functions. This can be done in two ways: + +1. Pass an object that maps function names to callbacks. Those callbacks will be used for FunctionNodes that contain functions with that name. +2. Pass a callback directly. This callback will run for every node, so you can replace the output of anything you like. + +A callback function has the following form: + +```js +function callback (node, options) { + ... +} +``` +Where `options` is the object passed to `toHTML`/`toTex`/`toString`. Don't forget to pass this on to the child nodes, and `node` is a reference to the current node. + +If a callback returns nothing, the standard output will be used. If your callback returns a string, this string will be used. + +**Although the following examples use `toTex`, it works for `toString` and `toHTML` in the same way** + +#### Examples for option 1 + +```js +const customFunctions = { + binomial: function (n, k) { + //calculate n choose k + // (do some stuff) + return result + } +} + +const customLaTeX = { + 'binomial': function (node, options) { //provide toTex for your own custom function + return '\\binom{' + node.args[0].toTex(options) + '}{' + node.args[1].toTex(options) + '}' + }, + 'factorial': function (node, options) { //override toTex for builtin functions + return 'factorial\\left(' + node.args[0] + '\\right)' + } +} +``` + +You can simply use your custom toTex functions by passing them to `toTex`: + +```js +math.import(customFunctions) +const expression = math.parse('binomial(factorial(2),1)') +const latex = expression.toTex({handler: customLaTeX}) +// latex now contains "\binom{factorial\\left(2\\right)}{1}" +``` + +#### Examples for option 2: + +```js +function customLaTeX(node, options) { + if ((node.type === 'OperatorNode') && (node.fn === 'add')) { + //don't forget to pass the options to the toTex functions + return node.args[0].toTex(options) + ' plus ' + node.args[1].toTex(options) + } + else if (node.type === 'ConstantNode') { + if (node.value === 0) { + return '\\mbox{zero}' + } + else if (node.value === 1) { + return '\\mbox{one}' + } + else if (node.value === 2) { + return '\\mbox{two}' + } + else { + return node.value + } + } +} + +const expression = math.parse('1+2') +const latex = expression.toTex({handler: customLaTeX}) +// latex now contains '\mbox{one} plus \mbox{two}' +``` + +Another example in conjunction with custom functions: + +```js +const customFunctions = { + binomial: function (n, k) { + //calculate n choose k + // (do some stuff) + return result + } +} + +function customLaTeX(node, options) { + if ((node.type === 'FunctionNode') && (node.name === 'binomial')) { + return '\\binom{' + node.args[0].toTex(options) + '}{' + node.args[1].toTex(options) + '}' + } +} + +math.import(customFunctions) +const expression = math.parse('binomial(2,1)') +const latex = expression.toTex({handler: customLaTeX}) +// latex now contains "\binom{2}{1}" +``` + +### Implicit multiplication + +You can change the way that implicit multiplication is converted to a string or LaTeX. The two options are `hide`, to not show a multiplication operator for implicit multiplication and `show` to show it. + +Example: + +```js +const node = math.parse('2a') + +node.toString() // '2 a' +node.toString({implicit: 'hide'}) // '2 a' +node.toString({implicit: 'show'}) // '2 * a' + +node.toTex() // '2~ a' +node.toTex({implicit: 'hide'}) // '2~ a' +node.toTex({implicit: 'show'}) // '2\\cdot a' +``` + + +## Customize supported characters + +It is possible to customize the characters allowed in symbols and digits. +The `parse` function exposes the following test functions: + +- `math.parse.isAlpha(c, cPrev, cNext)` +- `math.parse.isWhitespace(c, nestingLevel)` +- `math.parse.isDecimalMark(c, cNext)` +- `math.parse.isDigitDot(c)` +- `math.parse.isDigit(c)` + +The exact signature and implementation of these functions can be looked up in +the [source code of the parser](https://github.com/josdejong/mathjs/blob/master/lib/expression/parse.js). The allowed alpha characters are described here: [Constants and variables](syntax.md#constants-and-variables). + +For example, the phone character is not supported by default. It can be enabled +by replacing the `isAlpha` function: + +```js +const isAlphaOriginal = math.parse.isAlpha +math.parse.isAlpha = function (c, cPrev, cNext) { + return isAlphaOriginal(c, cPrev, cNext) || (c === '\u260E') +} + +// now we can use the \u260E (phone) character in expressions +const result = math.evaluate('\u260Efoo', {'\u260Efoo': 42}) // returns 42 +console.log(result) +``` diff --git a/node_modules/mathjs/docs/expressions/expression_trees.md b/node_modules/mathjs/docs/expressions/expression_trees.md new file mode 100644 index 0000000..f2ce692 --- /dev/null +++ b/node_modules/mathjs/docs/expressions/expression_trees.md @@ -0,0 +1,700 @@ +# Expression trees + +When parsing an expression via `math.parse(expr)`, math.js generates an +expression tree and returns the root node of the tree. An expression tree can +be used to analyze, manipulate, and evaluate expressions. + +Example: + +```js +const node = math.parse('sqrt(2 + x)') +``` + +In this case, the expression `sqrt(2 + x)` is parsed as: + +``` + FunctionNode sqrt + | + OperatorNode + + / \ + ConstantNode 2 x SymbolNode +``` + +Alternatively, this expression tree can be build by manually creating nodes: + +```js +const node1 = new math.ConstantNode(2) +const node2 = new math.SymbolNode('x') +const node3 = new math.OperatorNode('+', 'add', [node1, node2]) +const node4 = new math.FunctionNode('sqrt', [node3]) +``` + +The resulting expression tree with root node `node4` is equal to the expression +tree generated by `math.parse('sqrt(2 + x)')`. + + +## API + +### Methods + +All nodes have the following methods: + +- `clone() : Node` + + Create a shallow clone of the node. + The node itself is cloned, its childs are not cloned. + +- `cloneDeep() : Node` + + Create a deep clone of the node. + Both the node as well as all its childs are cloned recursively. + +- `compile() : Object` + + Compile an expression into optimized JavaScript code. `compile` returns an + object with a function `evaluate([scope])` to evaluate. Example: + + ```js + const node = math.parse('2 + x') // returns the root Node of an expression tree + const code = node.compile() // returns {evaluate: function (scope) {...}} + const evaluate = code.evaluate({x: 3}) // returns 5 + ``` + +- `evaluate([scope]) : Object` + + Compile and evaluate an expression, this is the equivalent of doing + `node.compile().evaluate(scope)`. Example: + + ```js + const node = math.parse('2 + x') // returns the root Node of an expression tree + const evaluate = node.evaluate({x: 3}) // returns 5 + ``` + +- `equals(other: Node) : boolean` + + Test whether this node equals an other node. Does a deep comparison of the + values of both nodes. + +- `filter(callback: function) : Node[]` + + Recursively filter nodes in an expression tree. The `callback` function is + called as `callback(node: Node, path: string, parent: Node) : boolean` for + every node in the tree, and must return a boolean. The function `filter` + returns an array with nodes for which the test returned true. + Parameter `path` is a string containing a relative JSON Path. + + Example: + + ```js + const node = math.parse('x^2 + x/4 + 3*y') + const filtered = node.filter(function (node) { + return node.isSymbolNode && node.name === 'x' + }) + // returns an array with two entries: two SymbolNodes 'x' + ``` + +- `forEach(callback: function) : Node[]` + + Execute a callback for each of the child nodes of this node. The `callback` + function is called as `callback(child: Node, path: string, parent: Node)`. + Parameter `path` is a string containing a relative JSON Path. + + See also `traverse`, which is a recursive version of `forEach`. + + Example: + + ```js + const node = math.parse('3 * x + 2') + node.forEach(function (node, path, parent) { + switch (node.type) { + case 'OperatorNode': + console.log(node.type, node.op) + break + case 'ConstantNode': + console.log(node.type, node.value) + break + case 'SymbolNode': + console.log(node.type, node.name) + break + default: + console.log(node.type) + } + }) + // outputs: + // OperatorNode * + // ConstantNode 2 + ``` + +- `map(callback: function) : Node[]` + + Transform a node. Creates a new Node having it's childs be the results of + calling the provided callback function for each of the childs of the original + node. The `callback` function is called as `callback(child: Node, path: string, + parent: Node)` and must return a Node. Parameter `path` is a string containing + a relative JSON Path. + + See also `transform`, which is a recursive version of `map`. + +- `toHTML(options: object): string` + + Get a HTML representation of the parsed expression. Example: + + ```js + const node = math.parse('sqrt(2/3)') + node.toHTML() + // returns + // sqrt + // ( + // 2 + // / + // 3 + // ) + ``` + + Information about the available HTML classes in [HTML Classes](html_classes.md). + Information about the options in [Customization](customization.md#custom-html-latex-and-string-output). + +- `toString(options: object) : string` + + Get a string representation of the parsed expression. This is not exactly + the same as the original input. Example: + + ```js + const node = math.parse('3+4*2') + node.toString() // returns '3 + (4 * 2)' + ``` + + Information about the options in [Customization](customization.md#custom-html-latex-and-string-output). + +- `toTex(options: object): string` + + Get a [LaTeX](https://en.wikipedia.org/wiki/LaTeX) representation of the + expression. Example: + + ```js + const node = math.parse('sqrt(2/3)') + node.toTex() // returns '\sqrt{\frac{2}{3}}' + ``` + + Information about the options in [Customization](customization.md#custom-html-latex-and-string-output). + +- `transform(callback: function)` + + Recursively transform an expression tree via a transform function. Similar + to `Array.map`, but recursively executed on all nodes in the expression tree. + The callback function is a mapping function accepting a node, and returning + a replacement for the node or the original node. Function `callback` is + called as `callback(node: Node, path: string, parent: Node)` for every node + in the tree, and must return a `Node`. Parameter `path` is a string containing + a relative JSON Path. + + The transform function will stop iterating when a node is replaced by the + callback function, it will not iterate over replaced nodes. + + For example, to replace all nodes of type `SymbolNode` having name 'x' with a + ConstantNode with value `3`: + + ```js + const node = math.parse('x^2 + 5*x') + const transformed = node.transform(function (node, path, parent) { + if (node.isSymbolNode && node.name === 'x') { + return new math.ConstantNode(3) + } + else { + return node + } + }) + transformed.toString() // returns '3 ^ 2 + 5 * 3' + ``` + +- `traverse(callback)` + + Recursively traverse all nodes in a node tree. Executes given callback for + this node and each of its child nodes. Similar to `Array.forEach`, except + recursive. + The callback function is a mapping function accepting a node, and returning + a replacement for the node or the original node. Function `callback` is + called as `callback(node: Node, path: string, parent: Node)` for every node + in the tree. Parameter `path` is a string containing a relative JSON Path. + Example: + + ```js + const node = math.parse('3 * x + 2') + node.traverse(function (node, path, parent) { + switch (node.type) { + case 'OperatorNode': + console.log(node.type, node.op) + break + case 'ConstantNode': + console.log(node.type, node.value) + break + case 'SymbolNode': + console.log(node.type, node.name) + break + default: + console.log(node.type) + } + }) + // outputs: + // OperatorNode + + // OperatorNode * + // ConstantNode 3 + // SymbolNode x + // ConstantNode 2 + ``` + + +### Properties + +Each `Node` has the following properties: + +- `comment: string` + + A string holding a comment if there was any in the expression, or else the + string will be empty string. A comment can be attached to the root node of + an expression or to each of the childs nodes of a `BlockNode`. + +- `isNode: true` + + Is defined with value `true` on Nodes. Additionally, each type of node + adds it's own flag, for example a `SymbolNode` as has a property + `isSymbolNode: true`. + +- `type: string` + + The type of the node, for example `'SymbolNode'` in case of a `SymbolNode`. + + +## Nodes + +math.js has the following types of nodes. All nodes are available at the +namespace `math`. + + +### AccessorNode + +Construction: + +``` +new AccessorNode(object: Node, index: IndexNode) +``` + +Properties: + +- `object: Node` +- `index: IndexNode` +- `name: string` (read-only) The function or method name. Returns an empty string when undefined. + +Examples: + +```js +const node1 = math.parse('a[3]') + +const object = new math.SymbolNode('a') +const index = new math.IndexNode([3]) +const node2 = new math.AccessorNode(object, index) +``` + + +### ArrayNode + +Construction: + +``` +new ArrayNode(items: Node[]) +``` + +Properties: + +- `items: Node[]` + +Examples: + +```js +const node1 = math.parse('[1, 2, 3]') + +const one = new math.ConstantNode(1) +const two = new math.ConstantNode(2) +const three = new math.ConstantNode(3) +const node2 = new math.ArrayNode([one, two, three]) +``` + + +### AssignmentNode + +Construction: + +``` +new AssignmentNode(object: SymbolNode, value: Node) +new AssignmentNode(object: SymbolNode | AccessorNode, index: IndexNode, value: Node) +``` + +Properties: + +- `object: SymbolNode | AccessorNode` +- `index: IndexNode | null` +- `value: Node` +- `name: string` (read-only) The function or method name. Returns an empty string when undefined. + +Examples: + +```js +const node1 = math.parse('a = 3') + +const object = new math.SymbolNode('a') +const value = new math.ConstantNode(3) +const node2 = new math.AssignmentNode(object, value) +``` + + +### BlockNode + +A `BlockNode` is created when parsing a multi line expression like `a=2;b=3` or +`a=2\nb=3`. Evaluating a `BlockNode` returns a `ResultSet`. The results can be +retrieved via `ResultSet.entries` or `ResultSet.valueOf()`, which contains +an `Array` with the results of the visible lines (i.e. lines not ending with +a semicolon). + +Construction: + +``` +block = new BlockNode(Array.<{node: Node} | {node: Node, visible: boolean}>) +``` + +Properties: + +- `blocks: Array.<{node: Node, visible: boolean}>` + +Examples: + +```js +const block1 = math.parse('a=1; b=2; c=3') + +const a = new math.SymbolNode('a') +const one = new math.ConstantNode(1) +const ass1 = new math.AssignmentNode(a, one) + +const b = new math.SymbolNode('b') +const two = new math.ConstantNode(2) +const ass2 = new math.AssignmentNode(b, two) + +const c = new math.SymbolNode('c') +const three = new math.ConstantNode(3) +const ass3 = new math.AssignmentNode(c, three) + +const block2 = new BlockNode([ + {node: ass1, visible: false}, + {node: ass2, visible: false}, + {node: ass3, visible: true} +]) +``` + + +### ConditionalNode + +Construction: + +``` +new ConditionalNode(condition: Node, trueExpr: Node, falseExpr: Node) +``` + +Properties: + +- `condition: Node` +- `trueExpr: Node` +- `falseExpr: Node` + +Examples: + +```js +const node1 = math.parse('a > 0 ? a : -a') + +const a = new math.SymbolNode('a') +const zero = new math.ConstantNode(0) +const condition = new math.OperatorNode('>', 'larger', [a, zero]) +const trueExpr = a +const falseExpr = new math.OperatorNode('-', 'unaryMinus', [a]) +const node2 = new math.ConditionalNode(condition, trueExpr, falseExpr) +``` + +### ConstantNode + +Construction: + +``` +new ConstantNode(value: *) +``` + +Properties: + +- `value: *` + +Examples: + +```js +const node1 = math.parse('2.4') + +const node2 = new math.ConstantNode(2.4) +const node3 = new math.ConstantNode('foo') +``` + + +### FunctionAssignmentNode + +Construction: + +``` +new FunctionAssignmentNode(name: string, params: string[], expr: Node) +``` + +Properties: + +- `name: string` +- `params: string[]` +- `expr: Node` + +Examples: + +```js +const node1 = math.parse('f(x) = x^2') + +const x = new math.SymbolNode('x') +const two = new math.ConstantNode(2) +const expr = new math.OperatorNode('^', 'pow', [x, 2]) +const node2 = new math.FunctionAssignmentNode('f', ['x'], expr) +``` + + +### FunctionNode + +Construction: + +``` +new FunctionNode(fn: Node | string, args: Node[]) +``` + +Properties: + +- `fn: Node | string` (read-only) The object or function name which to invoke. +- `args: Node[]` + +Examples: + +```js +const node1 = math.parse('sqrt(4)') + +const four = new math.ConstantNode(4) +const node3 = new math.FunctionNode(new SymbolNode('sqrt'), [four]) +``` + + +### IndexNode + +Construction: + +``` +new IndexNode(dimensions: Node[]) +new IndexNode(dimensions: Node[], dotNotation: boolean) +``` + +Each dimension can be a single value, a range, or a property. The values of +indices are one-based, including range end. + +An optional property `dotNotation` can be provided describing whether this index +was written using dot notation like `a.b`, or using bracket notation +like `a["b"]`. Default value is `false`. This information is used when +stringifying the IndexNode. + +Properties: + +- `dimensions: Node[]` +- `dotNotation: boolean` + +Examples: + +```js +const node1 = math.parse('A[1:3, 2]') + +const A = new math.SymbolNode('A') +const one = new math.ConstantNode(1) +const two = new math.ConstantNode(2) +const three = new math.ConstantNode(3) + +const range = new math.RangeNode(one, three) +const index = new math.IndexNode([range, two]) +const node2 = new math.AccessNode(A, index) +``` + +### ObjectNode + +Construction: + +``` +new ObjectNode(properties: Object.) +``` + +Properties: + +- `properties: Object.` + +Examples: + +```js +const node1 = math.parse('{a: 1, b: 2, c: 3}') + +const a = new math.ConstantNode(1) +const b = new math.ConstantNode(2) +const c = new math.ConstantNode(3) +const node2 = new math.ObjectNode({a: a, b: b, c: c}) +``` + + +### OperatorNode + +Construction: + +``` +new OperatorNode(op: string, fn: string, args: Node[], implicit: boolean = false) +``` + +Additional methods: + +- `isUnary() : boolean` + + Returns true when the `OperatorNode` contains exactly one argument, + like with a unary minus: + + ```js + const a = new math.ConstantNode(2) + const b = new math.OperatorNode('-', 'unaryMinus', [a]) + b.isUnary() // true + ``` + +- `isBinary() : boolean` + + Returns true when the `OperatorNode` contains exactly two arguments, + like with most regular operators: + + ```js + const a = new math.ConstantNode(2) + const b = new math.ConstantNode(3) + const c = new math.OperatorNode('+', 'add', [a, b]) + c.isBinary() // true + ``` + +Properties: + +- `op: string` +- `fn: string` +- `args: Node[]` +- `implicit: boolean` True in case of an implicit multiplication, false otherwise + +Examples: + +```js +const node1 = math.parse('2.3 + 5') + +const a = new math.ConstantNode(2.3) +const b = new math.ConstantNode(5) +const node2 = new math.OperatorNode('+', 'add', [a, b]) +``` + +### ParenthesisNode + +Construction: + +``` +new ParenthesisNode(content: Node) +``` + +Properties: + +- `content: Node` + +Examples: + +```js +const node1 = math.parse('(1)') + +const a = new math.ConstantNode(1) +const node2 = new math.ParenthesisNode(a) +``` + +### RangeNode + +Construction: + +``` +new RangeNode(start: Node, end: Node [, step: Node]) +``` + +Properties: + +- `start: Node` +- `end: Node` +- `step: Node | null` + +Examples: + +```js +const node1 = math.parse('1:10') +const node2 = math.parse('0:2:10') + +const zero = new math.ConstantNode(0) +const one = new math.ConstantNode(1) +const two = new math.ConstantNode(2) +const ten = new math.ConstantNode(10) + +const node3 = new math.RangeNode(one, ten) +const node4 = new math.RangeNode(zero, ten, two) +``` + +### RelationalNode + +Construction: + +``` +new RelationalNode(conditionals: string[], params: Node[]) +``` + +`conditionals` is an array of strings, each of which may be 'smaller', 'larger', 'smallerEq', 'largerEq', 'equal', or 'unequal'. The `conditionals` array must contain exactly one fewer item than `params`. + +Properties: + +- `conditionals: string[]` +- `params: Node[]` + +A `RelationalNode` efficiently represents a chained conditional expression with two or more comparison operators, such as `10 < x <= 50`. The expression is equivalent to `10 < x and x <= 50`, except that `x` is evaluated only once, and evaluation stops (is "short-circuited") once any condition tests false. Operators that are subject to chaining are `<`, `>`, `<=`, `>=`, `==`, and `!=`. For backward compatibility, `math.parse` will return an `OperatorNode` if only a single conditional is present (such as `x > 2`). + +Examples: + +```js + +const ten = new math.ConstantNode(10) +const x = new math.SymbolNode('x') +const fifty = new math.ConstantNode(50) + +const node1 = new math.RelationalNode(['smaller', 'smallerEq'], [ten, x, fifty]) +const node2 = math.parse('10 < x <= 50') +``` + + +### SymbolNode + +Construction: + +``` +new SymbolNode(name: string) +``` + +Properties: + +- `name: string` + +Examples: + +```js +const node = math.parse('x') + +const x = new math.SymbolNode('x') +``` diff --git a/node_modules/mathjs/docs/expressions/html_classes.md b/node_modules/mathjs/docs/expressions/html_classes.md new file mode 100644 index 0000000..8922765 --- /dev/null +++ b/node_modules/mathjs/docs/expressions/html_classes.md @@ -0,0 +1,38 @@ +# HTML output + +The expression parser can output a HTML string, where every `Node` is +transformed into a `` element with semantic class names. Each class +name begins with the `math-` prefix. These class names can be used in CSS to +highlight the syntax or change the default layout (e.g. spaces around operators). + +## Available class names + +- `math-number` +- `math-string` +- `math-boolean` (`true` and `false`) +- `math-undefined` +- `math-function` (function names) +- `math-parameter` (function parameters) +- `math-property` (object members) +- `math-symbol` (variables, units and built-in constants) + - `math-null-symbol` (`null`) + - `math-nan-symbol` (`NaN`) + - `math-infinity-symbol` (`Infinity`) + - `math-imaginary-symbol` (`i`) +- `math-operator` + - `math-unary-operator` + - `math-lefthand-unary-operator` + - `math-righthand-unary-operator` + - `math-binary-operator` + - `math-explicit-binary-operator` + - `math-implicit-binary-operator` (empty element) + - `math-assignment-operator` + - `math-variable-assignment-operator` (`=`) + - `math-property-assignment-operator` (`:` in objects) + - `math-accessor-operator` (`.` in objects) + - `math-range-operator` (`:` in ranges) +- `math-parenthesis` + -`math-round-parenthesis` (`(` and `)`) + -`math-square-parenthesis` (`[` and `]`) + -`math-curly-parenthesis` (`{` and `}`) +- `math-separator` (�,`, `;` and <br />) \ No newline at end of file diff --git a/node_modules/mathjs/docs/expressions/index.md b/node_modules/mathjs/docs/expressions/index.md new file mode 100644 index 0000000..6bc6c03 --- /dev/null +++ b/node_modules/mathjs/docs/expressions/index.md @@ -0,0 +1,21 @@ +# Expressions + +Math.js contains a flexible and easy to use expression parser. +The parser supports all data types, functions and constants available in math.js. + +Whilst the math.js library is aimed at JavaScript developers, the expression +parser is aimed at end users: mathematicians, engineers, students, pupils. +The syntax of the expression parser differs from JavaScript and the low-level +math.js library. + +This section is divided in the following pages: + +- [Parsing and evaluation](parsing.md) describes how to parse and + evaluate expressions with math.js. +- [Syntax](syntax.md) describes how to write expressions. +- [Expression trees](expression_trees.md) explains how to parse an expression into an + expression tree, and use this to analyse and manipulate the expression. +- [Algebra](algebra.md) describing symbolic computation in math.js. +- [Customization](customization.md) describes how to customize processing and + evaluation of expressions. +- [Security](security.md) about security risks of executing arbitrary expressions. diff --git a/node_modules/mathjs/docs/expressions/parsing.md b/node_modules/mathjs/docs/expressions/parsing.md new file mode 100644 index 0000000..50fe6c7 --- /dev/null +++ b/node_modules/mathjs/docs/expressions/parsing.md @@ -0,0 +1,224 @@ +# Expression parsing and evaluation + +Expressions can be parsed and evaluated in various ways: + +- Using the function [`math.evaluate(expr [,scope])`](#evaluate). +- Using the function [`math.compile(expr)`](#compile). +- Using the function [`math.parse(expr)`](#parse). +- By creating a [parser](#parser), `math.parser()`, which contains a method + `evaluate` and keeps a scope with assigned variables in memory. + + +## Evaluate + +Math.js comes with a function `math.evaluate` to evaluate expressions. Syntax: + +```js +math.evaluate(expr) +math.evaluate(expr, scope) +math.evaluate([expr1, expr2, expr3, ...]) +math.evaluate([expr1, expr2, expr3, ...], scope) +``` + +Function `evaluate` accepts a single expression or an array with +expressions as the first argument and has an optional second argument +containing a scope with variables and functions. The scope can be a regular +JavaScript Object, or Map. The scope will be used to resolve symbols, and to write +assigned variables or function. + +The following code demonstrates how to evaluate expressions. + +```js +// evaluate expressions +math.evaluate('sqrt(3^2 + 4^2)') // 5 +math.evaluate('sqrt(-4)') // 2i +math.evaluate('2 inch to cm') // 5.08 cm +math.evaluate('cos(45 deg)') // 0.7071067811865476 + +// provide a scope +let scope = { + a: 3, + b: 4 +} +math.evaluate('a * b', scope) // 12 +math.evaluate('c = 2.3 + 4.5', scope) // 6.8 +scope.c // 6.8 +``` + + +## Compile + +Math.js contains a function `math.compile` which compiles expressions +into JavaScript code. This is a shortcut for first [parsing](#parse) and then +compiling an expression. The syntax is: + +```js +math.compile(expr) +math.compile([expr1, expr2, expr3, ...]) +``` + +Function `compile` accepts a single expression or an array with +expressions as the argument. Function `compile` returns an object with a function +`evaluate([scope])`, which can be executed to evaluate the expression against an +(optional) scope: + +```js +const code = math.compile(expr) // compile an expression +const result = code.evaluate([scope]) // evaluate the code with an optional scope +``` + +An expression needs to be compiled only once, after which the +expression can be evaluated repeatedly and against different scopes. +The optional scope is used to resolve symbols and to write assigned +variables or functions. Parameter [`scope`](#scope) can be a regular Object, or Map. + +Example usage: + +```js +// parse an expression into a node, and evaluate the node +const code1 = math.compile('sqrt(3^2 + 4^2)') +code1.evaluate() // 5 +``` + + +## Parse + +Math.js contains a function `math.parse` to parse expressions into an +[expression tree](expression_trees.md). The syntax is: + +```js +math.parse(expr) +math.parse([expr1, expr2, expr3, ...]) +``` + +Function `parse` accepts a single expression or an array with +expressions as the argument. Function `parse` returns a the root node of the tree, +which can be successively compiled and evaluated: + +```js +const node = math.parse(expr) // parse expression into a node tree +const code = node.compile() // compile the node tree +const result = code.evaluate([scope]) // evaluate the code with an optional scope +``` + +The API of nodes is described in detail on the page +[Expression trees](expression_trees.md). + +An expression needs to be parsed and compiled only once, after which the +expression can be evaluated repeatedly. On evaluation, an optional scope +can be provided, which is used to resolve symbols and to write assigned +variables or functions. Parameter [`scope`](#scope) is a regular Object or Map. + +Example usage: + +```js +// parse an expression into a node, and evaluate the node +const node1 = math.parse('sqrt(3^2 + 4^2)') +const code1 = node1.compile() +code1.evaluate() // 5 + +// provide a scope +const node2 = math.parse('x^a') +const code2 = node2.compile() +let scope = { + x: 3, + a: 2 +} +code2.evaluate(scope) // 9 + +// change a value in the scope and re-evaluate the node +scope.a = 3 +code2.evaluate(scope) // 27 +``` + +Parsed expressions can be exported to text using `node.toString()`, and can +be exported to LaTeX using `node.toTex()`. The LaTeX export can be used to +pretty print an expression in the browser with a library like +[MathJax](https://www.mathjax.org/). Example usage: + +```js +// parse an expression +const node = math.parse('sqrt(x/x+1)') +node.toString() // returns 'sqrt((x / x) + 1)' +node.toTex() // returns '\sqrt{ {\frac{x}{x} }+{1} }' +``` + + +## Parser + +In addition to the static functions [`math.evaluate`](#evaluate) and +[`math.parse`](#parse), math.js contains a parser with functions `evaluate` and +`parse`, which automatically keeps a scope with assigned variables in memory. +The parser also contains some convenience functions to get, set, and remove +variables from memory. + +A parser can be created by: + +```js +const parser = math.parser() +``` + +The parser contains the following functions: + +- `clear()` + Completely clear the parser's scope. +- `evaluate(expr)` + Evaluate an expression. Returns the result of the expression. +- `get(name)` + Retrieve a variable or function from the parser's scope. +- `getAll()` + Retrieve a map with all defined a variables from the parser's scope. +- `remove(name)` + Remove a variable or function from the parser's scope. +- `set(name, value)` + Set a variable or function in the parser's scope. + +The following code shows how to create and use a parser. + +```js +// create a parser +const parser = math.parser() + +// evaluate expressions +parser.evaluate('sqrt(3^2 + 4^2)') // 5 +parser.evaluate('sqrt(-4)') // 2i +parser.evaluate('2 inch to cm') // 5.08 cm +parser.evaluate('cos(45 deg)') // 0.7071067811865476 + +// define variables and functions +parser.evaluate('x = 7 / 2') // 3.5 +parser.evaluate('x + 3') // 6.5 +parser.evaluate('f(x, y) = x^y') // f(x, y) +parser.evaluate('f(2, 3)') // 8 + +// get and set variables and functions +const x = parser.get('x') // x = 7 +const f = parser.get('f') // function +const g = f(3, 3) // g = 27 +parser.set('h', 500) +parser.evaluate('h / 2') // 250 +parser.set('hello', function (name) { + return 'hello, ' + name + '!' +}) +parser.evaluate('hello("user")') // "hello, user!" + +// clear defined functions and variables +parser.clear() +``` + +## Scope + +The scope is a data-structure used to store and lookup variables and functions defined and used by expressions. + +It is passed to mathjs via calls to [`math.evaluate`](#evaluate) or `simplify`. + +For ease of use, it can be a Plain Javascript Object; for safety it can be a plain `Map` and for flexibility, any object that has +the methods `get`/`set`/`has`/`keys`, seen on `Map`. + +Some care is taken to mutate the same object that is passed into mathjs, so they can collect the definitions from mathjs scripts and expressions. + +`evaluate` will fail if the expression uses a blacklisted symbol, preventing mathjs expressions to escape into Javascript. This is enforced by access to the scope. + +For less reliance on this blacklist, scope can also be a `Map`, which allows mathjs expressions to define variables and functions of any name. + +For more, see [examples of custom scopes](../../examples/advanced/custom_scope_objects.js). diff --git a/node_modules/mathjs/docs/expressions/security.md b/node_modules/mathjs/docs/expressions/security.md new file mode 100644 index 0000000..a25668e --- /dev/null +++ b/node_modules/mathjs/docs/expressions/security.md @@ -0,0 +1,89 @@ +# Security + +Executing arbitrary expressions like enabled by the expression parser of +mathjs involves a risk in general. When you're using mathjs to let users +execute arbitrary expressions, it's good to take a moment to think about +possible security and stability implications, especially when running +the code server side. + +## Security risks + +A user could try to inject malicious JavaScript code via the expression +parser. The expression parser of mathjs offers a sandboxed environment +to execute expressions which should make this impossible. It's possible +though that there are unknown security vulnerabilities, so it's important +to be careful, especially when allowing server side execution of +arbitrary expressions. + +The expression parser of mathjs parses the input in a controlled +way into an expression tree or abstract syntax tree (AST). +In a "compile" step, it does as much as possible preprocessing on the +static parts of the expression, and creates a fast performing function +which can be used to evaluate the expression repeatedly using a +dynamically passed scope. + +The parser actively prevents access to JavaScripts internal `eval` and +`new Function` which are the main cause of security attacks. Mathjs +versions 4 and newer does not use JavaScript's `eval` under the hood. +Version 3 and older did use `eval` for the compile step. This is not +directly a security issue but results in a larger possible attack surface. + +When running a node.js server, it's good to be aware of the different +types of security risks. The risk whe running inside a browser may be +limited though it's good to be aware of [Cross side scripting (XSS)](https://www.wikiwand.com/en/Cross-site_scripting) vulnerabilities. A nice overview of +security risks of a node.js servers is listed in an article [Node.js security checklist](https://blog.risingstack.com/node-js-security-checklist/) by Gergely Nemeth. + +### Less vulnerable expression parser + +There is a small number of functions which yield the biggest security +risk in the expression parser: + +- `import` and `createUnit` which alter the built-in functionality and + allow overriding existing functions and units. +- `evaluate`, `parse`, `simplify`, and `derivative` which parse arbitrary + input into a manipulable expression tree. + +To make the expression parser less vulnerable whilst still supporting +most functionality, these functions can be disabled: + +```js +import { create, all } from 'mathjs' + +const math = create(all) +const limitedEvaluate = math.evaluate + +math.import({ + 'import': function () { throw new Error('Function import is disabled') }, + 'createUnit': function () { throw new Error('Function createUnit is disabled') }, + 'evaluate': function () { throw new Error('Function evaluate is disabled') }, + 'parse': function () { throw new Error('Function parse is disabled') }, + 'simplify': function () { throw new Error('Function simplify is disabled') }, + 'derivative': function () { throw new Error('Function derivative is disabled') } +}, { override: true }) + +console.log(limitedEvaluate('sqrt(16)')) // Ok, 4 +console.log(limitedEvaluate('parse("2+3")')) // Error: Function parse is disabled +``` + + +### Found a security vulnerability? Please report in private! + +You found a security vulnerability? Awesome! We hope you don't have bad +intentions and want to help fix the issue. Please report the +vulnerability in a private way by contacting one of the maintainers +via mail or an other private channel. That way we can work together +on a fix before sharing the issue with everybody including the bad guys. + +## Stability risks + +A user could accidentally or on purpose execute a +heavy expression like creating a huge matrix. That can let the +JavaScript engine run out of memory or freeze it when the CPU goes +to 100% for a long time. + +To protect against this sort of issue, one can run the expression parser +in a separate Web Worker or child_process, so it can't affect the +main process. The workers can be killed when it runs for too +long or consumes too much memory. A useful library in this regard +is [workerpool](https://github.com/josdejong/workerpool), which makes +it easy to manage a pool of workers in both browser and node.js. diff --git a/node_modules/mathjs/docs/expressions/syntax.md b/node_modules/mathjs/docs/expressions/syntax.md new file mode 100644 index 0000000..34487b9 --- /dev/null +++ b/node_modules/mathjs/docs/expressions/syntax.md @@ -0,0 +1,703 @@ +# Expression syntax + +This page describes the syntax of expression parser of math.js. It describes +how to work with the available data types, functions, operators, variables, +and more. + +## Differences from JavaScript + +The expression parser of math.js is aimed at a mathematical audience, +not a programming audience. The syntax is similar to most calculators and +mathematical applications. This is close to JavaScript as well, though there +are a few important differences between the syntax of the expression parser and +the lower level syntax of math.js. Differences are: + +- No need to prefix functions and constants with the `math.*` namespace, + you can just enter `sin(pi / 4)`. +- Matrix indexes are one-based instead of zero-based. +- There are index and range operators which allow more conveniently getting + and setting matrix indexes, like `A[2:4, 1]`. +- Both indexes and ranges and have the upper-bound included. +- There is a differing syntax for defining functions. Example: `f(x) = x^2`. +- There are custom operators like `x + y` instead of `add(x, y)`. +- Some operators are different. For example `^` is used for exponentiation, + not bitwise xor. +- Implicit multiplication, like `2 pi`, is supported and has special rules. +- Relational operators (`<`, `>`, `<=`, `>=`, `==`, and `!=`) are chained, so the expression `5 < x < 10` is equivalent to `5 < x and x < 10`. +- Multi-expression constructs like `a = 1; b = 2; a + b` or + `"a = 1;\n cos(a)\n sin(a)"` (where `\n` denotes newline) + produce a collection ("ResultSet") of values. Those expressions + terminated by `;` are evaluated for side effect only and their values + are suppressed from the result. + +## Operators + +The expression parser has operators for all common arithmetic operations such +as addition and multiplication. The expression parser uses conventional infix +notation for operators: an operator is placed between its arguments. +Round parentheses can be used to override the default precedence of operators. + +```js +// use operators +math.evaluate('2 + 3') // 5 +math.evaluate('2 * 3') // 6 + +// use parentheses to override the default precedence +math.evaluate('2 + 3 * 4') // 14 +math.evaluate('(2 + 3) * 4') // 20 +``` + +The following operators are available: + +Operator | Name | Syntax | Associativity | Example | Result +----------- | -------------------------- | ---------- | ------------- | --------------------- | --------------- +`(`, `)` | Grouping | `(x)` | None | `2 * (3 + 4)` | `14` +`[`, `]` | Matrix, Index | `[...]` | None | `[[1,2],[3,4]]` | `[[1,2],[3,4]]` +`{`, `}` | Object | `{...}` | None | `{a: 1, b: 2}` | `{a: 1, b: 2}` +`,` | Parameter separator | `x, y` | Left to right | `max(2, 1, 5)` | `5` +`.` | Property accessor | `obj.prop` | Left to right | `obj={a: 12}; obj.a` | `12` +`;` | Statement separator | `x; y` | Left to right | `a=2; b=3; a*b` | `[6]` +`;` | Row separator | `[x; y]` | Left to right | `[1,2;3,4]` | `[[1,2],[3,4]]` +`\n` | Statement separator | `x \n y` | Left to right | `a=2 \n b=3 \n a*b` | `[2,3,6]` +`+` | Add | `x + y` | Left to right | `4 + 5` | `9` +`+` | Unary plus | `+y` | Right to left | `+4` | `4` +`-` | Subtract | `x - y` | Left to right | `7 - 3` | `4` +`-` | Unary minus | `-y` | Right to left | `-4` | `-4` +`*` | Multiply | `x * y` | Left to right | `2 * 3` | `6` +`.*` | Element-wise multiply | `x .* y` | Left to right | `[1,2,3] .* [1,2,3]` | `[1,4,9]` +`/` | Divide | `x / y` | Left to right | `6 / 2` | `3` +`./` | Element-wise divide | `x ./ y` | Left to right | `[9,6,4] ./ [3,2,2]` | `[3,3,2]` +`%` | Percentage | `x%` | None | `8%` | `0.08` +`%` | Addition with Percentage | `x + y%` | Left to right | `100 + 3%` | `103` +`%` | Subtraction with Percentage| `x - y%` | Left to right | `100 - 3%` | `97` +`%` `mod` | Modulus | `x % y` | Left to right | `8 % 3` | `2` +`^` | Power | `x ^ y` | Right to left | `2 ^ 3` | `8` +`.^` | Element-wise power | `x .^ y` | Right to left | `[2,3] .^ [3,3]` | `[8,27]` +`'` | Transpose | `y'` | Left to right | `[[1,2],[3,4]]'` | `[[1,3],[2,4]]` +`!` | Factorial | `y!` | Left to right | `5!` | `120` +`&` | Bitwise and | `x & y` | Left to right | `5 & 3` | `1` +`~` | Bitwise not | `~x` | Right to left | `~2` | `-3` +| | Bitwise or | x | y | Left to right | 5 | 3 | `7` +^| | Bitwise xor | x ^| y | Left to right | 5 ^| 2 | `7` +`<<` | Left shift | `x << y` | Left to right | `4 << 1` | `8` +`>>` | Right arithmetic shift | `x >> y` | Left to right | `8 >> 1` | `4` +`>>>` | Right logical shift | `x >>> y` | Left to right | `-8 >>> 1` | `2147483644` +`and` | Logical and | `x and y` | Left to right | `true and false` | `false` +`not` | Logical not | `not y` | Right to left | `not true` | `false` +`or` | Logical or | `x or y` | Left to right | `true or false` | `true` +`xor` | Logical xor | `x xor y` | Left to right | `true xor true` | `false` +`=` | Assignment | `x = y` | Right to left | `a = 5` | `5` +`?` `:` | Conditional expression | `x ? y : z` | Right to left | `15 > 100 ? 1 : -1` | `-1` +`:` | Range | `x : y` | Right to left | `1:4` | `[1,2,3,4]` +`to`, `in` | Unit conversion | `x to y` | Left to right | `2 inch to cm` | `5.08 cm` +`==` | Equal | `x == y` | Left to right | `2 == 4 - 2` | `true` +`!=` | Unequal | `x != y` | Left to right | `2 != 3` | `true` +`<` | Smaller | `x < y` | Left to right | `2 < 3` | `true` +`>` | Larger | `x > y` | Left to right | `2 > 3` | `false` +`<=` | Smallereq | `x <= y` | Left to right | `4 <= 3` | `false` +`>=` | Largereq | `x >= y` | Left to right | `2 + 4 >= 6` | `true` + + +## Precedence + +The operators have the following precedence, from highest to lowest: + +Operators | Description +--------------------------------- | -------------------- +`(...)`
    `[...]`
    `{...}` | Grouping
    Matrix
    Object +`x(...)`
    `x[...]`
    `obj.prop`
    `:`| Function call
    Matrix index
    Property accessor
    Key/value separator +`'` | Matrix transpose +`!` | Factorial +`^`, `.^` | Exponentiation +`+`, `-`, `~`, `not` | Unary plus, unary minus, bitwise not, logical not +See section below | Implicit multiplication +`*`, `/`, `.*`, `./`, `%`, `mod` | Multiply, divide, percentage, modulus +`+`, `-` | Add, subtract +`:` | Range +`to`, `in` | Unit conversion +`<<`, `>>`, `>>>` | Bitwise left shift, bitwise right arithmetic shift, bitwise right logical shift +`==`, `!=`, `<`, `>`, `<=`, `>=` | Relational +`&` | Bitwise and +^| | Bitwise xor +| | Bitwise or +`and` | Logical and +`xor` | Logical xor +`or` | Logical or +`?`, `:` | Conditional expression +`=` | Assignment +`,` | Parameter and column separator +`;` | Row separator +`\n`, `;` | Statement separators + + +## Functions + +Functions are called by entering their name, followed by zero or more +arguments enclosed by parentheses. All available functions are listed on the +page [Functions](../reference/functions.md). + +```js +math.evaluate('sqrt(25)') // 5 +math.evaluate('log(10000, 3 + 7)') // 4 +math.evaluate('sin(pi / 4)') // 0.7071067811865475 +``` + +New functions can be defined by "assigning" an expression to a function call +with one or more variables. Such function assignments are limited: they can +only be defined on a single line. + +```js +const parser = math.parser() + +parser.evaluate('f(x) = x ^ 2 - 5') +parser.evaluate('f(2)') // -1 +parser.evaluate('f(3)') // 4 + +parser.evaluate('g(x, y) = x ^ y') +parser.evaluate('g(2, 3)') // 8 +``` + +Note that these function assignments do _not_ create closures; put another way, +all free variables in mathjs are dynamic: + +```js +const parser = math.parser() + +parser.evaluate('x = 7') +parser.evaluate('h(y) = x + y') +parser.evaluate('h(3)') // 10 +parser.evaluate('x = 3') +parser.evaluate('h(3)') // 6, *not* 10 +``` + +It is however possible to pass functions as parameters: + +```js +const parser = math.parser() + +parser.evaluate('twice(func, x) = func(func(x))') +parser.evaluate('twice(square, 2)') // 16 +parser.evaluate('f(x) = 3*x') +parser.evaluate('twice(f, 2)') // 18 + +// a simplistic "numerical derivative": +parser.evaluate('eps = 1e-10') +parser.evaluate('nd(f, x) = (f(x+eps) - func(x-eps))/(2*eps)') +parser.evaluate('nd(square,2)') // 4.000000330961484 +``` + +Math.js itself heavily uses typed functions, which ensure correct inputs and +throws meaningful errors when the input arguments are invalid. One can create +a [typed-function](https://github.com/josdejong/typed-function) in the +expression parser like: + +```js +const parser = math.parser() + +parser.evaluate('f = typed({"number": f(x) = x ^ 2 - 5})') +``` + + +## Constants and variables + +Math.js has a number of built-in constants such as `pi` and `e`. +All available constants are listed on he page +[Constants](../reference/constants.md). + +```js +// use constants +math.evaluate('pi') // 3.141592653589793 +math.evaluate('e ^ 2') // 7.3890560989306495 +math.evaluate('log(e)') // 1 +math.evaluate('e ^ (pi * i) + 1') // ~0 (Euler) +``` + +Variables can be defined using the assignment operator `=`, and can be used +like constants. + +```js +const parser = math.parser() + +// define variables +parser.evaluate('a = 3.4') // 3.4 +parser.evaluate('b = 5 / 2') // 2.5 + +// use variables +parser.evaluate('a * b') // 8.5 +``` + +Variable names must: + +- Begin with an "alpha character", which is: + - A latin letter (upper or lower case). Ascii: `a-z`, `A-Z` + - An underscore. Ascii: `_` + - A dollar sign. Ascii: `$` + - A latin letter with accents. Unicode: `\u00C0` - `\u02AF` + - A greek letter. Unicode: `\u0370` - `\u03FF` + - A letter-like character. Unicode: `\u2100` - `\u214F` + - A mathematical alphanumeric symbol. Unicode: `\u{1D400}` - `\u{1D7FF}` excluding invalid code points +- Contain only alpha characters (above) and digits `0-9` +- Not be any of the following: `mod`, `to`, `in`, `and`, `xor`, `or`, `not`, `end`. It is possible to assign to some of these, but that's not recommended. + +It is possible to customize the allowed alpha characters, see [Customize supported characters](customization.md#customize-supported-characters) for more information. + + +## Data types + +The expression parser supports booleans, numbers, complex numbers, units, +strings, matrices, and objects. + + +### Booleans + +Booleans `true` and `false` can be used in expressions. + +```js +// use booleans +math.evaluate('true') // true +math.evaluate('false') // false +math.evaluate('(2 == 3) == false') // true +``` + +Booleans can be converted to numbers and strings and vice versa using the +functions `number` and `boolean`, and `string`. + +```js +// convert booleans +math.evaluate('number(true)') // 1 +math.evaluate('string(false)') // "false" +math.evaluate('boolean(1)') // true +math.evaluate('boolean("false")') // false +``` + + +### Numbers + +The most important and basic data type in math.js are numbers. Numbers use a +point as decimal mark. Numbers can be entered with exponential notation. +Examples: + +```js +// numbers in math.js +math.evaluate('2') // 2 +math.evaluate('3.14') // 3.14 +math.evaluate('1.4e3') // 1400 +math.evaluate('22e-3') // 0.022 +``` + +A number can be converted to a string and vice versa using the functions +`number` and `string`. + +```js +// convert a string into a number +math.evaluate('number("2.3")') // 2.3 +math.evaluate('string(2.3)') // "2.3" +``` + +Math.js uses regular JavaScript numbers, which are floating points with a +limited precision and limited range. The limitations are described in detail +on the page [Numbers](../datatypes/numbers.md). + +```js +math.evaluate('1e-325') // 0 +math.evaluate('1e309') // Infinity +math.evaluate('-1e309') // -Infinity +``` + +When doing calculations with floats, one can very easily get round-off errors: + +```js +// round-off error due to limited floating point precision +math.evaluate('0.1 + 0.2') // 0.30000000000000004 +``` + +When outputting results, the function `math.format` can be used to hide +these round-off errors when outputting results for the user: + +```js +const ans = math.evaluate('0.1 + 0.2') // 0.30000000000000004 +math.format(ans, {precision: 14}) // "0.3" +``` + +Numbers can be expressed as binary, octal, and hexadecimal literals: + +```js +math.evaluate('0b11') // 3 +math.evaluate('0o77') // 63 +math.evaluate('0xff') // 255 +``` + +A word size suffix can be used to change the behavior of non decimal literal evaluation: + +```js +math.evaluate('0xffi8') // -1 +math.evaluate('0xffffffffi32') // -1 +math.evaluate('0xfffffffffi32') // SyntaxError: String "0xfffffffff" is out of range +``` + +Non decimal numbers can include a radix point: +```js +math.evaluate('0b1.1') // 1.5 +math.evaluate('0o1.4') // 1.5 +math.evaluate('0x1.8') // 1.5 +``` + +Numbers can be formatted as binary, octal, and hex strings using the `notation` option of the `format` function: + +```js +math.evaluate('format(3, {notation: "bin"})') // '0b11' +math.evaluate('format(63, {notation: "oct"})') // '0o77' +math.evaluate('format(255, {notation: "hex"})') // '0xff' +math.evaluate('format(-1, {notation: "hex"})') // '-0x1' +math.evaluate('format(2.3, {notation: "hex"})') // '0x2.4cccccccccccc' +``` + +The `format` function accepts a `wordSize` option to use in conjunction with the non binary notations: + +```js +math.evaluate('format(-1, {notation: "hex", wordSize: 8})') // '0xffi8' +``` + +The functions `bin`, `oct`, and `hex` are shorthand for the `format` function with `notation` set accordingly: + +```js +math.evaluate('bin(-1)') // '-0b1' +math.evaluate('bin(-1, 8)') // '0b11111111i8' +``` + +### BigNumbers + +Math.js supports BigNumbers for calculations with an arbitrary precision. +The pros and cons of Number and BigNumber are explained in detail on the page +[Numbers](../datatypes/numbers.md). + +BigNumbers are slower but have a higher precision. Calculations with big +numbers are supported only by arithmetic functions. + +BigNumbers can be created using the `bignumber` function: + +```js +math.evaluate('bignumber(0.1) + bignumber(0.2)') // BigNumber, 0.3 +``` + +The default number type of the expression parser can be changed at instantiation +of math.js. The expression parser parses numbers as BigNumber by default: + +```js +// Configure the type of number: 'number' (default), 'BigNumber', or 'Fraction' +math.config({number: 'BigNumber'}) + +// all numbers are parsed as BigNumber +math.evaluate('0.1 + 0.2') // BigNumber, 0.3 +``` + +BigNumbers can be converted to numbers and vice versa using the functions +`number` and `bignumber`. When converting a BigNumber to a Number, the high +precision of the BigNumber will be lost. When a BigNumber is too large to be represented +as Number, it will be initialized as `Infinity`. + + +### Complex numbers + +Complex numbers can be created using the imaginary unit `i`, which is defined +as `i^2 = -1`. Complex numbers have a real and complex part, which can be +retrieved using the functions `re` and `im`. + +```js +const parser = math.parser() + +// create complex numbers +parser.evaluate('a = 2 + 3i') // Complex, 2 + 3i +parser.evaluate('b = 4 - i') // Complex, 4 - i + +// get real and imaginary part of a complex number +parser.evaluate('re(a)') // Number, 2 +parser.evaluate('im(a)') // Number, 3 + +// calculations with complex numbers +parser.evaluate('a + b') // Complex, 6 + 2i +parser.evaluate('a * b') // Complex, 11 + 10i +parser.evaluate('i * i') // Number, -1 +parser.evaluate('sqrt(-4)') // Complex, 2i +``` + +Math.js does not automatically convert complex numbers with an imaginary part +of zero to numbers. They can be converted to a number using the function +`number`. + +```js +// convert a complex number to a number +const parser = math.parser() +parser.evaluate('a = 2 + 3i') // Complex, 2 + 3i +parser.evaluate('b = a - 3i') // Complex, 2 + 0i +parser.evaluate('number(b)') // Number, 2 +parser.evaluate('number(a)') // Error: 2 + i is no valid number +``` + + +### Units + +math.js supports units. Units can be used in the arithmetic operations +add, subtract, multiply, divide, and exponentiation. +Units can also be converted from one to another. +An overview of all available units can be found on the page +[Units](../datatypes/units.md). + +Units can be converted using the operator `to` or `in`. + +```js +// create a unit +math.evaluate('5.4 kg') // Unit, 5.4 kg + +// convert a unit +math.evaluate('2 inch to cm') // Unit, 5.08 cm +math.evaluate('20 celsius in fahrenheit') // Unit, ~68 fahrenheit +math.evaluate('90 km/h to m/s') // Unit, 25 m / s + +// convert a unit to a number +// A second parameter with the unit for the exported number must be provided +math.evaluate('number(5 cm, mm)') // Number, 50 + +// calculations with units +math.evaluate('0.5kg + 33g') // Unit, 0.533 kg +math.evaluate('3 inch + 2 cm') // Unit, 3.7874 inch +math.evaluate('3 inch + 2 cm') // Unit, 3.7874 inch +math.evaluate('12 seconds * 2') // Unit, 24 seconds +math.evaluate('sin(45 deg)') // Number, 0.7071067811865475 +math.evaluate('9.81 m/s^2 * 5 s to mi/h') // Unit, 109.72172512527 mi / h +``` + + +### Strings + +Strings are enclosed by double quotes " or single quotes '. Strings can be concatenated using the +function `concat` (not by adding them using `+` like in JavaScript). Parts of +a string can be retrieved or replaced by using indexes. Strings can be converted +to a number using function `number`, and numbers can be converted to a string +using function `string`. + +When setting the value of a character in a string, the character that has been +set is returned. Likewise, when a range of characters is set, that range of +characters is returned. + + +```js +const parser = math.parser() + +// create a string +parser.evaluate('"hello"') // String, "hello" + +// string manipulation +parser.evaluate('a = concat("hello", " world")') // String, "hello world" +parser.evaluate('size(a)') // Matrix [11] +parser.evaluate('a[1:5]') // String, "hello" +parser.evaluate('a[1] = "H"') // String, "H" +parser.evaluate('a[7:12] = "there!"') // String, "there!" +parser.evaluate('a') // String, "Hello there!" + +// string conversion +parser.evaluate('number("300")') // Number, 300 +parser.evaluate('string(300)') // String, "300" +``` + +Strings can be used in the `evaluate` function, to parse expressions inside +the expression parser: + +```js +math.evaluate('evaluate("2 + 3")') // 5 +``` + + +### Matrices + +Matrices can be created by entering a series of values between square brackets, +elements are separated by a comma `,`. +A matrix like `[1, 2, 3]` will create a vector, a 1-dimensional matrix with +size `[3]`. To create a multi-dimensional matrix, matrices can be nested into +each other. For easier creation of two-dimensional matrices, a semicolon `;` +can be used to separate rows in a matrix. + +```js +// create a matrix +math.evaluate('[1, 2, 3]') // Matrix, size [3] +math.evaluate('[[1, 2, 3], [4, 5, 6]]') // Matrix, size [2, 3] +math.evaluate('[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]') // Matrix, size [2, 2, 2] + +// create a two dimensional matrix +math.evaluate('[1, 2, 3; 4, 5, 6]') // Matrix, size [2, 3] +``` + +Another way to create filled matrices is using the functions `zeros`, `ones`, +`identity`, and `range`. + +```js +// initialize a matrix with ones or zeros +math.evaluate('zeros(3, 2)') // Matrix, [[0, 0], [0, 0], [0, 0]], size [3, 2] +math.evaluate('ones(3)') // Matrix, [1, 1, 1], size [3] +math.evaluate('5 * ones(2, 2)') // Matrix, [[5, 5], [5, 5]], size [2, 2] + +// create an identity matrix +math.evaluate('identity(2)') // Matrix, [[1, 0], [0, 1]], size [2, 2] + +// create a range +math.evaluate('1:4') // Matrix, [1, 2, 3, 4], size [4] +math.evaluate('0:2:10') // Matrix, [0, 2, 4, 6, 8, 10], size [6] +``` + +A subset can be retrieved from a matrix using indexes and a subset of a matrix +can be replaced by using indexes. Indexes are enclosed in square brackets, and +contain a number or a range for each of the matrix dimensions. A range can have +its start and/or end undefined. When the start is undefined, the range will start +at 1, when the end is undefined, the range will end at the end of the matrix. +There is a context variable `end` available as well to denote the end of the +matrix. + +*IMPORTANT: matrix indexes and ranges work differently from the math.js indexes +in JavaScript: They are one-based with an included upper-bound, similar to most +math applications.* + +```js +parser = math.parser() + +// create matrices +parser.evaluate('a = [1, 2; 3, 4]') // Matrix, [[1, 2], [3, 4]] +parser.evaluate('b = zeros(2, 2)') // Matrix, [[0, 0], [0, 0]] +parser.evaluate('c = 5:9') // Matrix, [5, 6, 7, 8, 9] + +// replace a subset in a matrix +parser.evaluate('b[1, 1:2] = [5, 6]') // Matrix, [[5, 6], [0, 0]] +parser.evaluate('b[2, :] = [7, 8]') // Matrix, [[5, 6], [7, 8]] + +// perform a matrix calculation +parser.evaluate('d = a * b') // Matrix, [[19, 22], [43, 50]] + +// retrieve a subset of a matrix +parser.evaluate('d[2, 1]') // 43 +parser.evaluate('d[2, 1:end]') // Matrix, [[43, 50]] +parser.evaluate('c[end - 1 : -1 : 2]') // Matrix, [8, 7, 6] +``` + +## Objects + +Objects in math.js work the same as in languages like JavaScript and Python. +An object is enclosed by curly brackets `{`, `}`, and contains a set of +comma separated key/value pairs. Keys and values are separated by a colon `:`. +Keys can be a symbol like `prop` or a string like `"prop"`. + +```js +math.evaluate('{a: 2 + 1, b: 4}') // {a: 3, b: 4} +math.evaluate('{"a": 2 + 1, "b": 4}') // {a: 3, b: 4} +``` + +Objects can contain objects: + +```js +math.evaluate('{a: 2, b: {c: 3, d: 4}}') // {a: 2, b: {c: 3, d: 4}} +``` + +Object properties can be retrieved or replaced using dot notation or bracket +notation. Unlike JavaScript, when setting a property value, the whole object +is returned, not the property value + +```js +let scope = { + obj: { + prop: 42 + } +} + +// retrieve properties +math.evaluate('obj.prop', scope) // 42 +math.evaluate('obj["prop"]', scope) // 42 + +// set properties (returns the whole object, not the property value!) +math.evaluate('obj.prop = 43', scope) // {prop: 43} +math.evaluate('obj["prop"] = 43', scope) // {prop: 43} +scope.obj // {prop: 43} +``` + + +## Multi-line expressions + +An expression can contain multiple lines, and expressions can be spread over +multiple lines. Lines can be separated by a newline character `\n` or by a +semicolon `;`. Output of statements followed by a semicolon will be hidden from +the output, and empty lines are ignored. The output is returned as a `ResultSet`, +with an entry for every visible statement. + +```js +// a multi-line expression +math.evaluate('1 * 3 \n 2 * 3 \n 3 * 3') // ResultSet, [3, 6, 9] + +// semicolon statements are hidden from the output +math.evaluate('a=3; b=4; a + b \n a * b') // ResultSet, [7, 12] + +// single expression spread over multiple lines +math.evaluate('a = 2 +\n 3') // 5 +math.evaluate('[\n 1, 2;\n 3, 4\n]') // Matrix, [[1, 2], [3, 4]] +``` + +The results can be read from a `ResultSet` via the property `ResultSet.entries` +which is an `Array`, or by calling `ResultSet.valueOf()`, which returns the +array with results. + + +## Implicit multiplication + +*Implicit multiplication* means the multiplication of two symbols, numbers, or a grouped expression inside parentheses without using the `*` operator. This type of syntax allows a more natural way to enter expressions. For example: + +```js +math.evaluate('2 pi') // 6.283185307179586 +math.evaluate('(1+2)(3+4)') // 21 +``` + +Parentheses are parsed as a function call when there is a symbol or accessor on +the left hand side, like `sqrt(4)` or `obj.method(4)`. In other cases the +parentheses are interpreted as an implicit multiplication. + +Math.js will always evaluate implicit multiplication before explicit multiplication `*`, so that the expression `x * y z` is parsed as `x * (y * z)`. Math.js also gives implicit multiplication higher precedence than division, *except* when the division matches the pattern `[unaryPrefixOp]?[number] / [number] [symbol]` or `[unaryPrefixOp]?[number] / [number] [left paren]`. In that special case, the division is evaluated first: + +```js +math.evaluate('20 kg / 4 kg') // 5 Evaluated as (20 kg) / (4 kg) +math.evaluate('20 / 4 kg') // 5 kg Evaluated as (20 / 4) kg +``` + +The behavior of implicit multiplication can be summarized by these operator precedence rules, listed from highest to lowest precedence: + +- Function calls: `[symbol] [left paren]` +- Explicit division `/` when the division matches this pattern: `[+-~]?[number] / [+-~]?[number] [symbol]` or `[number] / [number] [left paren]` +- Implicit multiplication +- All other division `/` and multiplication `*` + +Implicit multiplication is tricky as there can appear to be ambiguity in how an expression will be evaluated. Experience has shown that the above rules most closely match user intent when entering expressions that could be interpreted different ways. It's also possible that these rules could be tweaked in future major releases. Use implicit multiplication carefully. If you don't like the uncertainty introduced by implicit multiplication, use explicit `*` operators and parentheses to ensure your expression is evaluated the way you intend. + +Here are some more examples using implicit multiplication: + +Expression | Evaluated as | Result +--------------- | ------------------- | ------------------ +(1 + 3) pi | (1 + 3) * pi | 12.566370614359172 +(4 - 1) 2 | (4 - 1) * 2 | 6 +3 / 4 mm | (3 / 4) * mm | 0.75 mm +2 + 3 i | 2 + (3 * i) | 2 + 3i +(1 + 2) (4 - 2) | (1 + 2) * (4 - 2) | 6 +sqrt(4) (1 + 2) | sqrt(4) * (1 + 2) | 6 +8 pi / 2 pi | (8 * pi) / (2 * pi) | 4 +pi / 2 pi | pi / (2 * pi) | 0.5 +1 / 2i | (1 / 2) * i | 0.5 i +8.314 J / mol K | 8.314 J / (mol * K) | 8.314 J / (mol * K) + + +## Comments + +Comments can be added to explain or describe calculations in the text. A comment +starts with a sharp sign character `#`, and ends at the end of the line. A line +can contain a comment only, or can contain an expression followed by a comment. + +```js +const parser = math.parser() + +parser.evaluate('# define some variables') +parser.evaluate('width = 3') // 3 +parser.evaluate('height = 4') // 4 +parser.evaluate('width * height # calculate the area') // 12 +``` diff --git a/node_modules/mathjs/docs/getting_started.md b/node_modules/mathjs/docs/getting_started.md new file mode 100644 index 0000000..469ad74 --- /dev/null +++ b/node_modules/mathjs/docs/getting_started.md @@ -0,0 +1,124 @@ +# Getting Started + +This getting started describes how to install, load, and use math.js. + + +## Install + +Math.js can be installed using various package managers like [npm](https://npmjs.org/), or by just downloading the library from the website: [https://mathjs.org/download.html](https://mathjs.org/download.html). + +To install via npm, run: + + npm install mathjs + +Other ways to install math.js are described on the [website](https://mathjs.org/download.html). + + +## Load + +Math.js can be used in node.js and in the browser. The library must be loaded +and instantiated. When creating an instance, one can optionally provide +configuration options as described in +[Configuration](core/configuration.md). + +### ES modules + +Load the functions you need and use them: + +```js +import { sqrt } from 'mathjs' + +console.log(sqrt(-4).toString()) // 2i +``` + +To use lightweight, number only implementations of all functions: + +```js +import { sqrt } from 'mathjs/number' + +console.log(sqrt(4).toString()) // 2 +console.log(sqrt(-4).toString()) // NaN +``` + +You can create a mathjs instance allowing [configuration](core/configuration.md) and importing of external functions as follows: + +```js +import { create, all } from 'mathjs' + +const config = { } +const math = create(all, config) + +console.log(math.sqrt(-4).toString()) // 2i +``` + +How to optimize your bundle size using tree-shaking is described on the page +[Custom bundling](custom_bundling.md). + + +### Node.js + +Load math.js in [node.js](https://nodejs.org/) (CommonJS module system): + +```js +const { sqrt } = require('mathjs') + +console.log(sqrt(-4).toString()) // 2i +``` + + +### Browser + +Math.js can be loaded as a regular JavaScript file in the browser, use the global +variable `math` to access the libary once loaded: + +```html + + + + + + + + + +``` + +## Use + +Math.js can be used similar to JavaScript's built-in Math library. Besides that, +math.js can evaluate expressions (see [Expressions](expressions/index.md)) and +supports chaining (see [Chaining](core/chaining.md)). + +The example code below shows how to use math.js. More examples can be found in the +section [Examples](https://mathjs.org/examples/index.html). + +```js +// functions and constants +math.round(math.e, 3) // 2.718 +math.atan2(3, -3) / math.pi // 0.75 +math.log(10000, 10) // 4 +math.sqrt(-4) // 2i +math.pow([[-1, 2], [3, 1]], 2) // [[7, 0], [0, 7]] + +// expressions +math.evaluate('12 / (2.3 + 0.7)') // 4 +math.evaluate('12.7 cm to inch') // 5 inch +math.evaluate('sin(45 deg) ^ 2') // 0.5 +math.evaluate('9 / 3 + 2i') // 3 + 2i +math.evaluate('det([-1, 2; 3, 1])') // -7 + +// chained operations +math.chain(3) + .add(4) + .multiply(2) + .done() // 14 +``` + +## Next + +To learn more about math.js, check out the available documentation and examples: + +- [Documentation](index.md) +- [Examples](https://mathjs.org/examples/index.html) diff --git a/node_modules/mathjs/docs/index.md b/node_modules/mathjs/docs/index.md new file mode 100644 index 0000000..f3e77f9 --- /dev/null +++ b/node_modules/mathjs/docs/index.md @@ -0,0 +1,39 @@ +# Documentation + +[Math.js](https://mathjs.org) is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with different data types like numbers, big numbers, complex numbers, fractions, units, and matrices. + +Math.js can be used in the browser, in node.js and in any JavaScript engine. Installation and download instructions are available on the [Download page](https://mathjs.org/download.html) of the website. + +## Getting Started + +- [Getting Started](getting_started.md) +- [Examples](//mathjs.org/examples/index.html) + +## Documentation + +- **[Core](core/index.md)** + - [Configuration](core/configuration.md) + - [Chaining](core/chaining.md) + - [Extension](core/extension.md) + - [Serialization](core/serialization.md) +- **[Expressions](expressions/index.md)** + - [Parsing and evaluation](expressions/parsing.md) + - [Syntax](expressions/syntax.md) + - [Expression trees](expressions/expression_trees.md) + - [Algebra](expressions/algebra.md) + - [Customization](expressions/customization.md) + - [Security](expressions/security.md) +- **[Data Types](datatypes/index.md)** + - [Numbers](datatypes/numbers.md) + - [BigNumbers](datatypes/bignumbers.md) + - [Fractions](datatypes/fractions.md) + - [Complex Numbers](datatypes/complex_numbers.md) + - [Matrices](datatypes/matrices.md) + - [Units](datatypes/units.md) +- **[Reference](reference/index.md)** + - [Classes](reference/classes.md) + - [Functions](reference/functions.md) + - [Constants](reference/constants.md) +- [Custom bundling](custom_bundling.md) +- [Command Line Interface](command_line_interface.md) +- [History](../HISTORY.md) diff --git a/node_modules/mathjs/docs/reference/classes.md b/node_modules/mathjs/docs/reference/classes.md new file mode 100644 index 0000000..8954572 --- /dev/null +++ b/node_modules/mathjs/docs/reference/classes.md @@ -0,0 +1,86 @@ + +# Class Reference + +This page lists all the various class types in Math.js. Every top-level function is listed here and links to its detailed reference to other parts of the documentation. + +## math + +The "math" namespace contains the entire math.js functionality. All of the mathematical functions are available in the "math" namespace, and allow for inputs of various types. + +- [Function reference](functions.md) +- [Constant reference](constants.md) + + +## Unit + +Stores values for a scalar unit and its postfix. (eg `100 mm` or `100 kg`). Although the `Unit` class contains public functions documented as follows, using the following API directly is *not* recommended. Prefer using the functions in the "math" namespace wherever possible. + +- [Overview](../datatypes/units.md) +- [Class API](classes/unit.md) + + +## Fraction + +Stores values for a fractional number. + +- [Overview](../datatypes/fractions.md) +- [Class API](https://github.com/infusion/Fraction.js/) + +## BigNumber + +Stores values for a arbitrary-precision floating point number. + +- [Overview](../datatypes/bignumbers.md) +- [Class API](https://mikemcl.github.io/decimal.js/) + + +## Matrix + +Two types of matrix classes are available in math.js, for storage of dense and sparse matrices. Although they contain public functions documented as follows, using the following API directly is *not* recommended. Prefer using the functions in the "math" namespace wherever possible. + +- [Overview](../datatypes/matrices.md) +- [DenseMatrix](classes/densematrix.md) +- [SparseMatrix](classes/sparsematrix.md) + +Classes used internally that may be of use to developers: + +- [Index](classes/matrixindex.md) +- [Range](classes/matrixrange.md) +- [ResultSet](classes/matrixrange.md) +- [FibonacciHeap](classes/fibonacciheap.md) + +## Complex + +Stores values for a complex number. + +- [Overview](../datatypes/complex_numbers.md) +- [Class API](https://github.com/infusion/Complex.js/) + +## Parser + +The Parser object returned by `math.parser()`. + +- [Overview](../expressions/parsing.md) + +## Node + +A node in an expression-tree, which can be used to analyze, manipulate, and evaluate expressions. + +- [Overview](../expressions/expression_trees.md) + +`Node` is the base class of all other node classes: + +- [AccessorNode](../expressions/expression_trees.md#accessornode) +- [ArrayNode](../expressions/expression_trees.md#arraynode) +- [AssignmentNode](../expressions/expression_trees.md#assignmentnode) +- [BlockNode](../expressions/expression_trees.md#blocknode) +- [ConditionalNode](../expressions/expression_trees.md#conditionalnode) +- [ConstantNode](../expressions/expression_trees.md#constantnode) +- [FunctionAssignmentNode](../expressions/expression_trees.md#functionassignmentnode) +- [FunctionNode](../expressions/expression_trees.md#functionnode) +- [IndexNode](../expressions/expression_trees.md#indexnode) +- [ObjectNode](../expressions/expression_trees.md#objectnode) +- [OperatorNode](../expressions/expression_trees.md#operatornode) +- [ParenthesisNode](../expressions/expression_trees.md#parenthesisnode) +- [RangeNode](../expressions/expression_trees.md#rangenode) +- [SymbolNode](../expressions/expression_trees.md#symbolnode) diff --git a/node_modules/mathjs/docs/reference/classes/densematrix.md b/node_modules/mathjs/docs/reference/classes/densematrix.md new file mode 100644 index 0000000..8c9f377 --- /dev/null +++ b/node_modules/mathjs/docs/reference/classes/densematrix.md @@ -0,0 +1,247 @@ + +## DenseMatrix +Dense Matrix implementation. This type implements an efficient Array format +for dense matrices. + +* _instance_ + * [.storage()](#DenseMatrix+storage) ⇒ string + * [.datatype()](#DenseMatrix+datatype) ⇒ string + * [.create(data, [datatype])](#DenseMatrix+create) + * [.subset(index, [replacement], [defaultValue])](#DenseMatrix+subset) + * [.get(index)](#DenseMatrix+get) ⇒ \* + * [.set(index, value, [defaultValue])](#DenseMatrix+set) ⇒ DenseMatrix + * [.resize(size, [defaultValue], [copy])](#DenseMatrix+resize) ⇒ Matrix + * [.clone()](#DenseMatrix+clone) ⇒ DenseMatrix + * [.size()](#DenseMatrix+size) ⇒ Array.<number> + * [.map(callback)](#DenseMatrix+map) ⇒ DenseMatrix + * [.forEach(callback)](#DenseMatrix+forEach) + * [.toArray()](#DenseMatrix+toArray) ⇒ Array + * [.valueOf()](#DenseMatrix+valueOf) ⇒ Array + * [.format([options])](#DenseMatrix+format) ⇒ string + * [.toString()](#DenseMatrix+toString) ⇒ string + * [.toJSON()](#DenseMatrix+toJSON) ⇒ Object + * [.diagonal([k])](#DenseMatrix+diagonal) ⇒ Array + * [.swapRows(i, j)](#DenseMatrix+swapRows) ⇒ Matrix +* _static_ + * [.diagonal(size, value, [k], [defaultValue])](#DenseMatrix.diagonal) ⇒ DenseMatrix + * [.fromJSON(json)](#DenseMatrix.fromJSON) ⇒ DenseMatrix + * [.preprocess(data)](#DenseMatrix.preprocess) ⇒ Array + + +### denseMatrix.storage() ⇒ string +Get the storage format used by the matrix. + +Usage: + +```js +const format = matrix.storage() // retrieve storage format +``` + +**Kind**: instance method of DenseMatrix +**Returns**: string - The storage format. + +### denseMatrix.datatype() ⇒ string +Get the datatype of the data stored in the matrix. + +Usage: + +```js +const format = matrix.datatype() // retrieve matrix datatype +``` + +**Kind**: instance method of DenseMatrix +**Returns**: string - The datatype. + +### denseMatrix.create(data, [datatype]) +Create a new DenseMatrix + +**Kind**: instance method of DenseMatrix + +| Param | Type | +| --- | --- | +| data | Array | +| [datatype] | string | + + +### denseMatrix.subset(index, [replacement], [defaultValue]) +Get a subset of the matrix, or replace a subset of the matrix. + +Usage: + +```js +const subset = matrix.subset(index) // retrieve subset +const value = matrix.subset(index, replacement) // replace subset +``` + +**Kind**: instance method of DenseMatrix + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| index | Index | | | +| [replacement] | Array | DenseMatrix| \* | | | +| [defaultValue] | \* | 0 | Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be filled with zeros. | + + +### denseMatrix.get(index) ⇒ \* +Get a single element from the matrix. + +**Kind**: instance method of DenseMatrix +**Returns**: \* - value + +| Param | Type | Description | +| --- | --- | --- | +| index | Array.<number> | Zero-based index | + + +### denseMatrix.set(index, value, [defaultValue]) ⇒ DenseMatrix +Replace a single element in the matrix. + +**Kind**: instance method of DenseMatrix +**Returns**: DenseMatrix- self + +| Param | Type | Description | +| --- | --- | --- | +| index | Array.<number> | Zero-based index | +| value | \* | | +| [defaultValue] | \* | Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be left undefined. | + + +### denseMatrix.resize(size, [defaultValue], [copy]) ⇒ Matrix +Resize the matrix to the given size. Returns a copy of the matrix when +`copy=true`, otherwise return the matrix itself (resize in place). + +**Kind**: instance method of DenseMatrix +**Returns**: Matrix - The resized matrix + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| size | Array.<number> | | The new size the matrix should have. | +| [defaultValue] | \* | 0 | Default value, filled in on new entries. If not provided, the matrix elements will be filled with zeros. | +| [copy] | boolean | | Return a resized copy of the matrix | + + +### denseMatrix.clone() ⇒ DenseMatrix +Create a clone of the matrix + +**Kind**: instance method of DenseMatrix +**Returns**: DenseMatrix- clone + +### denseMatrix.size() ⇒ Array.<number> +Retrieve the size of the matrix. + +**Kind**: instance method of DenseMatrix +**Returns**: Array.<number> - size + +### denseMatrix.map(callback) ⇒ DenseMatrix +Create a new matrix with the results of the callback function executed on +each entry of the matrix. + +**Kind**: instance method of DenseMatrix +**Returns**: DenseMatrix- matrix + +| Param | Type | Description | +| --- | --- | --- | +| callback | function | The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed. | + + +### denseMatrix.forEach(callback) +Execute a callback function on each entry of the matrix. + +**Kind**: instance method of DenseMatrix + +| Param | Type | Description | +| --- | --- | --- | +| callback | function | The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed. | + + +### denseMatrix.toArray() ⇒ Array +Create an Array with a copy of the data of the DenseMatrix + +**Kind**: instance method of DenseMatrix +**Returns**: Array - array + +### denseMatrix.valueOf() ⇒ Array +Get the primitive value of the DenseMatrix: a multidimensional array + +**Kind**: instance method of DenseMatrix +**Returns**: Array - array + +### denseMatrix.format([options]) ⇒ string +Get a string representation of the matrix, with optional formatting options. + +**Kind**: instance method of DenseMatrix +**Returns**: string - str + +| Param | Type | Description | +| --- | --- | --- | +| [options] | Object | number | function | Formatting options. See lib/utils/number:format for a description of the available options. | + + +### denseMatrix.toString() ⇒ string +Get a string representation of the matrix + +**Kind**: instance method of DenseMatrix +**Returns**: string - str + +### denseMatrix.toJSON() ⇒ Object +Get a JSON representation of the matrix + +**Kind**: instance method of DenseMatrix + +### denseMatrix.diagonal([k]) ⇒ Array +Get the kth Matrix diagonal. + +**Kind**: instance method of DenseMatrix +**Returns**: Array - The array vector with the diagonal values. + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [k] | number | BigNumber | 0 | The kth diagonal where the vector will retrieved. | + + +### denseMatrix.swapRows(i, j) ⇒ Matrix +Swap rows i and j in Matrix. + +**Kind**: instance method of DenseMatrix +**Returns**: Matrix - The matrix reference + +| Param | Type | Description | +| --- | --- | --- | +| i | number | Matrix row index 1 | +| j | number | Matrix row index 2 | + + +### DenseMatrix.diagonal(size, value, [k], [defaultValue]) ⇒ DenseMatrix +Create a diagonal matrix. + +**Kind**: static method of DenseMatrix + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| size | Array | | The matrix size. | +| value | number | Array | | The values for the diagonal. | +| [k] | number | BigNumber | 0 | The kth diagonal where the vector will be filled in. | +| [defaultValue] | number | | The default value for non-diagonal | + + +### DenseMatrix.fromJSON(json) ⇒ DenseMatrix +Generate a matrix from a JSON object + +**Kind**: static method of DenseMatrix + +| Param | Type | Description | +| --- | --- | --- | +| json | Object | An object structured like `{"mathjs": "DenseMatrix", data: [], size: []}`, where mathjs is optional | + + +### DenseMatrix.preprocess(data) ⇒ Array +Preprocess data, which can be an Array or DenseMatrix with nested Arrays and +Matrices. Replaces all nested Matrices with Arrays + +**Kind**: static method of DenseMatrix +**Returns**: Array - data + +| Param | Type | +| --- | --- | +| data | Array | + diff --git a/node_modules/mathjs/docs/reference/classes/fibonacciheap.md b/node_modules/mathjs/docs/reference/classes/fibonacciheap.md new file mode 100644 index 0000000..7021674 --- /dev/null +++ b/node_modules/mathjs/docs/reference/classes/fibonacciheap.md @@ -0,0 +1,70 @@ + +## FibonacciHeap +* [new FibonacciHeap()](#new_FibonacciHeap_new) +* _instance_ + * [.insert()](#FibonacciHeap+insert) + * [.size()](#FibonacciHeap+size) + * [.clear()](#FibonacciHeap+clear) + * [.isEmpty()](#FibonacciHeap+isEmpty) + * [.extractMinimum()](#FibonacciHeap+extractMinimum) + * [.remove()](#FibonacciHeap+remove) +* _static_ + * [._decreaseKey()](#FibonacciHeap._decreaseKey) + * [._cut()](#FibonacciHeap._cut) + * [._cascadingCut()](#FibonacciHeap._cascadingCut) + * [._linkNodes()](#FibonacciHeap._linkNodes) + + +### new FibonacciHeap() +Creates a new instance of a Fibonacci Heap. + + +### fibonacciHeap.insert() +Inserts a new data element into the heap. No heap consolidation is performed at this time, the new node is simply inserted into the root list of this heap. Running time: O(1) actual. + +**Kind**: instance method of [FibonacciHeap](#FibonacciHeap) + +### fibonacciHeap.size() +Returns the number of nodes in heap. Running time: O(1) actual. + +**Kind**: instance method of [FibonacciHeap](#FibonacciHeap) + +### fibonacciHeap.clear() +Removes all elements from this heap. + +**Kind**: instance method of [FibonacciHeap](#FibonacciHeap) + +### fibonacciHeap.isEmpty() +Returns true if the heap is empty, otherwise false. + +**Kind**: instance method of [FibonacciHeap](#FibonacciHeap) + +### fibonacciHeap.extractMinimum() +Extracts the node with minimum key from heap. Amortized running time: O(log n). + +**Kind**: instance method of [FibonacciHeap](#FibonacciHeap) + +### fibonacciHeap.remove() +Removes a node from the heap given the reference to the node. The trees in the heap will be consolidated, if necessary. This operation may fail to remove the correct element if there are nodes with key value -Infinity. Running time: O(log n) amortized. + +**Kind**: instance method of [FibonacciHeap](#FibonacciHeap) + +### FibonacciHeap._decreaseKey() +Decreases the key value for a heap node, given the new value to take on. The structure of the heap may be changed and will not be consolidated. Running time: O(1) amortized. + +**Kind**: static method of [FibonacciHeap](#FibonacciHeap) + +### FibonacciHeap._cut() +The reverse of the link operation: removes node from the child list of parent. This method assumes that min is non-null. Running time: O(1). + +**Kind**: static method of [FibonacciHeap](#FibonacciHeap) + +### FibonacciHeap._cascadingCut() +Performs a cascading cut operation. This cuts node from its parent and then does the same for its parent, and so on up the tree. Running time: O(log n); O(1) excluding the recursion. + +**Kind**: static method of [FibonacciHeap](#FibonacciHeap) + +### FibonacciHeap._linkNodes() +Make the first node a child of the second one. Running time: O(1) actual. + +**Kind**: static method of [FibonacciHeap](#FibonacciHeap) diff --git a/node_modules/mathjs/docs/reference/classes/matrixindex.md b/node_modules/mathjs/docs/reference/classes/matrixindex.md new file mode 100644 index 0000000..2e21133 --- /dev/null +++ b/node_modules/mathjs/docs/reference/classes/matrixindex.md @@ -0,0 +1,133 @@ + +## Index +* [new Index(...ranges)](#new_Index_new) +* _instance_ + * [.valueOf](#Index+valueOf) ⇒ Array + * [.clone()](#Index+clone) ⇒ [Index](#Index) + * [.size()](#Index+size) ⇒ Array.<number> + * [.max()](#Index+max) ⇒ Array.<number> + * [.min()](#Index+min) ⇒ Array.<number> + * [.forEach(callback)](#Index+forEach) + * [.dimension(dim)](#Index+dimension) ⇒ Range | null + * [.isScalar()](#Index+isScalar) ⇒ boolean + * [.toArray()](#Index+toArray) ⇒ Array + * [.toString()](#Index+toString) ⇒ String + * [.toJSON()](#Index+toJSON) ⇒ Object +* _static_ + * [.fromJSON(json)](#Index.fromJSON) ⇒ [Index](#Index) + + +### new Index(...ranges) +Create an index. An Index can store ranges and sets for multiple dimensions. +Matrix.get, Matrix.set, and math.subset accept an Index as input. + +Usage: +```js +const index = new Index(range1, range2, matrix1, array1, ...) +``` + +Where each parameter can be any of: + +- A number +- An instance of Range +- An Array with the Set values +- A Matrix with the Set values + +The parameters start, end, and step must be integer numbers. + + +| Param | Type | +| --- | --- | +| ...ranges | \* | + + +### index.valueOf ⇒ Array +Get the primitive value of the Index, a two dimensional array. +Equivalent to Index.toArray(). + +**Kind**: instance property of [Index](#Index) +**Returns**: Array - array + +### index.clone() ⇒ [Index](#Index) +Create a clone of the index + +**Kind**: instance method of [Index](#Index) +**Returns**: [Index](#Index) - clone + +### index.size() ⇒ Array.<number> +Retrieve the size of the index, the number of elements for each dimension. + +**Kind**: instance method of [Index](#Index) +**Returns**: Array.<number> - size + +### index.max() ⇒ Array.<number> +Get the maximum value for each of the indexes ranges. + +**Kind**: instance method of [Index](#Index) +**Returns**: Array.<number> - max + +### index.min() ⇒ Array.<number> +Get the minimum value for each of the indexes ranges. + +**Kind**: instance method of [Index](#Index) +**Returns**: Array.<number> - min + +### index.forEach(callback) +Loop over each of the ranges of the index + +**Kind**: instance method of [Index](#Index) + +| Param | Type | Description | +| --- | --- | --- | +| callback | function | Called for each range with a Range as first argument, the dimension as second, and the index object as third. | + + +### index.dimension(dim) ⇒ Range | null +Retrieve the dimension for the given index + +**Kind**: instance method of [Index](#Index) +**Returns**: Range | null - range + +| Param | Type | Description | +| --- | --- | --- | +| dim | Number | Number of the dimension | + + +### index.isScalar() ⇒ boolean +Test whether this index contains only a single value. + +This is the case when the index is created with only scalar values as ranges, +not for ranges resolving into a single value. + +**Kind**: instance method of [Index](#Index) +**Returns**: boolean - isScalar + +### index.toArray() ⇒ Array +Expand the Index into an array. +For example new Index([0,3], [2,7]) returns [[0,1,2], [2,3,4,5,6]] + +**Kind**: instance method of [Index](#Index) +**Returns**: Array - array + +### index.toString() ⇒ String +Get the string representation of the index, for example '[2:6]' or '[0:2:10, 4:7, [1,2,3]]' + +**Kind**: instance method of [Index](#Index) +**Returns**: String - str + +### index.toJSON() ⇒ Object +Get a JSON representation of the Index + +**Kind**: instance method of [Index](#Index) +**Returns**: Object - Returns a JSON object structured as: + `{"mathjs": "Index", "ranges": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}` + +### Index.fromJSON(json) ⇒ [Index](#Index) +Instantiate an Index from a JSON object + +**Kind**: static method of [Index](#Index) + +| Param | Type | Description | +| --- | --- | --- | +| json | Object | A JSON object structured as: `{"mathjs": "Index", "dimensions": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}` | + diff --git a/node_modules/mathjs/docs/reference/classes/matrixrange.md b/node_modules/mathjs/docs/reference/classes/matrixrange.md new file mode 100644 index 0000000..a16002e --- /dev/null +++ b/node_modules/mathjs/docs/reference/classes/matrixrange.md @@ -0,0 +1,158 @@ + +## Range +* [new Range(start, end, [step])](#new_Range_new) +* _instance_ + * [.size()](#Range+size) ⇒ Array.<number> + * [.min()](#Range+min) ⇒ number | undefined + * [.max()](#Range+max) ⇒ number | undefined + * [.forEach(callback)](#Range+forEach) + * [.map(callback)](#Range+map) ⇒ Array + * [.toArray()](#Range+toArray) ⇒ Array + * [.valueOf()](#Range+valueOf) ⇒ Array + * [.format([options])](#Range+format) ⇒ string + * [.toString()](#Range+toString) ⇒ string + * [.toJSON()](#Range+toJSON) ⇒ Object +* _static_ + * [.parse(str)](#Range.parse) ⇒ [Range](#Range) | null + * [.fromJSON(json)](#Range.fromJSON) ⇒ [Range](#Range) + + +### new Range(start, end, [step]) +Create a range. A range has a start, step, and end, and contains functions +to iterate over the range. + +A range can be constructed as: + +```js +const range = new Range(start, end) +const range = new Range(start, end, step) +``` + +To get the result of the range: + +```js +range.forEach(function (x) { + console.log(x) +}) +range.map(function (x) { + return math.sin(x) +}) +range.toArray() +``` + +Example usage: + +```js +const c = new Range(2, 6) // 2:1:5 +c.toArray() // [2, 3, 4, 5] +const d = new Range(2, -3, -1) // 2:-1:-2 +d.toArray() // [2, 1, 0, -1, -2] +``` + +| Param | Type | Description | +| --- | --- | --- | +| start | number | included lower bound | +| end | number | excluded upper bound | +| [step] | number | step size, default value is 1 | + + +### range.size() ⇒ Array.<number> +Retrieve the size of the range. +Returns an array containing one number, the number of elements in the range. + +**Kind**: instance method of [Range](#Range) +**Returns**: Array.<number> - size + +### range.min() ⇒ number | undefined +Calculate the minimum value in the range + +**Kind**: instance method of [Range](#Range) +**Returns**: number | undefined - min + +### range.max() ⇒ number | undefined +Calculate the maximum value in the range + +**Kind**: instance method of [Range](#Range) +**Returns**: number | undefined - max + +### range.forEach(callback) +Execute a callback function for each value in the range. + +**Kind**: instance method of [Range](#Range) + +| Param | Type | Description | +| --- | --- | --- | +| callback | function | The callback method is invoked with three parameters: the value of the element, the index of the element, and the Range being traversed. | + + +### range.map(callback) ⇒ Array +Execute a callback function for each value in the Range, and return the +results as an array + +**Kind**: instance method of [Range](#Range) +**Returns**: Array - array + +| Param | Type | Description | +| --- | --- | --- | +| callback | function | The callback method is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed. | + + +### range.toArray() ⇒ Array +Create an Array with a copy of the Ranges data + +**Kind**: instance method of [Range](#Range) +**Returns**: Array - array + +### range.valueOf() ⇒ Array +Get the primitive value of the Range, a one dimensional array + +**Kind**: instance method of [Range](#Range) +**Returns**: Array - array + +### range.format([options]) ⇒ string +Get a string representation of the range, with optional formatting options. +Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11' + +**Kind**: instance method of [Range](#Range) +**Returns**: string - str + +| Param | Type | Description | +| --- | --- | --- | +| [options] | Object | number | function | Formatting options. See lib/utils/number:format for a description of the available options. | + + +### range.toString() ⇒ string +Get a string representation of the range. + +**Kind**: instance method of [Range](#Range) + +### range.toJSON() ⇒ Object +Get a JSON representation of the range + +**Kind**: instance method of [Range](#Range) +**Returns**: Object - Returns a JSON object structured as: + `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` + +### Range.parse(str) ⇒ [Range](#Range) | null +Parse a string into a range, +The string contains the start, optional step, and end, separated by a colon. +If the string does not contain a valid range, null is returned. +For example str='0:2:11'. + +**Kind**: static method of [Range](#Range) +**Returns**: [Range](#Range) | null - range + +| Param | Type | +| --- | --- | +| str | string | + + +### Range.fromJSON(json) ⇒ [Range](#Range) +Instantiate a Range from a JSON object + +**Kind**: static method of [Range](#Range) + +| Param | Type | Description | +| --- | --- | --- | +| json | Object | A JSON object structured as: `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` | + diff --git a/node_modules/mathjs/docs/reference/classes/resultset.md b/node_modules/mathjs/docs/reference/classes/resultset.md new file mode 100644 index 0000000..b70ffb6 --- /dev/null +++ b/node_modules/mathjs/docs/reference/classes/resultset.md @@ -0,0 +1,47 @@ + +## ResultSet +* [new ResultSet(entries)](#new_ResultSet_new) +* _instance_ + * [.valueOf()](#ResultSet+valueOf) ⇒ Array + * [.toString()](#ResultSet+toString) ⇒ string + * [.toJSON()](#ResultSet+toJSON) ⇒ Object +* _static_ + * [.fromJSON(json)](#ResultSet.fromJSON) ⇒ [ResultSet](#ResultSet) + + +### new ResultSet(entries) +A ResultSet contains a list or results + + +| Param | Type | +| --- | --- | +| entries | Array | + + +### resultSet.valueOf() ⇒ Array +Returns the array with results hold by this ResultSet + +**Kind**: instance method of [ResultSet](#ResultSet) +**Returns**: Array - entries + +### resultSet.toString() ⇒ string +Returns the stringified results of the ResultSet + +**Kind**: instance method of [ResultSet](#ResultSet) +**Returns**: string - string + +### resultSet.toJSON() ⇒ Object +Get a JSON representation of the ResultSet + +**Kind**: instance method of [ResultSet](#ResultSet) +**Returns**: Object - Returns a JSON object structured as: `{"mathjs": "ResultSet", "entries": [...]}` + +### ResultSet.fromJSON(json) ⇒ [ResultSet](#ResultSet) +Instantiate a ResultSet from a JSON object + +**Kind**: static method of [ResultSet](#ResultSet) + +| Param | Type | Description | +| --- | --- | --- | +| json | Object | A JSON object structured as: `{"mathjs": "ResultSet", "entries": [...]}` | + diff --git a/node_modules/mathjs/docs/reference/classes/sparsematrix.md b/node_modules/mathjs/docs/reference/classes/sparsematrix.md new file mode 100644 index 0000000..3007436 --- /dev/null +++ b/node_modules/mathjs/docs/reference/classes/sparsematrix.md @@ -0,0 +1,245 @@ + +## SparseMatrix +Sparse Matrix implementation. This type implements a Compressed Column Storage format +for sparse matrices. + +* _instance_ + * [.storage()](#SparseMatrix+storage) ⇒ string + * [.datatype()](#SparseMatrix+datatype) ⇒ string + * [.create(data, [datatype])](#SparseMatrix+create) + * [.density()](#SparseMatrix+density) ⇒ number + * [.subset(index, [replacement], [defaultValue])](#SparseMatrix+subset) + * [.get(index)](#SparseMatrix+get) ⇒ \* + * [.set(index, value, [defaultValue])](#SparseMatrix+set) ⇒ [SparseMatrix](#SparseMatrix) + * [.resize(size, [defaultValue], [copy])](#SparseMatrix+resize) ⇒ Matrix + * [.clone()](#SparseMatrix+clone) ⇒ [SparseMatrix](#SparseMatrix) + * [.size()](#SparseMatrix+size) ⇒ Array.<number> + * [.map(callback, [skipZeros])](#SparseMatrix+map) ⇒ [SparseMatrix](#SparseMatrix) + * [.forEach(callback, [skipZeros])](#SparseMatrix+forEach) + * [.toArray()](#SparseMatrix+toArray) ⇒ Array + * [.valueOf()](#SparseMatrix+valueOf) ⇒ Array + * [.format([options])](#SparseMatrix+format) ⇒ string + * [.toString()](#SparseMatrix+toString) ⇒ string + * [.toJSON()](#SparseMatrix+toJSON) ⇒ Object + * [.diagonal([k])](#SparseMatrix+diagonal) ⇒ Matrix + * [.swapRows(i, j)](#SparseMatrix+swapRows) ⇒ Matrix +* _static_ + * [.fromJSON(json)](#SparseMatrix.fromJSON) ⇒ [SparseMatrix](#SparseMatrix) + * [.diagonal(size, value, [k], [datatype])](#SparseMatrix.diagonal) ⇒ [SparseMatrix](#SparseMatrix) + + +### sparseMatrix.storage() ⇒ string +Get the storage format used by the matrix. + +Usage: +```js +const format = matrix.storage() // retrieve storage format +``` + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: string - The storage format. + +### sparseMatrix.datatype() ⇒ string +Get the datatype of the data stored in the matrix. + +Usage: +```js +const format = matrix.datatype() // retrieve matrix datatype +``` + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: string - The datatype. + +### sparseMatrix.create(data, [datatype]) +Create a new SparseMatrix + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) + +| Param | Type | +| --- | --- | +| data | Array | +| [datatype] | string | + + +### sparseMatrix.density() ⇒ number +Get the matrix density. + +Usage: +```js +const density = matrix.density() // retrieve matrix density +``` + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: number - The matrix density. + +### sparseMatrix.subset(index, [replacement], [defaultValue]) +Get a subset of the matrix, or replace a subset of the matrix. + +Usage: +```js +const subset = matrix.subset(index) // retrieve subset +const value = matrix.subset(index, replacement) // replace subset +``` + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| index | Index | | | +| [replacement] | Array | Maytrix | \* | | | +| [defaultValue] | \* | 0 | Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be filled with zeros. | + + +### sparseMatrix.get(index) ⇒ \* +Get a single element from the matrix. + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: \* - value + +| Param | Type | Description | +| --- | --- | --- | +| index | Array.<number> | Zero-based index | + + +### sparseMatrix.set(index, value, [defaultValue]) ⇒ [SparseMatrix](#SparseMatrix) +Replace a single element in the matrix. + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: [SparseMatrix](#SparseMatrix) - self + +| Param | Type | Description | +| --- | --- | --- | +| index | Array.<number> | Zero-based index | +| value | \* | | +| [defaultValue] | \* | Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be set to zero. | + + +### sparseMatrix.resize(size, [defaultValue], [copy]) ⇒ Matrix +Resize the matrix to the given size. Returns a copy of the matrix when +`copy=true`, otherwise return the matrix itself (resize in place). + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: Matrix - The resized matrix + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| size | Array.<number> | | The new size the matrix should have. | +| [defaultValue] | \* | 0 | Default value, filled in on new entries. If not provided, the matrix elements will be filled with zeros. | +| [copy] | boolean | | Return a resized copy of the matrix | + + +### sparseMatrix.clone() ⇒ [SparseMatrix](#SparseMatrix) +Create a clone of the matrix + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: [SparseMatrix](#SparseMatrix) - clone + +### sparseMatrix.size() ⇒ Array.<number> +Retrieve the size of the matrix. + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: Array.<number> - size + +### sparseMatrix.map(callback, [skipZeros]) ⇒ [SparseMatrix](#SparseMatrix) +Create a new matrix with the results of the callback function executed on +each entry of the matrix. + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: [SparseMatrix](#SparseMatrix) - matrix + +| Param | Type | Description | +| --- | --- | --- | +| callback | function | The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed. | +| [skipZeros] | boolean | Invoke callback function for non-zero values only. | + + +### sparseMatrix.forEach(callback, [skipZeros]) +Execute a callback function on each entry of the matrix. + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) + +| Param | Type | Description | +| --- | --- | --- | +| callback | function | The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed. | +| [skipZeros] | boolean | Invoke callback function for non-zero values only. | + + +### sparseMatrix.toArray() ⇒ Array +Create an Array with a copy of the data of the SparseMatrix + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: Array - array + +### sparseMatrix.valueOf() ⇒ Array +Get the primitive value of the SparseMatrix: a two dimensions array + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: Array - array + +### sparseMatrix.format([options]) ⇒ string +Get a string representation of the matrix, with optional formatting options. + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: string - str + +| Param | Type | Description | +| --- | --- | --- | +| [options] | Object | number | function | Formatting options. See lib/utils/number:format for a description of the available options. | + + +### sparseMatrix.toString() ⇒ string +Get a string representation of the matrix + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: string - str + +### sparseMatrix.toJSON() ⇒ Object +Get a JSON representation of the matrix + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) + +### sparseMatrix.diagonal([k]) ⇒ Matrix +Get the kth Matrix diagonal. + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: Matrix - The matrix vector with the diagonal values. + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [k] | number | BigNumber | 0 | The kth diagonal where the vector will retrieved. | + + +### sparseMatrix.swapRows(i, j) ⇒ Matrix +Swap rows i and j in Matrix. + +**Kind**: instance method of [SparseMatrix](#SparseMatrix) +**Returns**: Matrix - The matrix reference + +| Param | Type | Description | +| --- | --- | --- | +| i | number | Matrix row index 1 | +| j | number | Matrix row index 2 | + + +### SparseMatrix.fromJSON(json) ⇒ [SparseMatrix](#SparseMatrix) +Generate a matrix from a JSON object + +**Kind**: static method of [SparseMatrix](#SparseMatrix) + +| Param | Type | Description | +| --- | --- | --- | +| json | Object | An object structured like `{"mathjs": "SparseMatrix", "values": [], "index": [], "ptr": [], "size": []}`, where mathjs is optional | + + +### SparseMatrix.diagonal(size, value, [k], [datatype]) ⇒ [SparseMatrix](#SparseMatrix) +Create a diagonal matrix. + +**Kind**: static method of [SparseMatrix](#SparseMatrix) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| size | Array | | The matrix size. | +| value | number | Array | Matrix | | The values for the diagonal. | +| [k] | number | BigNumber | 0 | The kth diagonal where the vector will be filled in. | +| [datatype] | string | | The Matrix datatype, values must be of this datatype. | + diff --git a/node_modules/mathjs/docs/reference/classes/unit.md b/node_modules/mathjs/docs/reference/classes/unit.md new file mode 100644 index 0000000..5deae14 --- /dev/null +++ b/node_modules/mathjs/docs/reference/classes/unit.md @@ -0,0 +1,242 @@ + +## Unit +* [new Unit([value], [name])](#new_Unit_new) +* _instance_ + * [.valueOf](#Unit+valueOf) ⇒ string + * [.clone()](#Unit+clone) ⇒ Unit + * [._isDerived()](#Unit+_isDerived) ⇒ boolean + * [.hasBase(base)](#Unit+hasBase) + * [.equalBase(other)](#Unit+equalBase) ⇒ boolean + * [.equals(other)](#Unit+equals) ⇒ boolean + * [.multiply(other)](#Unit+multiply) ⇒ Unit + * [.divide(other)](#Unit+divide) ⇒ Unit + * [.pow(p)](#Unit+pow) ⇒ Unit + * [.abs(x)](#Unit+abs) ⇒ Unit + * [.to(valuelessUnit)](#Unit+to) ⇒ Unit + * [.toNumber(valuelessUnit)](#Unit+toNumber) ⇒ number + * [.toNumeric(valuelessUnit)](#Unit+toNumeric) ⇒ number | BigNumber | Fraction + * [.toString()](#Unit+toString) ⇒ string + * [.toJSON()](#Unit+toJSON) ⇒ Object + * [.formatUnits()](#Unit+formatUnits) ⇒ string + * [.format([options])](#Unit+format) ⇒ string +* _static_ + * [.parse(str)](#Unit.parse) ⇒ Unit + * [.isValuelessUnit(name)](#Unit.isValuelessUnit) ⇒ boolean + * [.fromJSON(json)](#Unit.fromJSON) ⇒ Unit + + +### new Unit([value], [name]) +A unit can be constructed in the following ways: + +```js +const a = new Unit(value, name) +const b = new Unit(null, name) +const c = Unit.parse(str) +``` + +Example usage: + +```js +const a = new Unit(5, 'cm') // 50 mm +const b = Unit.parse('23 kg') // 23 kg +const c = math.in(a, new Unit(null, 'm') // 0.05 m +const d = new Unit(9.81, "m/s^2") // 9.81 m/s^2 +``` + +| Param | Type | Description | +| --- | --- | --- | +| [value] | number | BigNumber | Fraction | Complex | boolean | A value like 5.2 | +| [name] | string | A unit name like "cm" or "inch", or a derived unit of the form: "u1[^ex1] [u2[^ex2] ...] [/ u3[^ex3] [u4[^ex4]]]", such as "kg m^2/s^2", where each unit appearing after the forward slash is taken to be in the denominator. "kg m^2 s^-2" is a synonym and is also acceptable. Any of the units can include a prefix. | + + +### unit.valueOf ⇒ string +Returns the string representation of the unit. + +**Kind**: instance property of Unit + +### unit.clone() ⇒ Unit +create a copy of this unit + +**Kind**: instance method of Unit +**Returns**: Unit - Returns a cloned version of the unit + +### unit._isDerived() ⇒ boolean +Return whether the unit is derived (such as m/s, or cm^2, but not N) + +**Kind**: instance method of Unit +**Returns**: boolean - True if the unit is derived + +### unit.hasBase(base) +check if this unit has given base unit +If this unit is a derived unit, this will ALWAYS return false, since by definition base units are not derived. + +**Kind**: instance method of Unit + +| Param | Type | +| --- | --- | +| base | BASE_UNITS | STRING | undefined | + + +### unit.equalBase(other) ⇒ boolean +Check if this unit has a base or bases equal to another base or bases +For derived units, the exponent on each base also must match + +**Kind**: instance method of Unit +**Returns**: boolean - true if equal base + +| Param | Type | +| --- | --- | +| other | Unit | + + +### unit.equals(other) ⇒ boolean +Check if this unit equals another unit + +**Kind**: instance method of Unit +**Returns**: boolean - true if both units are equal + +| Param | Type | +| --- | --- | +| other | Unit | + + +### unit.multiply(other) ⇒ Unit +Multiply this unit with another one + +**Kind**: instance method of Unit +**Returns**: Unit - product of this unit and the other unit + +| Param | Type | +| --- | --- | +| other | Unit | + + +### unit.divide(other) ⇒ Unit +Divide this unit by another one + +**Kind**: instance method of Unit +**Returns**: Unit - result of dividing this unit by the other unit + +| Param | Type | +| --- | --- | +| other | Unit | + + +### unit.pow(p) ⇒ Unit +Calculate the power of a unit + +**Kind**: instance method of Unit +**Returns**: Unit - The result: this^p + +| Param | Type | +| --- | --- | +| p | number | Fraction | BigNumber | + + +### unit.abs(x) ⇒ Unit +Calculate the absolute value of a unit + +**Kind**: instance method of Unit +**Returns**: Unit - The result: |x|, absolute value of x + +| Param | Type | +| --- | --- | +| x | number | Fraction | BigNumber | + + +### unit.to(valuelessUnit) ⇒ Unit +Convert the unit to a specific unit name. + +**Kind**: instance method of Unit +**Returns**: Unit - Returns a clone of the unit with a fixed prefix and unit. + +| Param | Type | Description | +| --- | --- | --- | +| valuelessUnit | string | Unit | A unit without value. Can have prefix, like "cm" | + + +### unit.toNumber(valuelessUnit) ⇒ number +Return the value of the unit when represented with given valueless unit + +**Kind**: instance method of Unit +**Returns**: number - Returns the unit value as number. + +| Param | Type | Description | +| --- | --- | --- | +| valuelessUnit | string | Unit | For example 'cm' or 'inch' | + + +### unit.toNumeric(valuelessUnit) ⇒ number | BigNumber | Fraction +Return the value of the unit in the original numeric type + +**Kind**: instance method of Unit +**Returns**: number | BigNumber | Fraction - Returns the unit value + +| Param | Type | Description | +| --- | --- | --- | +| valuelessUnit | string | Unit | For example 'cm' or 'inch' | + + +### unit.toString() ⇒ string +Get a string representation of the unit. + +**Kind**: instance method of Unit + +### unit.toJSON() ⇒ Object +Get a JSON representation of the unit + +**Kind**: instance method of Unit +**Returns**: Object - Returns a JSON object structured as: + `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}` + +### unit.formatUnits() ⇒ string +Get a string representation of the units of this Unit, without the value. + +**Kind**: instance method of Unit + +### unit.format([options]) ⇒ string +Get a string representation of the Unit, with optional formatting options. + +**Kind**: instance method of Unit + +| Param | Type | Description | +| --- | --- | --- | +| [options] | Object | number | function | Formatting options. See lib/utils/number:format for a description of the available options. | + + +### Unit.parse(str) ⇒ Unit +Parse a string into a unit. The value of the unit is parsed as number, +BigNumber, or Fraction depending on the math.js config setting `number`. + +Throws an exception if the provided string does not contain a valid unit or +cannot be parsed. + +**Kind**: static method of Unit +**Returns**: Unit - unit + +| Param | Type | Description | +| --- | --- | --- | +| str | string | A string like "5.2 inch", "4e2 cm/s^2" | + + +### Unit.isValuelessUnit(name) ⇒ boolean +Test if the given expression is a unit. +The unit can have a prefix but cannot have a value. + +**Kind**: static method of Unit +**Returns**: boolean - true if the given string is a unit + +| Param | Type | Description | +| --- | --- | --- | +| name | string | A string to be tested whether it is a value less unit. The unit can have prefix, like "cm" | + + +### Unit.fromJSON(json) ⇒ Unit +Instantiate a Unit from a JSON object + +**Kind**: static method of Unit + +| Param | Type | Description | +| --- | --- | --- | +| json | Object | A JSON object structured as: `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}` | + diff --git a/node_modules/mathjs/docs/reference/constants.md b/node_modules/mathjs/docs/reference/constants.md new file mode 100644 index 0000000..ebe15d1 --- /dev/null +++ b/node_modules/mathjs/docs/reference/constants.md @@ -0,0 +1,29 @@ +# Constant reference + +Math.js contains the following constants. + +Constant | Description | Value +--------------- | ----------- | ----- +`e`, `E` | Euler's number, the base of the natural logarithm. | 2.718281828459045 +`i` | Imaginary unit, defined as `i * i = -1`. A complex number is described as `a + b * i`, where a is the real part, and b is the imaginary part. | `sqrt(-1)` +`Infinity` | Infinity, a number which is larger than the maximum number that can be handled by a floating point number. | `Infinity` +`LN2` | Returns the natural logarithm of 2. | `0.6931471805599453` +`LN10` | Returns the natural logarithm of 10. | `2.302585092994046` +`LOG2E` | Returns the base-2 logarithm of E. | `1.4426950408889634` +`LOG10E` | Returns the base-10 logarithm of E. | `0.4342944819032518` +`NaN` | Not a number. | `NaN` +`null` | Value null. | `null` +`phi` | Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` | `1.618033988749895` +`pi`, `PI` | The number pi is a mathematical constant that is the ratio of a circle\'s circumference to its diameter. | `3.141592653589793` +`SQRT1_2` | Returns the square root of 1/2. | `0.7071067811865476` +`SQRT2` | Returns the square root of 2. | `1.4142135623730951` +`tau` | Tau is the ratio constant of a circle\'s circumference to radius, equal to `2 * pi`. | `6.283185307179586` +`undefined` | An undefined value. Preferably, use `null` to indicate undefined values. | `undefined` +`version` | Returns the version number of math.js. | For example `0.24.1` + +Example usage: + +```js +math.sin(math.pi / 4) // 0.70711 +math.multiply(math.i, math.i) // -1 +``` diff --git a/node_modules/mathjs/docs/reference/functions.md b/node_modules/mathjs/docs/reference/functions.md new file mode 100644 index 0000000..088e4e0 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions.md @@ -0,0 +1,295 @@ +# Function reference + +## Expression functions + +Function | Description +---- | ----------- +[math.compile(expr)](functions/compile.md) | Parse and compile an expression. +[math.evaluate(expr [, scope])](functions/evaluate.md) | Evaluate an expression. +[math.help(search)](functions/help.md) | Retrieve help on a function or data type. +[math.parser()](functions/parser.md) | Create a parser. + +## Algebra functions + +Function | Description +---- | ----------- +[derivative(expr, variable)](functions/derivative.md) | Takes the derivative of an expression expressed in parser Nodes. +[leafCount(expr)](functions/leafCount.md) | Gives the number of "leaf nodes" in the parse tree of the given expression A leaf node is one that has no subexpressions, essentially either a symbol or a constant. +[math.lsolve(L, b)](functions/lsolve.md) | Finds one solution of a linear equation system by forwards substitution. +[math.lsolveAll(L, b)](functions/lsolveAll.md) | Finds all solutions of a linear equation system by forwards substitution. +[math.lup(A)](functions/lup.md) | Calculate the Matrix LU decomposition with partial pivoting. +[math.lusolve(A, b)](functions/lusolve.md) | Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector. +[math.qr(A)](functions/qr.md) | Calculate the Matrix QR decomposition. +[rationalize(expr)](functions/rationalize.md) | Transform a rationalizable expression in a rational fraction. +[resolve(expr, scope)](functions/resolve.md) | resolve(expr, scope) replaces variable nodes with their scoped values. +[simplify(expr)](functions/simplify.md) | Simplify an expression tree. +[simplifyCore(expr)](functions/simplifyCore.md) | simplifyCore() performs single pass simplification suitable for applications requiring ultimate performance. +[math.slu(A, order, threshold)](functions/slu.md) | Calculate the Sparse Matrix LU decomposition with full pivoting. +[symbolicEqual(expr1, expr2)](functions/symbolicEqual.md) | Attempts to determine if two expressions are symbolically equal, i. +[math.usolve(U, b)](functions/usolve.md) | Finds one solution of a linear equation system by backward substitution. +[math.usolveAll(U, b)](functions/usolveAll.md) | Finds all solutions of a linear equation system by backward substitution. + +## Arithmetic functions + +Function | Description +---- | ----------- +[math.abs(x)](functions/abs.md) | Calculate the absolute value of a number. +[math.add(x, y)](functions/add.md) | Add two or more values, `x + y`. +[math.cbrt(x [, allRoots])](functions/cbrt.md) | Calculate the cubic root of a value. +[math.ceil(x)](functions/ceil.md) | Round a value towards plus infinity If `x` is complex, both real and imaginary part are rounded towards plus infinity. +[math.cube(x)](functions/cube.md) | Compute the cube of a value, `x * x * x`. +[math.divide(x, y)](functions/divide.md) | Divide two values, `x / y`. +[math.dotDivide(x, y)](functions/dotDivide.md) | Divide two matrices element wise. +[math.dotMultiply(x, y)](functions/dotMultiply.md) | Multiply two matrices element wise. +[math.dotPow(x, y)](functions/dotPow.md) | Calculates the power of x to y element wise. +[math.exp(x)](functions/exp.md) | Calculate the exponent of a value. +[math.expm1(x)](functions/expm1.md) | Calculate the value of subtracting 1 from the exponential value. +[math.fix(x)](functions/fix.md) | Round a value towards zero. +[math.floor(x)](functions/floor.md) | Round a value towards minus infinity. +[math.gcd(a, b)](functions/gcd.md) | Calculate the greatest common divisor for two or more values or arrays. +[math.hypot(a, b, ...)](functions/hypot.md) | Calculate the hypotenusa of a list with values. +[math.invmod(a, b)](functions/invmod.md) | Calculate the (modular) multiplicative inverse of a modulo b. +[math.lcm(a, b)](functions/lcm.md) | Calculate the least common multiple for two or more values or arrays. +[math.log(x [, base])](functions/log.md) | Calculate the logarithm of a value. +[math.log10(x)](functions/log10.md) | Calculate the 10-base logarithm of a value. +[math.log1p(x)](functions/log1p.md) | Calculate the logarithm of a `value+1`. +[math.log2(x)](functions/log2.md) | Calculate the 2-base of a value. +[math.mod(x, y)](functions/mod.md) | Calculates the modulus, the remainder of an integer division. +[math.multiply(x, y)](functions/multiply.md) | Multiply two or more values, `x * y`. +[math.norm(x [, p])](functions/norm.md) | Calculate the norm of a number, vector or matrix. +[math.nthRoot(a)](functions/nthRoot.md) | Calculate the nth root of a value. +[math.nthRoots(x)](functions/nthRoots.md) | Calculate the nth roots of a value. +[math.pow(x, y)](functions/pow.md) | Calculates the power of x to y, `x ^ y`. +[math.round(x [, n])](functions/round.md) | Round a value towards the nearest integer. +[math.sign(x)](functions/sign.md) | Compute the sign of a value. +[math.sqrt(x)](functions/sqrt.md) | Calculate the square root of a value. +[math.square(x)](functions/square.md) | Compute the square of a value, `x * x`. +[math.subtract(x, y)](functions/subtract.md) | Subtract two values, `x - y`. +[math.unaryMinus(x)](functions/unaryMinus.md) | Inverse the sign of a value, apply a unary minus operation. +[math.unaryPlus(x)](functions/unaryPlus.md) | Unary plus operation. +[math.xgcd(a, b)](functions/xgcd.md) | Calculate the extended greatest common divisor for two values. + +## Bitwise functions + +Function | Description +---- | ----------- +[math.bitAnd(x, y)](functions/bitAnd.md) | Bitwise AND two values, `x & y`. +[math.bitNot(x)](functions/bitNot.md) | Bitwise NOT value, `~x`. +[math.bitOr(x, y)](functions/bitOr.md) | Bitwise OR two values, `x | y`. +[math.bitXor(x, y)](functions/bitXor.md) | Bitwise XOR two values, `x ^ y`. +[math.leftShift(x, y)](functions/leftShift.md) | Bitwise left logical shift of a value x by y number of bits, `x << y`. +[math.rightArithShift(x, y)](functions/rightArithShift.md) | Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`. +[math.rightLogShift(x, y)](functions/rightLogShift.md) | Bitwise right logical shift of value x by y number of bits, `x >>> y`. + +## Combinatorics functions + +Function | Description +---- | ----------- +[math.bellNumbers(n)](functions/bellNumbers.md) | The Bell Numbers count the number of partitions of a set. +[math.catalan(n)](functions/catalan.md) | The Catalan Numbers enumerate combinatorial structures of many different types. +[math.composition(n, k)](functions/composition.md) | The composition counts of n into k parts. +[math.stirlingS2(n, k)](functions/stirlingS2.md) | The Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. + +## Complex functions + +Function | Description +---- | ----------- +[math.arg(x)](functions/arg.md) | Compute the argument of a complex value. +[math.conj(x)](functions/conj.md) | Compute the complex conjugate of a complex value. +[math.im(x)](functions/im.md) | Get the imaginary part of a complex number. +[math.re(x)](functions/re.md) | Get the real part of a complex number. + +## Geometry functions + +Function | Description +---- | ----------- +[math.distance([x1, y1], [x2, y2])](functions/distance.md) | Calculates: The eucledian distance between two points in N-dimensional spaces. +[math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2)](functions/intersect.md) | Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in three dimensions. + +## Logical functions + +Function | Description +---- | ----------- +[math.and(x, y)](functions/and.md) | Logical `and`. +[math.not(x)](functions/not.md) | Logical `not`. +[math.or(x, y)](functions/or.md) | Logical `or`. +[math.xor(x, y)](functions/xor.md) | Logical `xor`. + +## Matrix functions + +Function | Description +---- | ----------- +[math.apply(A, dim, callback)](functions/apply.md) | Apply a function that maps an array to a scalar along a given axis of a matrix or array. +[math.column(value, index)](functions/column.md) | Return a column from a Matrix. +[math.concat(a, b, c, ... [, dim])](functions/concat.md) | Concatenate two or more matrices. +[math.count(x)](functions/count.md) | Count the number of elements of a matrix, array or string. +[math.cross(x, y)](functions/cross.md) | Calculate the cross product for two vectors in three dimensional space. +[math.ctranspose(x)](functions/ctranspose.md) | Transpose and complex conjugate a matrix. +[math.det(x)](functions/det.md) | Calculate the determinant of a matrix. +[math.diag(X)](functions/diag.md) | Create a diagonal matrix or retrieve the diagonal of a matrix When `x` is a vector, a matrix with vector `x` on the diagonal will be returned. +[math.diff(arr)](functions/diff.md) | Create a new matrix or array of the difference between elements of the given array The optional dim parameter lets you specify the dimension to evaluate the difference of If no dimension parameter is passed it is assumed as dimension 0 Dimension is zero-based in javascript and one-based in the parser and can be a number or bignumber Arrays must be 'rectangular' meaning arrays like [1, 2] If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays. +[math.dot(x, y)](functions/dot.md) | Calculate the dot product of two vectors. +[math.eigs(x, [prec])](functions/eigs.md) | Compute eigenvalues and eigenvectors of a matrix. +[math.expm(x)](functions/expm.md) | Compute the matrix exponential, expm(A) = e^A. +[math.filter(x, test)](functions/filter.md) | Filter the items in an array or one dimensional matrix. +[math.flatten(x)](functions/flatten.md) | Flatten a multi dimensional matrix into a single dimensional matrix. +[math.forEach(x, callback)](functions/forEach.md) | Iterate over all elements of a matrix/array, and executes the given callback function. +[math.getMatrixDataType(x)](functions/getMatrixDataType.md) | Find the data type of all elements in a matrix or array, for example 'number' if all items are a number and 'Complex' if all values are complex numbers. +[math.identity(n)](functions/identity.md) | Create a 2-dimensional identity matrix with size m x n or n x n. +[math.inv(x)](functions/inv.md) | Calculate the inverse of a square matrix. +[math.kron(x, y)](functions/kron.md) | Calculates the kronecker product of 2 matrices or vectors. +[math.map(x, callback)](functions/map.md) | Create a new matrix or array with the results of a callback function executed on each entry of a given matrix/array. +[math.matrixFromColumns(...arr)](functions/matrixFromColumns.md) | Create a dense matrix from vectors as individual columns. +[math.matrixFromFunction(size, fn)](functions/matrixFromFunction.md) | Create a matrix by evaluating a generating function at each index. +[math.matrixFromRows(...arr)](functions/matrixFromRows.md) | Create a dense matrix from vectors as individual rows. +[math.ones(m, n, p, ...)](functions/ones.md) | Create a matrix filled with ones. +[math.partitionSelect(x, k)](functions/partitionSelect.md) | Partition-based selection of an array or 1D matrix. +[math.range(start, end [, step])](functions/range.md) | Create an array from a range. +[math.reshape(x, sizes)](functions/reshape.md) | Reshape a multi dimensional array to fit the specified dimensions. +[math.resize(x, size [, defaultValue])](functions/resize.md) | Resize a matrix. +[math.rotate(w, theta)](functions/rotate.md) | Rotate a vector of size 1x2 counter-clockwise by a given angle Rotate a vector of size 1x3 counter-clockwise by a given angle around the given axis. +[math.rotationMatrix(theta)](functions/rotationMatrix.md) | Create a 2-dimensional counter-clockwise rotation matrix (2x2) for a given angle (expressed in radians). +[math.row(value, index)](functions/row.md) | Return a row from a Matrix. +[math.size(x)](functions/size.md) | Calculate the size of a matrix or scalar. +[math.sort(x)](functions/sort.md) | Sort the items in a matrix. +[X = math.sqrtm(A)](functions/sqrtm.md) | Calculate the principal square root of a square matrix. +[math.squeeze(x)](functions/squeeze.md) | Squeeze a matrix, remove inner and outer singleton dimensions from a matrix. +[math.subset(x, index [, replacement])](functions/subset.md) | Get or set a subset of a matrix or string. +[math.trace(x)](functions/trace.md) | Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix. +[math.transpose(x)](functions/transpose.md) | Transpose a matrix. +[math.zeros(m, n, p, ...)](functions/zeros.md) | Create a matrix filled with zeros. + +## Probability functions + +Function | Description +---- | ----------- +[math.combinations(n, k)](functions/combinations.md) | Compute the number of ways of picking `k` unordered outcomes from `n` possibilities. +[math.combinationsWithRep(n, k)](functions/combinationsWithRep.md) | Compute the number of ways of picking `k` unordered outcomes from `n` possibilities, allowing individual outcomes to be repeated more than once. +[math.factorial(n)](functions/factorial.md) | Compute the factorial of a value Factorial only supports an integer value as argument. +[math.gamma(n)](functions/gamma.md) | Compute the gamma function of a value using Lanczos approximation for small values, and an extended Stirling approximation for large values. +[math.kldivergence(x, y)](functions/kldivergence.md) | Calculate the Kullback-Leibler (KL) divergence between two distributions. +[math.multinomial(a)](functions/multinomial.md) | Multinomial Coefficients compute the number of ways of picking a1, a2, . +[math.permutations(n [, k])](functions/permutations.md) | Compute the number of ways of obtaining an ordered subset of `k` elements from a set of `n` elements. +[math.pickRandom(array)](functions/pickRandom.md) | Random pick one or more values from a one dimensional array. +[math.random([min, max])](functions/random.md) | Return a random number larger or equal to `min` and smaller than `max` using a uniform distribution. +[math.randomInt([min, max])](functions/randomInt.md) | Return a random integer number larger or equal to `min` and smaller than `max` using a uniform distribution. + +## Relational functions + +Function | Description +---- | ----------- +[math.compare(x, y)](functions/compare.md) | Compare two values. +[math.compareNatural(x, y)](functions/compareNatural.md) | Compare two values of any type in a deterministic, natural way. +[math.compareText(x, y)](functions/compareText.md) | Compare two strings lexically. +[math.deepEqual(x, y)](functions/deepEqual.md) | Test element wise whether two matrices are equal. +[math.equal(x, y)](functions/equal.md) | Test whether two values are equal. +[math.equalText(x, y)](functions/equalText.md) | Check equality of two strings. +[math.larger(x, y)](functions/larger.md) | Test whether value x is larger than y. +[math.largerEq(x, y)](functions/largerEq.md) | Test whether value x is larger or equal to y. +[math.smaller(x, y)](functions/smaller.md) | Test whether value x is smaller than y. +[math.smallerEq(x, y)](functions/smallerEq.md) | Test whether value x is smaller or equal to y. +[math.unequal(x, y)](functions/unequal.md) | Test whether two values are unequal. + +## Set functions + +Function | Description +---- | ----------- +[math.setCartesian(set1, set2)](functions/setCartesian.md) | Create the cartesian product of two (multi)sets. +[math.setDifference(set1, set2)](functions/setDifference.md) | Create the difference of two (multi)sets: every element of set1, that is not the element of set2. +[math.setDistinct(set)](functions/setDistinct.md) | Collect the distinct elements of a multiset. +[math.setIntersect(set1, set2)](functions/setIntersect.md) | Create the intersection of two (multi)sets. +[math.setIsSubset(set1, set2)](functions/setIsSubset.md) | Check whether a (multi)set is a subset of another (multi)set. +[math.setMultiplicity(element, set)](functions/setMultiplicity.md) | Count the multiplicity of an element in a multiset. +[math.setPowerset(set)](functions/setPowerset.md) | Create the powerset of a (multi)set. +[math.setSize(set)](functions/setSize.md) | Count the number of elements of a (multi)set. +[math.setSymDifference(set1, set2)](functions/setSymDifference.md) | Create the symmetric difference of two (multi)sets. +[math.setUnion(set1, set2)](functions/setUnion.md) | Create the union of two (multi)sets. + +## Special functions + +Function | Description +---- | ----------- +[math.erf(x)](functions/erf.md) | Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x. + +## Statistics functions + +Function | Description +---- | ----------- +[math.cumsum(a, b, c, ...)](functions/cumsum.md) | Compute the cumulative sum of a matrix or a list with values. +[math.mad(a, b, c, ...)](functions/mad.md) | Compute the median absolute deviation of a matrix or a list with values. +[math.max(a, b, c, ...)](functions/max.md) | Compute the maximum value of a matrix or a list with values. +[math.mean(a, b, c, ...)](functions/mean.md) | Compute the mean value of matrix or a list with values. +[math.median(a, b, c, ...)](functions/median.md) | Compute the median of a matrix or a list with values. +[math.min(a, b, c, ...)](functions/min.md) | Compute the minimum value of a matrix or a list of values. +[math.mode(a, b, c, ...)](functions/mode.md) | Computes the mode of a set of numbers or a list with values(numbers or characters). +[math.prod(a, b, c, ...)](functions/prod.md) | Compute the product of a matrix or a list with values. +[math.quantileSeq(A, prob[, sorted])](functions/quantileSeq.md) | Compute the prob order quantile of a matrix or a list with values. +[math.std(a, b, c, ...)](functions/std.md) | Compute the standard deviation of a matrix or a list with values. +[math.sum(a, b, c, ...)](functions/sum.md) | Compute the sum of a matrix or a list with values. +[math.variance(a, b, c, ...)](functions/variance.md) | Compute the variance of a matrix or a list with values. + +## String functions + +Function | Description +---- | ----------- +[math.bin(value)](functions/bin.md) | Format a number as binary. +[math.format(value [, precision])](functions/format.md) | Format a value of any type into a string. +[math.hex(value)](functions/hex.md) | Format a number as hexadecimal. +[math.oct(value)](functions/oct.md) | Format a number as octal. +[math.print(template, values [, precision])](functions/print.md) | Interpolate values into a string template. + +## Trigonometry functions + +Function | Description +---- | ----------- +[math.acos(x)](functions/acos.md) | Calculate the inverse cosine of a value. +[math.acosh(x)](functions/acosh.md) | Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`. +[math.acot(x)](functions/acot.md) | Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`. +[math.acoth(x)](functions/acoth.md) | Calculate the hyperbolic arccotangent of a value, defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`. +[math.acsc(x)](functions/acsc.md) | Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`. +[math.acsch(x)](functions/acsch.md) | Calculate the hyperbolic arccosecant of a value, defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`. +[math.asec(x)](functions/asec.md) | Calculate the inverse secant of a value. +[math.asech(x)](functions/asech.md) | Calculate the hyperbolic arcsecant of a value, defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`. +[math.asin(x)](functions/asin.md) | Calculate the inverse sine of a value. +[math.asinh(x)](functions/asinh.md) | Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`. +[math.atan(x)](functions/atan.md) | Calculate the inverse tangent of a value. +[math.atan2(y, x)](functions/atan2.md) | Calculate the inverse tangent function with two arguments, y/x. +[math.atanh(x)](functions/atanh.md) | Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`. +[math.cos(x)](functions/cos.md) | Calculate the cosine of a value. +[math.cosh(x)](functions/cosh.md) | Calculate the hyperbolic cosine of a value, defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`. +[math.cot(x)](functions/cot.md) | Calculate the cotangent of a value. +[math.coth(x)](functions/coth.md) | Calculate the hyperbolic cotangent of a value, defined as `coth(x) = 1 / tanh(x)`. +[math.csc(x)](functions/csc.md) | Calculate the cosecant of a value, defined as `csc(x) = 1/sin(x)`. +[math.csch(x)](functions/csch.md) | Calculate the hyperbolic cosecant of a value, defined as `csch(x) = 1 / sinh(x)`. +[math.sec(x)](functions/sec.md) | Calculate the secant of a value, defined as `sec(x) = 1/cos(x)`. +[math.sech(x)](functions/sech.md) | Calculate the hyperbolic secant of a value, defined as `sech(x) = 1 / cosh(x)`. +[math.sin(x)](functions/sin.md) | Calculate the sine of a value. +[math.sinh(x)](functions/sinh.md) | Calculate the hyperbolic sine of a value, defined as `sinh(x) = 1/2 * (exp(x) - exp(-x))`. +[math.tan(x)](functions/tan.md) | Calculate the tangent of a value. +[math.tanh(x)](functions/tanh.md) | Calculate the hyperbolic tangent of a value, defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`. + +## Unit functions + +Function | Description +---- | ----------- +[math.to(x, unit)](functions/to.md) | Change the unit of a value. + +## Utils functions + +Function | Description +---- | ----------- +[math.clone(x)](functions/clone.md) | Clone an object. +[math.hasNumericValue(x)](functions/hasNumericValue.md) | Test whether a value is an numeric value. +[math.isInteger(x)](functions/isInteger.md) | Test whether a value is an integer number. +[math.isNaN(x)](functions/isNaN.md) | Test whether a value is NaN (not a number). +[math.isNegative(x)](functions/isNegative.md) | Test whether a value is negative: smaller than zero. +[math.isNumeric(x)](functions/isNumeric.md) | Test whether a value is an numeric value. +[math.isPositive(x)](functions/isPositive.md) | Test whether a value is positive: larger than zero. +[math.isPrime(x)](functions/isPrime.md) | Test whether a value is prime: has no divisors other than itself and one. +[math.isZero(x)](functions/isZero.md) | Test whether a value is zero. +[math.numeric(x)](functions/numeric.md) | Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction. +[math.typeOf(x)](functions/typeOf.md) | Determine the type of a variable. + + + + diff --git a/node_modules/mathjs/docs/reference/functions/abs.md b/node_modules/mathjs/docs/reference/functions/abs.md new file mode 100644 index 0000000..e0f0440 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/abs.md @@ -0,0 +1,46 @@ + + +# Function abs + +Calculate the absolute value of a number. For matrices, the function is +evaluated element wise. + + +## Syntax + +```js +math.abs(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Array | Matrix | Unit | A number or matrix for which to get the absolute value + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Array | Matrix | Unit | Absolute value of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.abs(3.5) // returns number 3.5 +math.abs(-4.2) // returns number 4.2 + +math.abs([3, -5, -1, 0, 2]) // returns Array [3, 5, 1, 0, 2] +``` + + +## See also + +[sign](sign.md) diff --git a/node_modules/mathjs/docs/reference/functions/acos.md b/node_modules/mathjs/docs/reference/functions/acos.md new file mode 100644 index 0000000..8896040 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/acos.md @@ -0,0 +1,49 @@ + + +# Function acos + +Calculate the inverse cosine of a value. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.acos(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | The arc cosine of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.acos(0.5) // returns number 1.0471975511965979 +math.acos(math.cos(1.5)) // returns number 1.5 + +math.acos(2) // returns Complex 0 + 1.3169578969248166 i +``` + + +## See also + +[cos](cos.md), +[atan](atan.md), +[asin](asin.md) diff --git a/node_modules/mathjs/docs/reference/functions/acosh.md b/node_modules/mathjs/docs/reference/functions/acosh.md new file mode 100644 index 0000000..0c0604b --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/acosh.md @@ -0,0 +1,47 @@ + + +# Function acosh + +Calculate the hyperbolic arccos of a value, +defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.acosh(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Hyperbolic arccosine of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.acosh(1.5) // returns 0.9624236501192069 +``` + + +## See also + +[cosh](cosh.md), +[asinh](asinh.md), +[atanh](atanh.md) diff --git a/node_modules/mathjs/docs/reference/functions/acot.md b/node_modules/mathjs/docs/reference/functions/acot.md new file mode 100644 index 0000000..40f86d8 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/acot.md @@ -0,0 +1,48 @@ + + +# Function acot + +Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.acot(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | The arc cotangent of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.acot(0.5) // returns number 0.4636476090008061 +math.acot(math.cot(1.5)) // returns number 1.5 + +math.acot(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i +``` + + +## See also + +[cot](cot.md), +[atan](atan.md) diff --git a/node_modules/mathjs/docs/reference/functions/acoth.md b/node_modules/mathjs/docs/reference/functions/acoth.md new file mode 100644 index 0000000..6da323f --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/acoth.md @@ -0,0 +1,46 @@ + + +# Function acoth + +Calculate the hyperbolic arccotangent of a value, +defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.acoth(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Hyperbolic arccotangent of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.acoth(0.5) // returns 0.8047189562170503 +``` + + +## See also + +[acsch](acsch.md), +[asech](asech.md) diff --git a/node_modules/mathjs/docs/reference/functions/acsc.md b/node_modules/mathjs/docs/reference/functions/acsc.md new file mode 100644 index 0000000..98a09d1 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/acsc.md @@ -0,0 +1,49 @@ + + +# Function acsc + +Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.acsc(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | The arc cosecant of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.acsc(0.5) // returns number 0.5235987755982989 +math.acsc(math.csc(1.5)) // returns number ~1.5 + +math.acsc(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i +``` + + +## See also + +[csc](csc.md), +[asin](asin.md), +[asec](asec.md) diff --git a/node_modules/mathjs/docs/reference/functions/acsch.md b/node_modules/mathjs/docs/reference/functions/acsch.md new file mode 100644 index 0000000..9735f59 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/acsch.md @@ -0,0 +1,46 @@ + + +# Function acsch + +Calculate the hyperbolic arccosecant of a value, +defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.acsch(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Hyperbolic arccosecant of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.acsch(0.5) // returns 1.4436354751788103 +``` + + +## See also + +[asech](asech.md), +[acoth](acoth.md) diff --git a/node_modules/mathjs/docs/reference/functions/add.md b/node_modules/mathjs/docs/reference/functions/add.md new file mode 100644 index 0000000..051b05c --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/add.md @@ -0,0 +1,59 @@ + + +# Function add + +Add two or more values, `x + y`. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.add(x, y) +math.add(x, y, z, ...) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | First value to add +`y` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Second value to add + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Sum of `x` and `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.add(2, 3) // returns number 5 +math.add(2, 3, 4) // returns number 9 + +const a = math.complex(2, 3) +const b = math.complex(-4, 1) +math.add(a, b) // returns Complex -2 + 4i + +math.add([1, 2, 3], 4) // returns Array [5, 6, 7] + +const c = math.unit('5 cm') +const d = math.unit('2.1 mm') +math.add(c, d) // returns Unit 52.1 mm + +math.add("2.3", "4") // returns number 6.3 +``` + + +## See also + +[subtract](subtract.md), +[sum](sum.md) diff --git a/node_modules/mathjs/docs/reference/functions/and.md b/node_modules/mathjs/docs/reference/functions/and.md new file mode 100644 index 0000000..592b013 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/and.md @@ -0,0 +1,53 @@ + + +# Function and + +Logical `and`. Test whether two values are both defined with a nonzero/nonempty value. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.and(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | First value to check +`y` | number | BigNumber | Complex | Unit | Array | Matrix | Second value to check + +### Returns + +Type | Description +---- | ----------- +boolean | Array | Matrix | Returns true when both inputs are defined with a nonzero/nonempty value. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.and(2, 4) // returns true + +a = [2, 0, 0] +b = [3, 7, 0] +c = 0 + +math.and(a, b) // returns [true, false, false] +math.and(a, c) // returns [false, false, false] +``` + + +## See also + +[not](not.md), +[or](or.md), +[xor](xor.md) diff --git a/node_modules/mathjs/docs/reference/functions/apply.md b/node_modules/mathjs/docs/reference/functions/apply.md new file mode 100644 index 0000000..5914def --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/apply.md @@ -0,0 +1,56 @@ + + +# Function apply + +Apply a function that maps an array to a scalar +along a given axis of a matrix or array. +Returns a new matrix or array with one less dimension than the input. + + +## Syntax + +```js +math.apply(A, dim, callback) +``` + +### Where + +- `dim: number` is a zero-based dimension over which to concatenate the matrices. + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`array` | Array | Matrix | The input Matrix +`dim` | number | The dimension along which the callback is applied +`callback` | Function | The callback function that is applied. This Function should take an array or 1-d matrix as an input and return a number. + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | res The residual matrix with the function applied over some dimension. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const A = [[1, 2], [3, 4]] +const sum = math.sum + +math.apply(A, 0, sum) // returns [4, 6] +math.apply(A, 1, sum) // returns [3, 7] +``` + + +## See also + +[map](map.md), +[filter](filter.md), +[forEach](forEach.md) diff --git a/node_modules/mathjs/docs/reference/functions/arg.md b/node_modules/mathjs/docs/reference/functions/arg.md new file mode 100644 index 0000000..5de1c00 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/arg.md @@ -0,0 +1,53 @@ + + +# Function arg + +Compute the argument of a complex value. +For a complex number `a + bi`, the argument is computed as `atan2(b, a)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.arg(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | A complex number or array with complex numbers + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Array | Matrix | The argument of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const a = math.complex(2, 2) +math.arg(a) / math.pi // returns number 0.25 + +const b = math.complex('2 + 3i') +math.arg(b) // returns number 0.982793723247329 +math.atan2(3, 2) // returns number 0.982793723247329 +``` + + +## See also + +[re](re.md), +[im](im.md), +[conj](conj.md), +[abs](abs.md) diff --git a/node_modules/mathjs/docs/reference/functions/asec.md b/node_modules/mathjs/docs/reference/functions/asec.md new file mode 100644 index 0000000..83f3b74 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/asec.md @@ -0,0 +1,49 @@ + + +# Function asec + +Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.asec(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | The arc secant of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.asec(0.5) // returns 1.0471975511965979 +math.asec(math.sec(1.5)) // returns 1.5 + +math.asec(2) // returns 0 + 1.3169578969248166 i +``` + + +## See also + +[acos](acos.md), +[acot](acot.md), +[acsc](acsc.md) diff --git a/node_modules/mathjs/docs/reference/functions/asech.md b/node_modules/mathjs/docs/reference/functions/asech.md new file mode 100644 index 0000000..0731b68 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/asech.md @@ -0,0 +1,46 @@ + + +# Function asech + +Calculate the hyperbolic arcsecant of a value, +defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.asech(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Hyperbolic arcsecant of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.asech(0.5) // returns 1.3169578969248166 +``` + + +## See also + +[acsch](acsch.md), +[acoth](acoth.md) diff --git a/node_modules/mathjs/docs/reference/functions/asin.md b/node_modules/mathjs/docs/reference/functions/asin.md new file mode 100644 index 0000000..7d39ee8 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/asin.md @@ -0,0 +1,49 @@ + + +# Function asin + +Calculate the inverse sine of a value. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.asin(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | The arc sine of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.asin(0.5) // returns number 0.5235987755982989 +math.asin(math.sin(1.5)) // returns number ~1.5 + +math.asin(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i +``` + + +## See also + +[sin](sin.md), +[atan](atan.md), +[acos](acos.md) diff --git a/node_modules/mathjs/docs/reference/functions/asinh.md b/node_modules/mathjs/docs/reference/functions/asinh.md new file mode 100644 index 0000000..07b06af --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/asinh.md @@ -0,0 +1,46 @@ + + +# Function asinh + +Calculate the hyperbolic arcsine of a value, +defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.asinh(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Hyperbolic arcsine of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.asinh(0.5) // returns 0.48121182505960347 +``` + + +## See also + +[acosh](acosh.md), +[atanh](atanh.md) diff --git a/node_modules/mathjs/docs/reference/functions/atan.md b/node_modules/mathjs/docs/reference/functions/atan.md new file mode 100644 index 0000000..938a79e --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/atan.md @@ -0,0 +1,49 @@ + + +# Function atan + +Calculate the inverse tangent of a value. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.atan(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | The arc tangent of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.atan(0.5) // returns number 0.4636476090008061 +math.atan(math.tan(1.5)) // returns number 1.5 + +math.atan(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i +``` + + +## See also + +[tan](tan.md), +[asin](asin.md), +[acos](acos.md) diff --git a/node_modules/mathjs/docs/reference/functions/atan2.md b/node_modules/mathjs/docs/reference/functions/atan2.md new file mode 100644 index 0000000..923ba42 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/atan2.md @@ -0,0 +1,56 @@ + + +# Function atan2 + +Calculate the inverse tangent function with two arguments, y/x. +By providing two arguments, the right quadrant of the computed angle can be +determined. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.atan2(y, x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`y` | number | Array | Matrix | Second dimension +`x` | number | Array | Matrix | First dimension + +### Returns + +Type | Description +---- | ----------- +number | Array | Matrix | Four-quadrant inverse tangent + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.atan2(2, 2) / math.pi // returns number 0.25 + +const angle = math.unit(60, 'deg') // returns Unit 60 deg +const x = math.cos(angle) +const y = math.sin(angle) + +math.atan(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i +``` + + +## See also + +[tan](tan.md), +[atan](atan.md), +[sin](sin.md), +[cos](cos.md) diff --git a/node_modules/mathjs/docs/reference/functions/atanh.md b/node_modules/mathjs/docs/reference/functions/atanh.md new file mode 100644 index 0000000..6e933c1 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/atanh.md @@ -0,0 +1,46 @@ + + +# Function atanh + +Calculate the hyperbolic arctangent of a value, +defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.atanh(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Hyperbolic arctangent of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.atanh(0.5) // returns 0.5493061443340549 +``` + + +## See also + +[acosh](acosh.md), +[asinh](asinh.md) diff --git a/node_modules/mathjs/docs/reference/functions/bellNumbers.md b/node_modules/mathjs/docs/reference/functions/bellNumbers.md new file mode 100644 index 0000000..d594fde --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/bellNumbers.md @@ -0,0 +1,45 @@ + + +# Function bellNumbers + +The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. +bellNumbers only takes integer arguments. +The following condition must be enforced: n >= 0 + + +## Syntax + +```js +math.bellNumbers(n) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`n` | Number | BigNumber | Total number of objects in the set + +### Returns + +Type | Description +---- | ----------- +Number | BigNumber | B(n) + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.bellNumbers(3) // returns 5 +math.bellNumbers(8) // returns 4140 +``` + + +## See also + +[stirlingS2](stirlingS2.md) diff --git a/node_modules/mathjs/docs/reference/functions/bignumber.md b/node_modules/mathjs/docs/reference/functions/bignumber.md new file mode 100644 index 0000000..ee21838 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/bignumber.md @@ -0,0 +1,47 @@ + + +# Function bignumber + +Create a BigNumber, which can store numbers with arbitrary precision. +When a matrix is provided, all elements will be converted to BigNumber. + + +## Syntax + +```js +math.bignumber(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | number | string | Fraction | BigNumber | Array | Matrix | boolean | null | Value for the big number, 0 by default. + +### Returns + +Type | Description +---- | ----------- +BigNumber | The created bignumber + + +## Examples + +```js +0.1 + 0.2 // returns number 0.30000000000000004 +math.bignumber(0.1) + math.bignumber(0.2) // returns BigNumber 0.3 + + +7.2e500 // returns number Infinity +math.bignumber('7.2e500') // returns BigNumber 7.2e500 +``` + + +## See also + +[boolean](boolean.md), +[complex](complex.md), +[index](index.md), +[matrix](matrix.md), +[string](string.md), +[unit](unit.md) diff --git a/node_modules/mathjs/docs/reference/functions/bin.md b/node_modules/mathjs/docs/reference/functions/bin.md new file mode 100644 index 0000000..37a209f --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/bin.md @@ -0,0 +1,45 @@ + + +# Function bin + +Format a number as binary. + + +## Syntax + +```js +math.bin(value) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | number | Value to be stringified +`wordSize` | number | Optional word size (see `format`) + +### Returns + +Type | Description +---- | ----------- +string | The formatted value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +//the following outputs "0b10" +math.bin(2) +``` + + +## See also + +[oct](oct.md), +[hex](hex.md) diff --git a/node_modules/mathjs/docs/reference/functions/bitAnd.md b/node_modules/mathjs/docs/reference/functions/bitAnd.md new file mode 100644 index 0000000..baab265 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/bitAnd.md @@ -0,0 +1,51 @@ + + +# Function bitAnd + +Bitwise AND two values, `x & y`. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.bitAnd(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Array | Matrix | First value to and +`y` | number | BigNumber | Array | Matrix | Second value to and + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Array | Matrix | AND of `x` and `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.bitAnd(53, 131) // returns number 1 + +math.bitAnd([1, 12, 31], 42) // returns Array [0, 8, 10] +``` + + +## See also + +[bitNot](bitNot.md), +[bitOr](bitOr.md), +[bitXor](bitXor.md), +[leftShift](leftShift.md), +[rightArithShift](rightArithShift.md), +[rightLogShift](rightLogShift.md) diff --git a/node_modules/mathjs/docs/reference/functions/bitNot.md b/node_modules/mathjs/docs/reference/functions/bitNot.md new file mode 100644 index 0000000..abd5eef --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/bitNot.md @@ -0,0 +1,51 @@ + + +# Function bitNot + +Bitwise NOT value, `~x`. +For matrices, the function is evaluated element wise. +For units, the function is evaluated on the best prefix base. + + +## Syntax + +```js +math.bitNot(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Array | Matrix | Value to not + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Array | Matrix | NOT of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.bitNot(1) // returns number -2 + +math.bitNot([2, -3, 4]) // returns Array [-3, 2, 5] +``` + + +## See also + +[bitAnd](bitAnd.md), +[bitOr](bitOr.md), +[bitXor](bitXor.md), +[leftShift](leftShift.md), +[rightArithShift](rightArithShift.md), +[rightLogShift](rightLogShift.md) diff --git a/node_modules/mathjs/docs/reference/functions/bitOr.md b/node_modules/mathjs/docs/reference/functions/bitOr.md new file mode 100644 index 0000000..d71dcd3 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/bitOr.md @@ -0,0 +1,52 @@ + + +# Function bitOr + +Bitwise OR two values, `x | y`. +For matrices, the function is evaluated element wise. +For units, the function is evaluated on the lowest print base. + + +## Syntax + +```js +math.bitOr(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Array | Matrix | First value to or +`y` | number | BigNumber | Array | Matrix | Second value to or + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Array | Matrix | OR of `x` and `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.bitOr(1, 2) // returns number 3 + +math.bitOr([1, 2, 3], 4) // returns Array [5, 6, 7] +``` + + +## See also + +[bitAnd](bitAnd.md), +[bitNot](bitNot.md), +[bitXor](bitXor.md), +[leftShift](leftShift.md), +[rightArithShift](rightArithShift.md), +[rightLogShift](rightLogShift.md) diff --git a/node_modules/mathjs/docs/reference/functions/bitXor.md b/node_modules/mathjs/docs/reference/functions/bitXor.md new file mode 100644 index 0000000..c1465b5 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/bitXor.md @@ -0,0 +1,51 @@ + + +# Function bitXor + +Bitwise XOR two values, `x ^ y`. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.bitXor(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Array | Matrix | First value to xor +`y` | number | BigNumber | Array | Matrix | Second value to xor + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Array | Matrix | XOR of `x` and `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.bitXor(1, 2) // returns number 3 + +math.bitXor([2, 3, 4], 4) // returns Array [6, 7, 0] +``` + + +## See also + +[bitAnd](bitAnd.md), +[bitNot](bitNot.md), +[bitOr](bitOr.md), +[leftShift](leftShift.md), +[rightArithShift](rightArithShift.md), +[rightLogShift](rightLogShift.md) diff --git a/node_modules/mathjs/docs/reference/functions/boolean.md b/node_modules/mathjs/docs/reference/functions/boolean.md new file mode 100644 index 0000000..4d87c59 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/boolean.md @@ -0,0 +1,50 @@ + + +# Function boolean + +Create a boolean or convert a string or number to a boolean. +In case of a number, `true` is returned for non-zero numbers, and `false` in +case of zero. +Strings can be `'true'` or `'false'`, or can contain a number. +When value is a matrix, all elements will be converted to boolean. + + +## Syntax + +```js +math.boolean(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | string | number | boolean | Array | Matrix | null | A value of any type + +### Returns + +Type | Description +---- | ----------- +boolean | Array | Matrix | The boolean value + + +## Examples + +```js +math.boolean(0) // returns false +math.boolean(1) // returns true +math.boolean(-3) // returns true +math.boolean('true') // returns true +math.boolean('false') // returns false +math.boolean([1, 0, 1, 1]) // returns [true, false, true, true] +``` + + +## See also + +[bignumber](bignumber.md), +[complex](complex.md), +[index](index.md), +[matrix](matrix.md), +[string](string.md), +[unit](unit.md) diff --git a/node_modules/mathjs/docs/reference/functions/catalan.md b/node_modules/mathjs/docs/reference/functions/catalan.md new file mode 100644 index 0000000..3517b7d --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/catalan.md @@ -0,0 +1,45 @@ + + +# Function catalan + +The Catalan Numbers enumerate combinatorial structures of many different types. +catalan only takes integer arguments. +The following condition must be enforced: n >= 0 + + +## Syntax + +```js +math.catalan(n) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`n` | Number | BigNumber | nth Catalan number + +### Returns + +Type | Description +---- | ----------- +Number | BigNumber | Cn(n) + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.catalan(3) // returns 5 +math.catalan(8) // returns 1430 +``` + + +## See also + +[bellNumbers](bellNumbers.md) diff --git a/node_modules/mathjs/docs/reference/functions/cbrt.md b/node_modules/mathjs/docs/reference/functions/cbrt.md new file mode 100644 index 0000000..3a9bd40 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/cbrt.md @@ -0,0 +1,60 @@ + + +# Function cbrt + +Calculate the cubic root of a value. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.cbrt(x) +math.cbrt(x, allRoots) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | Value for which to calculate the cubic root. +`allRoots` | boolean | Optional, false by default. Only applicable when `x` is a number or complex number. If true, all complex roots are returned, if false (default) the principal root is returned. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Unit | Array | Matrix | Returns the cubic root of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.cbrt(27) // returns 3 +math.cube(3) // returns 27 +math.cbrt(-64) // returns -4 +math.cbrt(math.unit('27 m^3')) // returns Unit 3 m +math.cbrt([27, 64, 125]) // returns [3, 4, 5] + +const x = math.complex('8i') +math.cbrt(x) // returns Complex 1.7320508075689 + i +math.cbrt(x, true) // returns Matrix [ + // 1.7320508075689 + i + // -1.7320508075689 + i + // -2i + // ] +``` + + +## See also + +[square](square.md), +[sqrt](sqrt.md), +[cube](cube.md) diff --git a/node_modules/mathjs/docs/reference/functions/ceil.md b/node_modules/mathjs/docs/reference/functions/ceil.md new file mode 100644 index 0000000..f8eb6ee --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/ceil.md @@ -0,0 +1,63 @@ + + +# Function ceil + +Round a value towards plus infinity +If `x` is complex, both real and imaginary part are rounded towards plus infinity. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.ceil(x) +math.ceil(x, n) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Array | Matrix | Number to be rounded +`n` | number | BigNumber | Array | Number of decimals Default value: 0. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Array | Matrix | Rounded value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.ceil(3.2) // returns number 4 +math.ceil(3.8) // returns number 4 +math.ceil(-4.2) // returns number -4 +math.ceil(-4.7) // returns number -4 + +math.ceil(3.212, 2) // returns number 3.22 +math.ceil(3.288, 2) // returns number 3.29 +math.ceil(-4.212, 2) // returns number -4.21 +math.ceil(-4.782, 2) // returns number -4.78 + +const c = math.complex(3.24, -2.71) +math.ceil(c) // returns Complex 4 - 2i +math.ceil(c, 1) // returns Complex 3.3 - 2.7i + +math.ceil([3.2, 3.8, -4.7]) // returns Array [4, 4, -4] +math.ceil([3.21, 3.82, -4.71], 1) // returns Array [3.3, 3.9, -4.7] +``` + + +## See also + +[floor](floor.md), +[fix](fix.md), +[round](round.md) diff --git a/node_modules/mathjs/docs/reference/functions/chain.md b/node_modules/mathjs/docs/reference/functions/chain.md new file mode 100644 index 0000000..2feda68 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/chain.md @@ -0,0 +1,54 @@ + + +# Function chain + +Wrap any value in a chain, allowing to perform chained operations on +the value. + +All methods available in the math.js library can be called upon the chain, +and then will be evaluated with the value itself as first argument. +The chain can be closed by executing `chain.done()`, which returns +the final value. + +The chain has a number of special functions: + +- `done()` Finalize the chain and return the chain's value. +- `valueOf()` The same as `done()` +- `toString()` Executes `math.format()` onto the chain's value, returning + a string representation of the value. + + +## Syntax + +```js +math.chain(value) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | * | A value of any type on which to start a chained operation. + +### Returns + +Type | Description +---- | ----------- +math.Chain | The created chain + + +## Examples + +```js +math.chain(3) + .add(4) + .subtract(2) + .done() // 5 + +math.chain( [[1, 2], [3, 4]] ) + .subset(math.index(0, 0), 8) + .multiply(3) + .done() // [[24, 6], [9, 12]] +``` + + diff --git a/node_modules/mathjs/docs/reference/functions/clone.md b/node_modules/mathjs/docs/reference/functions/clone.md new file mode 100644 index 0000000..8d4a0b3 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/clone.md @@ -0,0 +1,43 @@ + + +# Function clone + +Clone an object. Will make a deep copy of the data. + + +## Syntax + +```js +math.clone(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | * | Object to be cloned + +### Returns + +Type | Description +---- | ----------- +* | A clone of object x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.clone(3.5) // returns number 3.5 +math.clone(math.complex('2-4i') // returns Complex 2 - 4i +math.clone(math.unit(45, 'deg')) // returns Unit 45 deg +math.clone([[1, 2], [3, 4]]) // returns Array [[1, 2], [3, 4]] +math.clone("hello world") // returns string "hello world" +``` + + diff --git a/node_modules/mathjs/docs/reference/functions/column.md b/node_modules/mathjs/docs/reference/functions/column.md new file mode 100644 index 0000000..e96d3f5 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/column.md @@ -0,0 +1,45 @@ + + +# Function column + +Return a column from a Matrix. + + +## Syntax + +```js +math.column(value, index) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | Array | Matrix | An array or matrix +`column` | number | The index of the column + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | The retrieved column + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +// get a column +const d = [[1, 2], [3, 4]] +math.column(d, 1) // returns [[2], [4]] +``` + + +## See also + +[row](row.md) diff --git a/node_modules/mathjs/docs/reference/functions/combinations.md b/node_modules/mathjs/docs/reference/functions/combinations.md new file mode 100644 index 0000000..08174f8 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/combinations.md @@ -0,0 +1,49 @@ + + +# Function combinations + +Compute the number of ways of picking `k` unordered outcomes from `n` +possibilities. + +Combinations only takes integer arguments. +The following condition must be enforced: k <= n. + + +## Syntax + +```js +math.combinations(n, k) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`n` | number | BigNumber | Total number of objects in the set +`k` | number | BigNumber | Number of objects in the subset + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Number of possible combinations. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.combinations(7, 5) // returns 21 +``` + + +## See also + +[combinationsWithRep](combinationsWithRep.md), +[permutations](permutations.md), +[factorial](factorial.md) diff --git a/node_modules/mathjs/docs/reference/functions/combinationsWithRep.md b/node_modules/mathjs/docs/reference/functions/combinationsWithRep.md new file mode 100644 index 0000000..13fad3b --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/combinationsWithRep.md @@ -0,0 +1,49 @@ + + +# Function combinationsWithRep + +Compute the number of ways of picking `k` unordered outcomes from `n` +possibilities, allowing individual outcomes to be repeated more than once. + +CombinationsWithRep only takes integer arguments. +The following condition must be enforced: k <= n + k -1. + + +## Syntax + +```js +math.combinationsWithRep(n, k) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`n` | number | BigNumber | Total number of objects in the set +`k` | number | BigNumber | Number of objects in the subset + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Number of possible combinations with replacement. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.combinationsWithRep(7, 5) // returns 462 +``` + + +## See also + +[combinations](combinations.md), +[permutations](permutations.md), +[factorial](factorial.md) diff --git a/node_modules/mathjs/docs/reference/functions/compare.md b/node_modules/mathjs/docs/reference/functions/compare.md new file mode 100644 index 0000000..027928d --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/compare.md @@ -0,0 +1,67 @@ + + +# Function compare + +Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y. + +x and y are considered equal when the relative difference between x and y +is smaller than the configured epsilon. The function cannot be used to +compare values smaller than approximately 2.22e-16. + +For matrices, the function is evaluated element wise. +Strings are compared by their numerical value. + + +## Syntax + +```js +math.compare(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Unit | string | Array | Matrix | First value to compare +`y` | number | BigNumber | Fraction | Unit | string | Array | Matrix | Second value to compare + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Array | Matrix | Returns the result of the comparison: 1 when x > y, -1 when x < y, and 0 when x == y. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.compare(6, 1) // returns 1 +math.compare(2, 3) // returns -1 +math.compare(7, 7) // returns 0 +math.compare('10', '2') // returns 1 +math.compare('1000', '1e3') // returns 0 + +const a = math.unit('5 cm') +const b = math.unit('40 mm') +math.compare(a, b) // returns 1 + +math.compare(2, [1, 2, 3]) // returns [1, 0, -1] +``` + + +## See also + +[equal](equal.md), +[unequal](unequal.md), +[smaller](smaller.md), +[smallerEq](smallerEq.md), +[larger](larger.md), +[largerEq](largerEq.md), +[compareNatural](compareNatural.md), +[compareText](compareText.md) diff --git a/node_modules/mathjs/docs/reference/functions/compareNatural.md b/node_modules/mathjs/docs/reference/functions/compareNatural.md new file mode 100644 index 0000000..cd26c43 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/compareNatural.md @@ -0,0 +1,92 @@ + + +# Function compareNatural + +Compare two values of any type in a deterministic, natural way. + +For numeric values, the function works the same as `math.compare`. +For types of values that can't be compared mathematically, +the function compares in a natural way. + +For numeric values, x and y are considered equal when the relative +difference between x and y is smaller than the configured epsilon. +The function cannot be used to compare values smaller than +approximately 2.22e-16. + +For Complex numbers, first the real parts are compared. If equal, +the imaginary parts are compared. + +Strings are compared with a natural sorting algorithm, which +orders strings in a "logic" way following some heuristics. +This differs from the function `compare`, which converts the string +into a numeric value and compares that. The function `compareText` +on the other hand compares text lexically. + +Arrays and Matrices are compared value by value until there is an +unequal pair of values encountered. Objects are compared by sorted +keys until the keys or their values are unequal. + + +## Syntax + +```js +math.compareNatural(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | * | First value to compare +`y` | * | Second value to compare + +### Returns + +Type | Description +---- | ----------- +number | Returns the result of the comparison: 1 when x > y, -1 when x < y, and 0 when x == y. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.compareNatural(6, 1) // returns 1 +math.compareNatural(2, 3) // returns -1 +math.compareNatural(7, 7) // returns 0 + +math.compareNatural('10', '2') // returns 1 +math.compareText('10', '2') // returns -1 +math.compare('10', '2') // returns 1 + +math.compareNatural('Answer: 10', 'Answer: 2') // returns 1 +math.compareText('Answer: 10', 'Answer: 2') // returns -1 +math.compare('Answer: 10', 'Answer: 2') + // Error: Cannot convert "Answer: 10" to a number + +const a = math.unit('5 cm') +const b = math.unit('40 mm') +math.compareNatural(a, b) // returns 1 + +const c = math.complex('2 + 3i') +const d = math.complex('2 + 4i') +math.compareNatural(c, d) // returns -1 + +math.compareNatural([1, 2, 4], [1, 2, 3]) // returns 1 +math.compareNatural([1, 2, 3], [1, 2]) // returns 1 +math.compareNatural([1, 5], [1, 2, 3]) // returns 1 +math.compareNatural([1, 2], [1, 2]) // returns 0 + +math.compareNatural({a: 2}, {a: 4}) // returns -1 +``` + + +## See also + +[compare](compare.md), +[compareText](compareText.md) diff --git a/node_modules/mathjs/docs/reference/functions/compareText.md b/node_modules/mathjs/docs/reference/functions/compareText.md new file mode 100644 index 0000000..8d54ff0 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/compareText.md @@ -0,0 +1,54 @@ + + +# Function compareText + +Compare two strings lexically. Comparison is case sensitive. +Returns 1 when x > y, -1 when x < y, and 0 when x == y. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.compareText(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | string | Array | DenseMatrix | First string to compare +`y` | string | Array | DenseMatrix | Second string to compare + +### Returns + +Type | Description +---- | ----------- +number | Array | DenseMatrix | Returns the result of the comparison: 1 when x > y, -1 when x < y, and 0 when x == y. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.compareText('B', 'A') // returns 1 +math.compareText('2', '10') // returns 1 +math.compare('2', '10') // returns -1 +math.compareNatural('2', '10') // returns -1 + +math.compareText('B', ['A', 'B', 'C']) // returns [1, 0, -1] +``` + + +## See also + +[equal](equal.md), +[equalText](equalText.md), +[compare](compare.md), +[compareNatural](compareNatural.md) diff --git a/node_modules/mathjs/docs/reference/functions/compile.md b/node_modules/mathjs/docs/reference/functions/compile.md new file mode 100644 index 0000000..e3dbf84 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/compile.md @@ -0,0 +1,56 @@ + + +# Function compile + +Parse and compile an expression. +Returns a an object with a function `evaluate([scope])` to evaluate the +compiled expression. + + +## Syntax + +```js +math.compile(expr) // returns one node +math.compile([expr1, expr2, expr3, ...]) // returns an array with nodes +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`expr` | string | string[] | Array | Matrix | The expression to be compiled + +### Returns + +Type | Description +---- | ----------- +{evaluate: Function} | Array.<{evaluate: Function}> | code An object with the compiled expression + + +### Throws + +Type | Description +---- | ----------- +Error | + +## Examples + +```js +const code1 = math.compile('sqrt(3^2 + 4^2)') +code1.evaluate() // 5 + +let scope = {a: 3, b: 4} +const code2 = math.compile('a * b') // 12 +code2.evaluate(scope) // 12 +scope.a = 5 +code2.evaluate(scope) // 20 + +const nodes = math.compile(['a = 3', 'b = 4', 'a * b']) +nodes[2].evaluate() // 12 +``` + + +## See also + +[parse](parse.md), +[evaluate](evaluate.md) diff --git a/node_modules/mathjs/docs/reference/functions/complex.md b/node_modules/mathjs/docs/reference/functions/complex.md new file mode 100644 index 0000000..ee28aa9 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/complex.md @@ -0,0 +1,17 @@ + + +# Function complex + + + + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`arr` | number[][] | the matrix to find eigenvalues of +`N` | number | size of the matrix +`prec` | number | BigNumber | precision, anything lower will be considered zero +`type` | 'number' | 'BigNumber' | 'Complex' | +`findVectors` | boolean | should we find eigenvectors? + diff --git a/node_modules/mathjs/docs/reference/functions/composition.md b/node_modules/mathjs/docs/reference/functions/composition.md new file mode 100644 index 0000000..33f81f8 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/composition.md @@ -0,0 +1,46 @@ + + +# Function composition + +The composition counts of n into k parts. + +composition only takes integer arguments. +The following condition must be enforced: k <= n. + + +## Syntax + +```js +math.composition(n, k) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`n` | Number | BigNumber | Total number of objects in the set +`k` | Number | BigNumber | Number of objects in the subset + +### Returns + +Type | Description +---- | ----------- +Number | BigNumber | Returns the composition counts of n into k parts. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.composition(5, 3) // returns 6 +``` + + +## See also + +[combinations](combinations.md) diff --git a/node_modules/mathjs/docs/reference/functions/concat.md b/node_modules/mathjs/docs/reference/functions/concat.md new file mode 100644 index 0000000..0b90d85 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/concat.md @@ -0,0 +1,56 @@ + + +# Function concat + +Concatenate two or more matrices. + + +## Syntax + +```js +math.concat(A, B, C, ...) +math.concat(A, B, C, ..., dim) +``` + +### Where + +- `dim: number` is a zero-based dimension over which to concatenate the matrices. + By default the last dimension of the matrices. + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... Array | Matrix | Two or more matrices + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | Concatenated matrix + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const A = [[1, 2], [5, 6]] +const B = [[3, 4], [7, 8]] + +math.concat(A, B) // returns [[1, 2, 3, 4], [5, 6, 7, 8]] +math.concat(A, B, 0) // returns [[1, 2], [5, 6], [3, 4], [7, 8]] +math.concat('hello', ' ', 'world') // returns 'hello world' +``` + + +## See also + +[size](size.md), +[squeeze](squeeze.md), +[subset](subset.md), +[transpose](transpose.md) diff --git a/node_modules/mathjs/docs/reference/functions/config.md b/node_modules/mathjs/docs/reference/functions/config.md new file mode 100644 index 0000000..236115e --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/config.md @@ -0,0 +1,44 @@ + + +# Function config + +Set configuration options for math.js, and get current options. +Will emit a 'config' event, with arguments (curr, prev, changes). + +This function is only available on a mathjs instance created using `create`. + + +## Syntax + +```js +math.config(config: Object): Object +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`options` | Object | Available options: {number} epsilon Minimum relative difference between two compared values, used by all comparison functions. {string} matrix A string 'Matrix' (default) or 'Array'. {string} number A string 'number' (default), 'BigNumber', or 'Fraction' {number} precision The number of significant digits for BigNumbers. Not applicable for Numbers. {string} parenthesis How to display parentheses in LaTeX and string output. {string} randomSeed Random seed for seeded pseudo random number generator. Set to null to randomly seed. + +### Returns + +Type | Description +---- | ----------- +Object | Returns the current configuration + + +## Examples + +```js +import { create, all } from 'mathjs' + +// create a mathjs instance +const math = create(all) + +math.config().number // outputs 'number' +math.evaluate('0.4') // outputs number 0.4 +math.config({number: 'Fraction'}) +math.evaluate('0.4') // outputs Fraction 2/5 +``` + + diff --git a/node_modules/mathjs/docs/reference/functions/conj.md b/node_modules/mathjs/docs/reference/functions/conj.md new file mode 100644 index 0000000..aa874a2 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/conj.md @@ -0,0 +1,50 @@ + + +# Function conj + +Compute the complex conjugate of a complex value. +If `x = a+bi`, the complex conjugate of `x` is `a - bi`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.conj(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | A complex number or array with complex numbers + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | The complex conjugate of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.conj(math.complex('2 + 3i')) // returns Complex 2 - 3i +math.conj(math.complex('2 - 3i')) // returns Complex 2 + 3i +math.conj(math.complex('-5.2i')) // returns Complex 5.2i +``` + + +## See also + +[re](re.md), +[im](im.md), +[arg](arg.md), +[abs](abs.md) diff --git a/node_modules/mathjs/docs/reference/functions/cos.md b/node_modules/mathjs/docs/reference/functions/cos.md new file mode 100644 index 0000000..f6df69e --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/cos.md @@ -0,0 +1,51 @@ + + +# Function cos + +Calculate the cosine of a value. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.cos(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Cosine of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.cos(2) // returns number -0.4161468365471422 +math.cos(math.pi / 4) // returns number 0.7071067811865475 +math.cos(math.unit(180, 'deg')) // returns number -1 +math.cos(math.unit(60, 'deg')) // returns number 0.5 + +const angle = 0.2 +math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2) // returns number ~1 +``` + + +## See also + +[cos](cos.md), +[tan](tan.md) diff --git a/node_modules/mathjs/docs/reference/functions/cosh.md b/node_modules/mathjs/docs/reference/functions/cosh.md new file mode 100644 index 0000000..6cb014b --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/cosh.md @@ -0,0 +1,46 @@ + + +# Function cosh + +Calculate the hyperbolic cosine of a value, +defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.cosh(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Hyperbolic cosine of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.cosh(0.5) // returns number 1.1276259652063807 +``` + + +## See also + +[sinh](sinh.md), +[tanh](tanh.md) diff --git a/node_modules/mathjs/docs/reference/functions/cot.md b/node_modules/mathjs/docs/reference/functions/cot.md new file mode 100644 index 0000000..0f4bb81 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/cot.md @@ -0,0 +1,47 @@ + + +# Function cot + +Calculate the cotangent of a value. Defined as `cot(x) = 1 / tan(x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.cot(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Cotangent of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.cot(2) // returns number -0.45765755436028577 +1 / math.tan(2) // returns number -0.45765755436028577 +``` + + +## See also + +[tan](tan.md), +[sec](sec.md), +[csc](csc.md) diff --git a/node_modules/mathjs/docs/reference/functions/coth.md b/node_modules/mathjs/docs/reference/functions/coth.md new file mode 100644 index 0000000..2f73056 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/coth.md @@ -0,0 +1,49 @@ + + +# Function coth + +Calculate the hyperbolic cotangent of a value, +defined as `coth(x) = 1 / tanh(x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.coth(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Hyperbolic cotangent of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +// coth(x) = 1 / tanh(x) +math.coth(2) // returns 1.0373147207275482 +1 / math.tanh(2) // returns 1.0373147207275482 +``` + + +## See also + +[sinh](sinh.md), +[tanh](tanh.md), +[cosh](cosh.md) diff --git a/node_modules/mathjs/docs/reference/functions/count.md b/node_modules/mathjs/docs/reference/functions/count.md new file mode 100644 index 0000000..86078c0 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/count.md @@ -0,0 +1,45 @@ + + +# Function count + +Count the number of elements of a matrix, array or string. + + +## Syntax + +```js +math.count(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | string | Array | Matrix | A matrix or string + +### Returns + +Type | Description +---- | ----------- +number | An integer with the elements in `x`. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.count('hello world') // returns 11 +const A = [[1, 2, 3], [4, 5, 6]] +math.count(A) // returns 6 +math.count(math.range(1,6)) // returns 5 +``` + + +## See also + +[size](size.md) diff --git a/node_modules/mathjs/docs/reference/functions/createUnit.md b/node_modules/mathjs/docs/reference/functions/createUnit.md new file mode 100644 index 0000000..1c8e2a9 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/createUnit.md @@ -0,0 +1,52 @@ + + +# Function createUnit + +Create a user-defined unit and register it with the Unit type. + + +## Syntax + +```js +math.createUnit({ + baseUnit1: { + aliases: [string, ...] + prefixes: object + }, + unit2: { + definition: string, + aliases: [string, ...] + prefixes: object, + offset: number + }, + unit3: string // Shortcut +}) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`name` | string | The name of the new unit. Must be unique. Example: 'knot' +`definition` | string, Unit | Definition of the unit in terms of existing units. For example, '0.514444444 m / s'. +`options` | Object | (optional) An object containing any of the following properties:
    - `prefixes {string}` "none", "short", "long", "binary_short", or "binary_long". The default is "none".
    - `aliases {Array}` Array of strings. Example: ['knots', 'kt', 'kts']
    - `offset {Numeric}` An offset to apply when converting from the unit. For example, the offset for celsius is 273.15. Default is 0. + +### Returns + +Type | Description +---- | ----------- +Unit | The new unit + + +## Examples + +```js +math.createUnit('foo') +math.createUnit('knot', {definition: '0.514444444 m/s', aliases: ['knots', 'kt', 'kts']}) +math.createUnit('mph', '1 mile/hour') +``` + + +## See also + +[unit](unit.md) diff --git a/node_modules/mathjs/docs/reference/functions/cross.md b/node_modules/mathjs/docs/reference/functions/cross.md new file mode 100644 index 0000000..4822da0 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/cross.md @@ -0,0 +1,58 @@ + + +# Function cross + +Calculate the cross product for two vectors in three dimensional space. +The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined +as: + + cross(A, B) = [ + a2 * b3 - a3 * b2, + a3 * b1 - a1 * b3, + a1 * b2 - a2 * b1 + ] + +If one of the input vectors has a dimension greater than 1, the output +vector will be a 1x3 (2-dimensional) matrix. + + +## Syntax + +```js +math.cross(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Array | Matrix | First vector +`y` | Array | Matrix | Second vector + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | Returns the cross product of `x` and `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.cross([1, 1, 0], [0, 1, 1]) // Returns [1, -1, 1] +math.cross([3, -3, 1], [4, 9, 2]) // Returns [-15, -2, 39] +math.cross([2, 3, 4], [5, 6, 7]) // Returns [-3, 6, -3] +math.cross([[1, 2, 3]], [[4], [5], [6]]) // Returns [[-3, 6, -3]] +``` + + +## See also + +[dot](dot.md), +[multiply](multiply.md) diff --git a/node_modules/mathjs/docs/reference/functions/csc.md b/node_modules/mathjs/docs/reference/functions/csc.md new file mode 100644 index 0000000..507c6c1 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/csc.md @@ -0,0 +1,47 @@ + + +# Function csc + +Calculate the cosecant of a value, defined as `csc(x) = 1/sin(x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.csc(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Cosecant of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.csc(2) // returns number 1.099750170294617 +1 / math.sin(2) // returns number 1.099750170294617 +``` + + +## See also + +[sin](sin.md), +[sec](sec.md), +[cot](cot.md) diff --git a/node_modules/mathjs/docs/reference/functions/csch.md b/node_modules/mathjs/docs/reference/functions/csch.md new file mode 100644 index 0000000..18a89c3 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/csch.md @@ -0,0 +1,49 @@ + + +# Function csch + +Calculate the hyperbolic cosecant of a value, +defined as `csch(x) = 1 / sinh(x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.csch(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Hyperbolic cosecant of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +// csch(x) = 1/ sinh(x) +math.csch(0.5) // returns 1.9190347513349437 +1 / math.sinh(0.5) // returns 1.9190347513349437 +``` + + +## See also + +[sinh](sinh.md), +[sech](sech.md), +[coth](coth.md) diff --git a/node_modules/mathjs/docs/reference/functions/ctranspose.md b/node_modules/mathjs/docs/reference/functions/ctranspose.md new file mode 100644 index 0000000..ac9c94e --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/ctranspose.md @@ -0,0 +1,50 @@ + + +# Function ctranspose + +Transpose and complex conjugate a matrix. All values of the matrix are +reflected over its main diagonal and then the complex conjugate is +taken. This is equivalent to complex conjugation for scalars and +vectors. + + +## Syntax + +```js +math.ctranspose(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Array | Matrix | Matrix to be ctransposed + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | The ctransposed matrix + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const A = [[1, 2, 3], [4, 5, math.complex(6,7)]] +math.ctranspose(A) // returns [[1, 4], [2, 5], [3, {re:6,im:7}]] +``` + + +## See also + +[transpose](transpose.md), +[diag](diag.md), +[inv](inv.md), +[subset](subset.md), +[squeeze](squeeze.md) diff --git a/node_modules/mathjs/docs/reference/functions/cube.md b/node_modules/mathjs/docs/reference/functions/cube.md new file mode 100644 index 0000000..883310c --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/cube.md @@ -0,0 +1,51 @@ + + +# Function cube + +Compute the cube of a value, `x * x * x`. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.cube(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Array | Matrix | Unit | Number for which to calculate the cube + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Array | Matrix | Unit | Cube of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.cube(2) // returns number 8 +math.pow(2, 3) // returns number 8 +math.cube(4) // returns number 64 +4 * 4 * 4 // returns number 64 + +math.cube([1, 2, 3, 4]) // returns Array [1, 8, 27, 64] +``` + + +## See also + +[multiply](multiply.md), +[square](square.md), +[pow](pow.md), +[cbrt](cbrt.md) diff --git a/node_modules/mathjs/docs/reference/functions/cumsum.md b/node_modules/mathjs/docs/reference/functions/cumsum.md new file mode 100644 index 0000000..aca34ef --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/cumsum.md @@ -0,0 +1,57 @@ + + +# Function cumsum + +Compute the cumulative sum of a matrix or a list with values. +In case of a (multi dimensional) array or matrix, the cumulative sums +along a specified dimension (defaulting to the first) will be calculated. + + +## Syntax + +```js +math.cumsum(a, b, c, ...) +math.cumsum(A) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... * | A single matrix or or multiple scalar values + +### Returns + +Type | Description +---- | ----------- +* | The cumulative sum of all values + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.cumsum(2, 1, 4, 3) // returns [2, 3, 7, 10] +math.cumsum([2, 1, 4, 3]) // returns [2, 3, 7, 10] +math.cumsum([[1, 2], [3, 4]]) // returns [[1, 2], [4, 6]] +math.cumsum([[1, 2], [3, 4]], 0) // returns [[1, 2], [4, 6]] +math.cumsum([[1, 2], [3, 4]], 1) // returns [[1, 3], [3, 7]] +math.cumsum([[2, 5], [4, 3], [1, 7]]) // returns [[2, 5], [6, 8], [7, 15]] +``` + + +## See also + +[mean](mean.md), +[median](median.md), +[min](min.md), +[max](max.md), +[prod](prod.md), +[std](std.md), +[variance](variance.md), +[sum](sum.md) diff --git a/node_modules/mathjs/docs/reference/functions/deepEqual.md b/node_modules/mathjs/docs/reference/functions/deepEqual.md new file mode 100644 index 0000000..47b33b2 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/deepEqual.md @@ -0,0 +1,53 @@ + + +# Function deepEqual + +Test element wise whether two matrices are equal. +The function accepts both matrices and scalar values. + +Strings are compared by their numerical value. + + +## Syntax + +```js +math.deepEqual(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | First matrix to compare +`y` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Second matrix to compare + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Returns true when the input matrices have the same size and each of their elements is equal. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.deepEqual(2, 4) // returns false + +a = [2, 5, 1] +b = [2, 7, 1] + +math.deepEqual(a, b) // returns false +math.equal(a, b) // returns [true, false, true] +``` + + +## See also + +[equal](equal.md), +[unequal](unequal.md) diff --git a/node_modules/mathjs/docs/reference/functions/derivative.md b/node_modules/mathjs/docs/reference/functions/derivative.md new file mode 100644 index 0000000..1c84f69 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/derivative.md @@ -0,0 +1,61 @@ + + +# Function derivative + +Takes the derivative of an expression expressed in parser Nodes. +The derivative will be taken over the supplied variable in the +second parameter. If there are multiple variables in the expression, +it will return a partial derivative. + +This uses rules of differentiation which can be found here: + +- [Differentiation rules (Wikipedia)](https://en.wikipedia.org/wiki/Differentiation_rules) + + +## Syntax + +```js +derivative(expr, variable) +derivative(expr, variable, options) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`expr` | Node | string | The expression to differentiate +`variable` | SymbolNode | string | The variable over which to differentiate +`options` | {simplify: boolean} | There is one option available, `simplify`, which is true by default. When false, output will not be simplified. + +### Returns + +Type | Description +---- | ----------- +ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode | The derivative of `expr` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.derivative('x^2', 'x') // Node {2 * x} +math.derivative('x^2', 'x', {simplify: false}) // Node {2 * 1 * x ^ (2 - 1) +math.derivative('sin(2x)', 'x')) // Node {2 * cos(2 * x)} +math.derivative('2*x', 'x').evaluate() // number 2 +math.derivative('x^2', 'x').evaluate({x: 4}) // number 8 +const f = math.parse('x^2') +const x = math.parse('x') +math.derivative(f, x) // Node {2 * x} +``` + + +## See also + +[simplify](simplify.md), +[parse](parse.md), +[evaluate](evaluate.md) diff --git a/node_modules/mathjs/docs/reference/functions/det.md b/node_modules/mathjs/docs/reference/functions/det.md new file mode 100644 index 0000000..44f269a --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/det.md @@ -0,0 +1,49 @@ + + +# Function det + +Calculate the determinant of a matrix. + + +## Syntax + +```js +math.det(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Array | Matrix | A matrix + +### Returns + +Type | Description +---- | ----------- +number | The determinant of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.det([[1, 2], [3, 4]]) // returns -2 + +const A = [ + [-2, 2, 3], + [-1, 1, 3], + [2, 0, -1] +] +math.det(A) // returns 6 +``` + + +## See also + +[inv](inv.md) diff --git a/node_modules/mathjs/docs/reference/functions/diag.md b/node_modules/mathjs/docs/reference/functions/diag.md new file mode 100644 index 0000000..52a67ce --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/diag.md @@ -0,0 +1,61 @@ + + +# Function diag + +Create a diagonal matrix or retrieve the diagonal of a matrix + +When `x` is a vector, a matrix with vector `x` on the diagonal will be returned. +When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector. +When k is positive, the values are placed on the super diagonal. +When k is negative, the values are placed on the sub diagonal. + + +## Syntax + +```js +math.diag(X) +math.diag(X, format) +math.diag(X, k) +math.diag(X, k, format) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Matrix | Array | A two dimensional matrix or a vector +`k` | number | BigNumber | The diagonal where the vector will be filled in or retrieved. Default value: 0. +`format` | string | The matrix storage format. Default value: 'dense'. + +### Returns + +Type | Description +---- | ----------- +Matrix | Array | Diagonal matrix from input vector, or diagonal from input matrix. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js + // create a diagonal matrix + math.diag([1, 2, 3]) // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]] + math.diag([1, 2, 3], 1) // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]] + math.diag([1, 2, 3], -1) // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]] + +// retrieve the diagonal from a matrix +const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +math.diag(a) // returns [1, 5, 9] +``` + + +## See also + +[ones](ones.md), +[zeros](zeros.md), +[identity](identity.md) diff --git a/node_modules/mathjs/docs/reference/functions/diff.md b/node_modules/mathjs/docs/reference/functions/diff.md new file mode 100644 index 0000000..69f1338 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/diff.md @@ -0,0 +1,70 @@ + + +# Function diff + +Create a new matrix or array of the difference between elements of the given array +The optional dim parameter lets you specify the dimension to evaluate the difference of +If no dimension parameter is passed it is assumed as dimension 0 + +Dimension is zero-based in javascript and one-based in the parser and can be a number or bignumber +Arrays must be 'rectangular' meaning arrays like [1, 2] +If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays + + +## Syntax + +```js +math.diff(arr) +math.diff(arr, dim) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`arr` | Array | Matrix | An array or matrix +`dim` | number | Dimension + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | Difference between array elements in given dimension + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const arr = [1, 2, 4, 7, 0] +math.diff(arr) // returns [1, 2, 3, -7] (no dimension passed so 0 is assumed) +math.diff(math.matrix(arr)) // returns math.matrix([1, 2, 3, -7]) + +const arr = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [9, 8, 7, 6, 4]] +math.diff(arr) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]] +math.diff(arr, 0) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]] +math.diff(arr, 1) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]] +math.diff(arr, math.bignumber(1)) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]] + +math.diff(arr, 2) // throws RangeError as arr is 2 dimensional not 3 +math.diff(arr, -1) // throws RangeError as negative dimensions are not allowed + +// These will all produce the same result +math.diff([[1, 2], [3, 4]]) +math.diff([math.matrix([1, 2]), math.matrix([3, 4])]) +math.diff([[1, 2], math.matrix([3, 4])]) +math.diff([math.matrix([1, 2]), [3, 4]]) +// They do not produce the same result as math.diff(math.matrix([[1, 2], [3, 4]])) as this returns a matrix +``` + + +## See also + +[sum](sum.md), +[subtract](subtract.md), +[partitionSelect](partitionSelect.md) diff --git a/node_modules/mathjs/docs/reference/functions/distance.md b/node_modules/mathjs/docs/reference/functions/distance.md new file mode 100644 index 0000000..d69dfe8 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/distance.md @@ -0,0 +1,80 @@ + + +# Function distance + +Calculates: + The eucledian distance between two points in N-dimensional spaces. + Distance between point and a line in 2 and 3 dimensional spaces. + Pairwise distance between a set of 2D or 3D points +NOTE: + When substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c + For parametric equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c) + + +## Syntax + +```js +math.distance([x1, y1], [x2, y2]) + math.distance({pointOneX: 4, pointOneY: 5}, {pointTwoX: 2, pointTwoY: 7}) +math.distance([x1, y1, z1], [x2, y2, z2]) +math.distance({pointOneX: 4, pointOneY: 5, pointOneZ: 8}, {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9}) +math.distance([x1, y1, ... , N1], [x2, y2, ... , N2]) +math.distance([[A], [B], [C]...]) +math.distance([x1, y1], [LinePtX1, LinePtY1], [LinePtX2, LinePtY2]) +math.distance({pointX: 1, pointY: 4}, {lineOnePtX: 6, lineOnePtY: 3}, {lineTwoPtX: 2, lineTwoPtY: 8}) +math.distance([x1, y1, z1], [LinePtX1, LinePtY1, LinePtZ1], [LinePtX2, LinePtY2, LinePtZ2]) +math.distance({pointX: 1, pointY: 4, pointZ: 7}, {lineOnePtX: 6, lineOnePtY: 3, lineOnePtZ: 4}, {lineTwoPtX: 2, lineTwoPtY: 8, lineTwoPtZ: 5}) +math.distance([x1, y1], [xCoeffLine, yCoeffLine, constant]) +math.distance({pointX: 10, pointY: 10}, {xCoeffLine: 8, yCoeffLine: 1, constant: 3}) +math.distance([x1, y1, z1], [x0, y0, z0, a-tCoeff, b-tCoeff, c-tCoeff]) point and parametric equation of 3D line +math.distance([x, y, z], [x0, y0, z0, a, b, c]) +math.distance({pointX: 2, pointY: 5, pointZ: 9}, {x0: 4, y0: 6, z0: 3, a: 4, b: 2, c: 0}) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Array | Matrix | Object | Co-ordinates of first point +`y` | Array | Matrix | Object | Co-ordinates of second point + +### Returns + +Type | Description +---- | ----------- +Number | BigNumber | Returns the distance from two/three points + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.distance([0,0], [4,4]) // Returns 5.6569 +math.distance( + {pointOneX: 0, pointOneY: 0}, + {pointTwoX: 10, pointTwoY: 10}) // Returns 14.142135623730951 +math.distance([1, 0, 1], [4, -2, 2]) // Returns 3.74166 +math.distance( + {pointOneX: 4, pointOneY: 5, pointOneZ: 8}, + {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9}) // Returns 3 +math.distance([1, 0, 1, 0], [0, -1, 0, -1]) // Returns 2 +math.distance([[1, 2], [1, 2], [1, 3]]) // Returns [0, 1, 1] +math.distance([[1,2,4], [1,2,6], [8,1,3]]) // Returns [2, 7.14142842854285, 7.681145747868608] +math.distance([10, 10], [8, 1, 3]) // Returns 11.535230316796387 +math.distance([10, 10], [2, 3], [-8, 0]) // Returns 8.759953130362847 +math.distance( + {pointX: 1, pointY: 4}, + {lineOnePtX: 6, lineOnePtY: 3}, + {lineTwoPtX: 2, lineTwoPtY: 8}) // Returns 2.720549372624744 +math.distance([2, 3, 1], [1, 1, 2, 5, 0, 1]) // Returns 2.3204774044612857 +math.distance( + {pointX: 2, pointY: 3, pointZ: 1}, + {x0: 1, y0: 1, z0: 2, a: 5, b: 0, c: 1} // Returns 2.3204774044612857 +``` + + diff --git a/node_modules/mathjs/docs/reference/functions/divide.md b/node_modules/mathjs/docs/reference/functions/divide.md new file mode 100644 index 0000000..836c9d1 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/divide.md @@ -0,0 +1,55 @@ + + +# Function divide + +Divide two values, `x / y`. +To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`. + + +## Syntax + +```js +math.divide(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Numerator +`y` | number | BigNumber | Fraction | Complex | Array | Matrix | Denominator + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Quotient, `x / y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.divide(2, 3) // returns number 0.6666666666666666 + +const a = math.complex(5, 14) +const b = math.complex(4, 1) +math.divide(a, b) // returns Complex 2 + 3i + +const c = [[7, -6], [13, -4]] +const d = [[1, 2], [4, 3]] +math.divide(c, d) // returns Array [[-9, 4], [-11, 6]] + +const e = math.unit('18 km') +math.divide(e, 4.5) // returns Unit 4 km +``` + + +## See also + +[multiply](multiply.md) diff --git a/node_modules/mathjs/docs/reference/functions/dot.md b/node_modules/mathjs/docs/reference/functions/dot.md new file mode 100644 index 0000000..4a7c96a --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/dot.md @@ -0,0 +1,48 @@ + + +# Function dot + +Calculate the dot product of two vectors. The dot product of +`A = [a1, a2, ..., an]` and `B = [b1, b2, ..., bn]` is defined as: + + dot(A, B) = conj(a1) * b1 + conj(a2) * b2 + ... + conj(an) * bn + + +## Syntax + +```js +math.dot(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Array | Matrix | First vector +`y` | Array | Matrix | Second vector + +### Returns + +Type | Description +---- | ----------- +number | Returns the dot product of `x` and `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.dot([2, 4, 1], [2, 2, 3]) // returns number 15 +math.multiply([2, 4, 1], [2, 2, 3]) // returns number 15 +``` + + +## See also + +[multiply](multiply.md), +[cross](cross.md) diff --git a/node_modules/mathjs/docs/reference/functions/dotDivide.md b/node_modules/mathjs/docs/reference/functions/dotDivide.md new file mode 100644 index 0000000..d250bbd --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/dotDivide.md @@ -0,0 +1,52 @@ + + +# Function dotDivide + +Divide two matrices element wise. The function accepts both matrices and +scalar values. + + +## Syntax + +```js +math.dotDivide(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Numerator +`y` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Denominator + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Quotient, `x ./ y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.dotDivide(2, 4) // returns 0.5 + +a = [[9, 5], [6, 1]] +b = [[3, 2], [5, 2]] + +math.dotDivide(a, b) // returns [[3, 2.5], [1.2, 0.5]] +math.divide(a, b) // returns [[1.75, 0.75], [-1.75, 2.25]] +``` + + +## See also + +[divide](divide.md), +[multiply](multiply.md), +[dotMultiply](dotMultiply.md) diff --git a/node_modules/mathjs/docs/reference/functions/dotMultiply.md b/node_modules/mathjs/docs/reference/functions/dotMultiply.md new file mode 100644 index 0000000..2d99eaa --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/dotMultiply.md @@ -0,0 +1,52 @@ + + +# Function dotMultiply + +Multiply two matrices element wise. The function accepts both matrices and +scalar values. + + +## Syntax + +```js +math.dotMultiply(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Left hand value +`y` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Right hand value + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Multiplication of `x` and `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.dotMultiply(2, 4) // returns 8 + +a = [[9, 5], [6, 1]] +b = [[3, 2], [5, 2]] + +math.dotMultiply(a, b) // returns [[27, 10], [30, 2]] +math.multiply(a, b) // returns [[52, 28], [23, 14]] +``` + + +## See also + +[multiply](multiply.md), +[divide](divide.md), +[dotDivide](dotDivide.md) diff --git a/node_modules/mathjs/docs/reference/functions/dotPow.md b/node_modules/mathjs/docs/reference/functions/dotPow.md new file mode 100644 index 0000000..7447649 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/dotPow.md @@ -0,0 +1,49 @@ + + +# Function dotPow + +Calculates the power of x to y element wise. + + +## Syntax + +```js +math.dotPow(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | The base +`y` | number | BigNumber | Complex | Unit | Array | Matrix | The exponent + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Unit | Array | Matrix | The value of `x` to the power `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.dotPow(2, 3) // returns number 8 + +const a = [[1, 2], [4, 3]] +math.dotPow(a, 2) // returns Array [[1, 4], [16, 9]] +math.pow(a, 2) // returns Array [[9, 8], [16, 17]] +``` + + +## See also + +[pow](pow.md), +[sqrt](sqrt.md), +[multiply](multiply.md) diff --git a/node_modules/mathjs/docs/reference/functions/eigs.md b/node_modules/mathjs/docs/reference/functions/eigs.md new file mode 100644 index 0000000..12882e8 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/eigs.md @@ -0,0 +1,54 @@ + + +# Function eigs + +Compute eigenvalues and eigenvectors of a matrix. The eigenvalues are sorted by their absolute value, ascending. +An eigenvalue with multiplicity k will be listed k times. The eigenvectors are returned as columns of a matrix – +the eigenvector that belongs to the j-th eigenvalue in the list (eg. `values[j]`) is the j-th column (eg. `column(vectors, j)`). +If the algorithm fails to converge, it will throw an error – in that case, however, you may still find useful information +in `err.values` and `err.vectors`. + + +## Syntax + +```js +math.eigs(x, [prec]) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Array | Matrix | Matrix to be diagonalized +`prec` | number | BigNumber | Precision, default value: 1e-15 + +### Returns + +Type | Description +---- | ----------- +{values: Array | Matrix, vectors: Array | Matrix} | Object containing an array of eigenvalues and a matrix with eigenvectors as columns. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const { eigs, multiply, column, transpose } = math +const H = [[5, 2.3], [2.3, 1]] +const ans = eigs(H) // returns {values: [E1,E2...sorted], vectors: [v1,v2.... corresponding vectors as columns]} +const E = ans.values +const U = ans.vectors +multiply(H, column(U, 0)) // returns multiply(E[0], column(U, 0)) +const UTxHxU = multiply(transpose(U), H, U) // diagonalizes H +E[0] == UTxHxU[0][0] // returns true +``` + + +## See also + +[inv](inv.md) diff --git a/node_modules/mathjs/docs/reference/functions/equal.md b/node_modules/mathjs/docs/reference/functions/equal.md new file mode 100644 index 0000000..ecff69f --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/equal.md @@ -0,0 +1,75 @@ + + +# Function equal + +Test whether two values are equal. + +The function tests whether the relative difference between x and y is +smaller than the configured epsilon. The function cannot be used to +compare values smaller than approximately 2.22e-16. + +For matrices, the function is evaluated element wise. +In case of complex numbers, x.re must equal y.re, and x.im must equal y.im. + +Values `null` and `undefined` are compared strictly, thus `null` is only +equal to `null` and nothing else, and `undefined` is only equal to +`undefined` and nothing else. Strings are compared by their numerical value. + + +## Syntax + +```js +math.equal(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | boolean | Complex | Unit | string | Array | Matrix | First value to compare +`y` | number | BigNumber | boolean | Complex | Unit | string | Array | Matrix | Second value to compare + +### Returns + +Type | Description +---- | ----------- +boolean | Array | Matrix | Returns true when the compared values are equal, else returns false + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.equal(2 + 2, 3) // returns false +math.equal(2 + 2, 4) // returns true + +const a = math.unit('50 cm') +const b = math.unit('5 m') +math.equal(a, b) // returns true + +const c = [2, 5, 1] +const d = [2, 7, 1] + +math.equal(c, d) // returns [true, false, true] +math.deepEqual(c, d) // returns false + +math.equal("1000", "1e3") // returns true +math.equal(0, null) // returns false +``` + + +## See also + +[unequal](unequal.md), +[smaller](smaller.md), +[smallerEq](smallerEq.md), +[larger](larger.md), +[largerEq](largerEq.md), +[compare](compare.md), +[deepEqual](deepEqual.md), +[equalText](equalText.md) diff --git a/node_modules/mathjs/docs/reference/functions/equalText.md b/node_modules/mathjs/docs/reference/functions/equalText.md new file mode 100644 index 0000000..b708755 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/equalText.md @@ -0,0 +1,53 @@ + + +# Function equalText + +Check equality of two strings. Comparison is case sensitive. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.equalText(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | string | Array | DenseMatrix | First string to compare +`y` | string | Array | DenseMatrix | Second string to compare + +### Returns + +Type | Description +---- | ----------- +number | Array | DenseMatrix | Returns true if the values are equal, and false if not. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.equalText('Hello', 'Hello') // returns true +math.equalText('a', 'A') // returns false +math.equal('2e3', '2000') // returns true +math.equalText('2e3', '2000') // returns false + +math.equalText('B', ['A', 'B', 'C']) // returns [false, true, false] +``` + + +## See also + +[equal](equal.md), +[compareText](compareText.md), +[compare](compare.md), +[compareNatural](compareNatural.md) diff --git a/node_modules/mathjs/docs/reference/functions/erf.md b/node_modules/mathjs/docs/reference/functions/erf.md new file mode 100644 index 0000000..8a5b6bc --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/erf.md @@ -0,0 +1,49 @@ + + +# Function erf + +Compute the erf function of a value using a rational Chebyshev +approximations for different intervals of x. + +This is a translation of W. J. Cody's Fortran implementation from 1987 +( https://www.netlib.org/specfun/erf ). See the AMS publication +"Rational Chebyshev Approximations for the Error Function" by W. J. Cody +for an explanation of this process. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.erf(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Array | Matrix | A real number + +### Returns + +Type | Description +---- | ----------- +number | Array | Matrix | The erf of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.erf(0.2) // returns 0.22270258921047847 +math.erf(-0.5) // returns -0.5204998778130465 +math.erf(4) // returns 0.9999999845827421 +``` + + diff --git a/node_modules/mathjs/docs/reference/functions/evaluate.md b/node_modules/mathjs/docs/reference/functions/evaluate.md new file mode 100644 index 0000000..dd16bb1 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/evaluate.md @@ -0,0 +1,56 @@ + + +# Function evaluate + +Evaluate an expression. + +Note the evaluating arbitrary expressions may involve security risks, +see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information. + + +## Syntax + +```js +math.evaluate(expr) +math.evaluate(expr, scope) +math.evaluate([expr1, expr2, expr3, ...]) +math.evaluate([expr1, expr2, expr3, ...], scope) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`expr` | string | string[] | Matrix | The expression to be evaluated +`scope` | Object | Scope to read/write variables + +### Returns + +Type | Description +---- | ----------- +* | The result of the expression + + +### Throws + +Type | Description +---- | ----------- +Error | + +## Examples + +```js +math.evaluate('(2+3)/4') // 1.25 +math.evaluate('sqrt(3^2 + 4^2)') // 5 +math.evaluate('sqrt(-4)') // 2i +math.evaluate(['a=3', 'b=4', 'a*b']) // [3, 4, 12] + +let scope = {a:3, b:4} +math.evaluate('a * b', scope) // 12 +``` + + +## See also + +[parse](parse.md), +[compile](compile.md) diff --git a/node_modules/mathjs/docs/reference/functions/exp.md b/node_modules/mathjs/docs/reference/functions/exp.md new file mode 100644 index 0000000..d8d2f6f --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/exp.md @@ -0,0 +1,54 @@ + + +# Function exp + +Calculate the exponent of a value. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.exp(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | A number or matrix to exponentiate + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Exponent of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.exp(2) // returns number 7.3890560989306495 +math.pow(math.e, 2) // returns number 7.3890560989306495 +math.log(math.exp(2)) // returns number 2 + +math.exp([1, 2, 3]) +// returns Array [ +// 2.718281828459045, +// 7.3890560989306495, +// 20.085536923187668 +// ] +``` + + +## See also + +[expm1](expm1.md), +[log](log.md), +[pow](pow.md) diff --git a/node_modules/mathjs/docs/reference/functions/expm.md b/node_modules/mathjs/docs/reference/functions/expm.md new file mode 100644 index 0000000..9e9558b --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/expm.md @@ -0,0 +1,49 @@ + + +# Function expm + +Compute the matrix exponential, expm(A) = e^A. The matrix must be square. +Not to be confused with exp(a), which performs element-wise +exponentiation. + +The exponential is calculated using the Padé approximant with scaling and +squaring; see "Nineteen Dubious Ways to Compute the Exponential of a +Matrix," by Moler and Van Loan. + + +## Syntax + +```js +math.expm(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Matrix | A square Matrix + +### Returns + +Type | Description +---- | ----------- +Matrix | The exponential of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const A = [[0,2],[0,0]] +math.expm(A) // returns [[1,2],[0,1]] +``` + + +## See also + +[exp](exp.md) diff --git a/node_modules/mathjs/docs/reference/functions/expm1.md b/node_modules/mathjs/docs/reference/functions/expm1.md new file mode 100644 index 0000000..ddf7e6f --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/expm1.md @@ -0,0 +1,54 @@ + + +# Function expm1 + +Calculate the value of subtracting 1 from the exponential value. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.expm1(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | A number or matrix to apply expm1 + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Exponent of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.expm1(2) // returns number 6.38905609893065 +math.pow(math.e, 2) - 1 // returns number 6.3890560989306495 +math.log(math.expm1(2) + 1) // returns number 2 + +math.expm1([1, 2, 3]) +// returns Array [ +// 1.718281828459045, +// 6.3890560989306495, +// 19.085536923187668 +// ] +``` + + +## See also + +[exp](exp.md), +[log](log.md), +[pow](pow.md) diff --git a/node_modules/mathjs/docs/reference/functions/factorial.md b/node_modules/mathjs/docs/reference/functions/factorial.md new file mode 100644 index 0000000..5cdfdf9 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/factorial.md @@ -0,0 +1,49 @@ + + +# Function factorial + +Compute the factorial of a value + +Factorial only supports an integer value as argument. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.factorial(n) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`n` | number | BigNumber | Array | Matrix | An integer number + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Array | Matrix | The factorial of `n` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.factorial(5) // returns 120 +math.factorial(3) // returns 6 +``` + + +## See also + +[combinations](combinations.md), +[combinationsWithRep](combinationsWithRep.md), +[gamma](gamma.md), +[permutations](permutations.md) diff --git a/node_modules/mathjs/docs/reference/functions/filter.md b/node_modules/mathjs/docs/reference/functions/filter.md new file mode 100644 index 0000000..d584a2b --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/filter.md @@ -0,0 +1,50 @@ + + +# Function filter + +Filter the items in an array or one dimensional matrix. + + +## Syntax + +```js +math.filter(x, test) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Matrix | Array | A one dimensional matrix or array to filter +`test` | Function | RegExp | A function or regular expression to test items. All entries for which `test` returns true are returned. When `test` is a function, it is invoked with three parameters: the value of the element, the index of the element, and the matrix/array being traversed. The function must return a boolean. + +### Returns + +Type | Description +---- | ----------- +Matrix | Array | Returns the filtered matrix. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +function isPositive (x) { + return x > 0 +} +math.filter([6, -2, -1, 4, 3], isPositive) // returns [6, 4, 3] + +math.filter(["23", "foo", "100", "55", "bar"], /[0-9]+/) // returns ["23", "100", "55"] +``` + + +## See also + +[forEach](forEach.md), +[map](map.md), +[sort](sort.md) diff --git a/node_modules/mathjs/docs/reference/functions/fix.md b/node_modules/mathjs/docs/reference/functions/fix.md new file mode 100644 index 0000000..59c487d --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/fix.md @@ -0,0 +1,61 @@ + + +# Function fix + +Round a value towards zero. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.fix(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Array | Matrix | Number to be rounded +`n` | number | BigNumber | Array | Number of decimals Default value: 0. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Array | Matrix | Rounded value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.fix(3.2) // returns number 3 +math.fix(3.8) // returns number 3 +math.fix(-4.2) // returns number -4 +math.fix(-4.7) // returns number -4 + +math.fix(3.12, 1) // returns number 3.1 +math.fix(3.18, 1) // returns number 3.1 +math.fix(-4.12, 1) // returns number -4.1 +math.fix(-4.17, 1) // returns number -4.1 + +const c = math.complex(3.22, -2.78) +math.fix(c) // returns Complex 3 - 2i +math.fix(c, 1) // returns Complex 3.2 - 2.7i + +math.fix([3.2, 3.8, -4.7]) // returns Array [3, 3, -4] +math.fix([3.2, 3.8, -4.7], 1) // returns Array [3.2, 3.8, -4.7] +``` + + +## See also + +[ceil](ceil.md), +[floor](floor.md), +[round](round.md) diff --git a/node_modules/mathjs/docs/reference/functions/flatten.md b/node_modules/mathjs/docs/reference/functions/flatten.md new file mode 100644 index 0000000..46f59a7 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/flatten.md @@ -0,0 +1,46 @@ + + +# Function flatten + +Flatten a multi dimensional matrix into a single dimensional matrix. +It is guaranteed to always return a clone of the argument. + + +## Syntax + +```js +math.flatten(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Matrix | Array | Matrix to be flattened + +### Returns + +Type | Description +---- | ----------- +Matrix | Array | Returns the flattened matrix + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.flatten([[1,2], [3,4]]) // returns [1, 2, 3, 4] +``` + + +## See also + +[concat](concat.md), +[resize](resize.md), +[size](size.md), +[squeeze](squeeze.md) diff --git a/node_modules/mathjs/docs/reference/functions/floor.md b/node_modules/mathjs/docs/reference/functions/floor.md new file mode 100644 index 0000000..4b23594 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/floor.md @@ -0,0 +1,62 @@ + + +# Function floor + +Round a value towards minus infinity. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.floor(x) +math.floor(x, n) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Array | Matrix | Number to be rounded +`n` | number | BigNumber | Array | Number of decimals Default value: 0. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Array | Matrix | Rounded value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.floor(3.2) // returns number 3 +math.floor(3.8) // returns number 3 +math.floor(-4.2) // returns number -5 +math.floor(-4.7) // returns number -5 + +math.floor(3.212, 2) // returns number 3.21 +math.floor(3.288, 2) // returns number 3.28 +math.floor(-4.212, 2) // returns number -4.22 +math.floor(-4.782, 2) // returns number -4.79 + +const c = math.complex(3.24, -2.71) +math.floor(c) // returns Complex 3 - 3i +math.floor(c, 1) // returns Complex 3.2 - 2.8i + +math.floor([3.2, 3.8, -4.7]) // returns Array [3, 3, -5] +math.floor([3.21, 3.82, -4.71], 1) // returns Array [3.2, 3.8, -4.8] +``` + + +## See also + +[ceil](ceil.md), +[fix](fix.md), +[round](round.md) diff --git a/node_modules/mathjs/docs/reference/functions/forEach.md b/node_modules/mathjs/docs/reference/functions/forEach.md new file mode 100644 index 0000000..315ac4f --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/forEach.md @@ -0,0 +1,41 @@ + + +# Function forEach + +Iterate over all elements of a matrix/array, and executes the given callback function. + + +## Syntax + +```js +math.forEach(x, callback) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Matrix | Array | The matrix to iterate on. +`callback` | Function | The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix/array being traversed. + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.forEach([1, 2, 3], function(value) { + console.log(value) +}) +// outputs 1, 2, 3 +``` + + +## See also + +[filter](filter.md), +[map](map.md), +[sort](sort.md) diff --git a/node_modules/mathjs/docs/reference/functions/format.md b/node_modules/mathjs/docs/reference/functions/format.md new file mode 100644 index 0000000..7d0dfea --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/format.md @@ -0,0 +1,127 @@ + + +# Function format + +Format a value of any type into a string. + + +## Syntax + +```js +math.format(value) +math.format(value, options) +math.format(value, precision) +math.format(value, callback) +``` + +### Where + + - `value: *` + The value to be formatted + - `options: Object` + An object with formatting options. Available options: + - `notation: string` + Number notation. Choose from: + - 'fixed' + Always use regular number notation. + For example '123.40' and '14000000' + - 'exponential' + Always use exponential notation. + For example '1.234e+2' and '1.4e+7' + - 'engineering' + Always use engineering notation: always have exponential notation, + and select the exponent to be a multiple of 3. + For example '123.4e+0' and '14.0e+6' + - 'auto' (default) + Regular number notation for numbers having an absolute value between + `lower` and `upper` bounds, and uses exponential notation elsewhere. + Lower bound is included, upper bound is excluded. + For example '123.4' and '1.4e7'. + - 'bin', 'oct, or 'hex' + Format the number using binary, octal, or hexadecimal notation. + For example '0b1101' and '0x10fe'. + - `wordSize: number` + The word size in bits to use for formatting in binary, octal, or + hexadecimal notation. To be used only with 'bin', 'oct', or 'hex' + values for 'notation' option. When this option is defined the value + is formatted as a signed twos complement integer of the given word + size and the size suffix is appended to the output. + For example format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'. + Default value is undefined. + - `precision: number` + Limit the number of digits of the formatted value. + For regular numbers, must be a number between 0 and 16. + For bignumbers, the maximum depends on the configured precision, + see function `config()`. + In case of notations 'exponential', 'engineering', and 'auto', `precision` + defines the total number of significant digits returned. + In case of notation 'fixed', `precision` defines the number of + significant digits after the decimal point. + `precision` is undefined by default. + - `lowerExp: number` + Exponent determining the lower boundary for formatting a value with + an exponent when `notation='auto`. Default value is `-3`. + - `upperExp: number` + Exponent determining the upper boundary for formatting a value with + an exponent when `notation='auto`. Default value is `5`. + - `fraction: string`. Available values: 'ratio' (default) or 'decimal'. + For example `format(fraction(1, 3))` will output '1/3' when 'ratio' is + configured, and will output `0.(3)` when 'decimal' is configured. + - `truncate: number`. Specifies the maximum allowed length of the + returned string. If it would have been longer, the excess characters + are deleted and replaced with `'...'`. +- `callback: function` + A custom formatting function, invoked for all numeric elements in `value`, + for example all elements of a matrix, or the real and imaginary + parts of a complex number. This callback can be used to override the + built-in numeric notation with any type of formatting. Function `callback` + is called with `value` as parameter and must return a string. + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | * | Value to be stringified +`options` | Object | Function | number | Formatting options + +### Returns + +Type | Description +---- | ----------- +string | The formatted value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.format(6.4) // returns '6.4' +math.format(1240000) // returns '1.24e6' +math.format(1/3) // returns '0.3333333333333333' +math.format(1/3, 3) // returns '0.333' +math.format(21385, 2) // returns '21000' +math.format(12e8, {notation: 'fixed'}) // returns '1200000000' +math.format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000' +math.format(52.8, {notation: 'exponential'}) // returns '5.28e+1' +math.format(12400,{notation: 'engineering'}) // returns '12.400e+3' +math.format(2000, {lowerExp: -2, upperExp: 2}) // returns '2e+3' + +function formatCurrency(value) { + // return currency notation with two digits: + return '$' + value.toFixed(2) + + // you could also use math.format inside the callback: + // return '$' + math.format(value, {notation: 'fixed', precision: 2}) +} +math.format([2.1, 3, 0.016], formatCurrency) // returns '[$2.10, $3.00, $0.02]' +``` + + +## See also + +[print](print.md) diff --git a/node_modules/mathjs/docs/reference/functions/fraction.md b/node_modules/mathjs/docs/reference/functions/fraction.md new file mode 100644 index 0000000..fd7b108 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/fraction.md @@ -0,0 +1,45 @@ + + +# Function fraction + +Create a fraction convert a value to a fraction. + + +## Syntax + +```js +math.fraction(numerator, denominator) +math.fraction({n: numerator, d: denominator}) +math.fraction(matrix: Array | Matrix) Turn all matrix entries + into fractions +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | number | string | Fraction | BigNumber | Array | Matrix | Arguments specifying the numerator and denominator of the fraction + +### Returns + +Type | Description +---- | ----------- +Fraction | Array | Matrix | Returns a fraction + + +## Examples + +```js +math.fraction(1, 3) +math.fraction('2/3') +math.fraction({n: 2, d: 3}) +math.fraction([0.2, 0.25, 1.25]) +``` + + +## See also + +[bignumber](bignumber.md), +[number](number.md), +[string](string.md), +[unit](unit.md) diff --git a/node_modules/mathjs/docs/reference/functions/gamma.md b/node_modules/mathjs/docs/reference/functions/gamma.md new file mode 100644 index 0000000..07d2b07 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/gamma.md @@ -0,0 +1,49 @@ + + +# Function gamma + +Compute the gamma function of a value using Lanczos approximation for +small values, and an extended Stirling approximation for large values. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.gamma(n) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`n` | number | Array | Matrix | A real or complex number + +### Returns + +Type | Description +---- | ----------- +number | Array | Matrix | The gamma of `n` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.gamma(5) // returns 24 +math.gamma(-0.5) // returns -3.5449077018110335 +math.gamma(math.i) // returns -0.15494982830180973 - 0.49801566811835596i +``` + + +## See also + +[combinations](combinations.md), +[factorial](factorial.md), +[permutations](permutations.md) diff --git a/node_modules/mathjs/docs/reference/functions/gcd.md b/node_modules/mathjs/docs/reference/functions/gcd.md new file mode 100644 index 0000000..5778a9b --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/gcd.md @@ -0,0 +1,50 @@ + + +# Function gcd + +Calculate the greatest common divisor for two or more values or arrays. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.gcd(a, b) +math.gcd(a, b, c, ...) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... number | BigNumber | Fraction | Array | Matrix | Two or more integer numbers + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Array | Matrix | The greatest common divisor + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.gcd(8, 12) // returns 4 +math.gcd(-4, 6) // returns 2 +math.gcd(25, 15, -10) // returns 5 + +math.gcd([8, -4], [12, 6]) // returns [4, 2] +``` + + +## See also + +[lcm](lcm.md), +[xgcd](xgcd.md) diff --git a/node_modules/mathjs/docs/reference/functions/getMatrixDataType.md b/node_modules/mathjs/docs/reference/functions/getMatrixDataType.md new file mode 100644 index 0000000..f3944b8 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/getMatrixDataType.md @@ -0,0 +1,59 @@ + + +# Function getMatrixDataType + +Find the data type of all elements in a matrix or array, +for example 'number' if all items are a number and 'Complex' if all values +are complex numbers. +If a matrix contains more than one data type, it will return 'mixed'. + + +## Syntax + +```js +math.getMatrixDataType(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | ...Matrix | Array | The Matrix with values. + +### Returns + +Type | Description +---- | ----------- +string | A string representation of the matrix type + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const x = [ [1, 2, 3], [4, 5, 6] ] +const mixedX = [ [1, true], [2, 3] ] +const fractionX = [ [math.fraction(1, 3)], [math.fraction(1, 3] ] +const unitX = [ [math.unit('5cm')], [math.unit('5cm')] ] +const bigNumberX = [ [math.bignumber(1)], [math.bignumber(0)] ] +const sparse = math.sparse(x) +const dense = math.matrix(x) +math.getMatrixDataType(x) // returns 'number' +math.getMatrixDataType(sparse) // returns 'number' +math.getMatrixDataType(dense) // returns 'number' +math.getMatrixDataType(mixedX) // returns 'mixed' +math.getMatrixDataType(fractionX) // returns 'Fraction' +math.getMatrixDataType(unitX) // returns 'Unit' +math.getMatrixDataType(bigNumberX) // return 'BigNumber' +``` + + +## See also + +[SparseMatrix](SparseMatrix.md), +[DenseMatrix](DenseMatrix.md) diff --git a/node_modules/mathjs/docs/reference/functions/hasNumericValue.md b/node_modules/mathjs/docs/reference/functions/hasNumericValue.md new file mode 100644 index 0000000..d15f3ac --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/hasNumericValue.md @@ -0,0 +1,55 @@ + + +# Function hasNumericValue + +Test whether a value is an numeric value. + +In case of a string, true is returned if the string contains a numeric value. + + +## Syntax + +```js +math.hasNumericValue(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | * | Value to be tested + +### Returns + +Type | Description +---- | ----------- +boolean | Returns true when `x` is a `number`, `BigNumber`, `Fraction`, `Boolean`, or a `String` containing number. Returns false for other types. Throws an error in case of unknown types. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.hasNumericValue(2) // returns true +math.hasNumericValue('2') // returns true +math.isNumeric('2') // returns false +math.hasNumericValue(0) // returns true +math.hasNumericValue(math.bignumber(500)) // returns true +math.hasNumericValue(math.fraction(4)) // returns true +math.hasNumericValue(math.complex('2-4i') // returns false +math.hasNumericValue([2.3, 'foo', false]) // returns [true, false, true] +``` + + +## See also + +[isZero](isZero.md), +[isPositive](isPositive.md), +[isNegative](isNegative.md), +[isInteger](isInteger.md), +[isNumeric](isNumeric.md) diff --git a/node_modules/mathjs/docs/reference/functions/help.md b/node_modules/mathjs/docs/reference/functions/help.md new file mode 100644 index 0000000..d71e968 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/help.md @@ -0,0 +1,42 @@ + + +# Function help + +Retrieve help on a function or data type. +Help files are retrieved from the embedded documentation in math.docs. + + +## Syntax + +```js +math.help(search) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`search` | Function | string | Object | A function or function name for which to get help + +### Returns + +Type | Description +---- | ----------- +Help | A help object + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +console.log(math.help('sin').toString()) +console.log(math.help(math.add).toString()) +console.log(math.help(math.add).toJSON()) +``` + + diff --git a/node_modules/mathjs/docs/reference/functions/hex.md b/node_modules/mathjs/docs/reference/functions/hex.md new file mode 100644 index 0000000..8d2146c --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/hex.md @@ -0,0 +1,45 @@ + + +# Function hex + +Format a number as hexadecimal. + + +## Syntax + +```js +math.hex(value) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | number | Value to be stringified +`wordSize` | number | Optional word size (see `format`) + +### Returns + +Type | Description +---- | ----------- +string | The formatted value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +//the following outputs "0xF0" +math.hex(240) +``` + + +## See also + +[oct](oct.md), +[bin](bin.md) diff --git a/node_modules/mathjs/docs/reference/functions/hypot.md b/node_modules/mathjs/docs/reference/functions/hypot.md new file mode 100644 index 0000000..d7c6e54 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/hypot.md @@ -0,0 +1,51 @@ + + +# Function hypot + +Calculate the hypotenusa of a list with values. The hypotenusa is defined as: + + hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) + +For matrix input, the hypotenusa is calculated for all values in the matrix. + + +## Syntax + +```js +math.hypot(a, b, ...) +math.hypot([a, b, c, ...]) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... number | BigNumber | Array | Matrix | A list with numeric values or an Array or Matrix. Matrix and Array input is flattened and returns a single number for the whole matrix. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Returns the hypothenusa of the input values. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.hypot(3, 4) // 5 +math.hypot(3, 4, 5) // 7.0710678118654755 +math.hypot([3, 4, 5]) // 7.0710678118654755 +math.hypot(-2) // 2 +``` + + +## See also + +[abs](abs.md), +[norm](norm.md) diff --git a/node_modules/mathjs/docs/reference/functions/identity.md b/node_modules/mathjs/docs/reference/functions/identity.md new file mode 100644 index 0000000..e3a6321 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/identity.md @@ -0,0 +1,57 @@ + + +# Function identity + +Create a 2-dimensional identity matrix with size m x n or n x n. +The matrix has ones on the diagonal and zeros elsewhere. + + +## Syntax + +```js +math.identity(n) +math.identity(n, format) +math.identity(m, n) +math.identity(m, n, format) +math.identity([m, n]) +math.identity([m, n], format) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`size` | ...number | Matrix | Array | The size for the matrix +`format` | string | The Matrix storage format + +### Returns + +Type | Description +---- | ----------- +Matrix | Array | number | A matrix with ones on the diagonal. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.identity(3) // returns [[1, 0, 0], [0, 1, 0], [0, 0, 1]] +math.identity(3, 2) // returns [[1, 0], [0, 1], [0, 0]] + +const A = [[1, 2, 3], [4, 5, 6]] +math.identity(math.size(A)) // returns [[1, 0, 0], [0, 1, 0]] +``` + + +## See also + +[diag](diag.md), +[ones](ones.md), +[zeros](zeros.md), +[size](size.md), +[range](range.md) diff --git a/node_modules/mathjs/docs/reference/functions/im.md b/node_modules/mathjs/docs/reference/functions/im.md new file mode 100644 index 0000000..1e606f3 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/im.md @@ -0,0 +1,53 @@ + + +# Function im + +Get the imaginary part of a complex number. +For a complex number `a + bi`, the function returns `b`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.im(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | A complex number or array with complex numbers + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Array | Matrix | The imaginary part of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const a = math.complex(2, 3) +math.re(a) // returns number 2 +math.im(a) // returns number 3 + +math.re(math.complex('-5.2i')) // returns number -5.2 +math.re(math.complex(2.4)) // returns number 0 +``` + + +## See also + +[re](re.md), +[conj](conj.md), +[abs](abs.md), +[arg](arg.md) diff --git a/node_modules/mathjs/docs/reference/functions/import.md b/node_modules/mathjs/docs/reference/functions/import.md new file mode 100644 index 0000000..5788652 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/import.md @@ -0,0 +1,68 @@ + + +# Function import + +Import functions from an object or a module. + +This function is only available on a mathjs instance created using `create`. + + +## Syntax + +```js +math.import(functions) +math.import(functions, options) +``` + +### Where + +- `functions: Object` + An object with functions or factories to be imported. +- `options: Object` An object with import options. Available options: + - `override: boolean` + If true, existing functions will be overwritten. False by default. + - `silent: boolean` + If true, the function will not throw errors on duplicates or invalid + types. False by default. + - `wrap: boolean` + If true, the functions will be wrapped in a wrapper function + which converts data types like Matrix to primitive data types like Array. + The wrapper is needed when extending math.js with libraries which do not + support these data type. False by default. + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`functions` | Object | Array | Object with functions to be imported. +`options` | Object | Import options. + +## Examples + +```js +import { create, all } from 'mathjs' +import * as numbers from 'numbers' + +// create a mathjs instance +const math = create(all) + +// define new functions and variables +math.import({ + myvalue: 42, + hello: function (name) { + return 'hello, ' + name + '!' + } +}) + +// use the imported function and variable +math.myvalue * 2 // 84 +math.hello('user') // 'hello, user!' + +// import the npm module 'numbers' +// (must be installed first with `npm install numbers`) +math.import(numbers, {wrap: true}) + +math.fibonacci(7) // returns 13 +``` + + diff --git a/node_modules/mathjs/docs/reference/functions/index.md b/node_modules/mathjs/docs/reference/functions/index.md new file mode 100644 index 0000000..533feca --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/index.md @@ -0,0 +1,55 @@ + + +# Function index + +Create an index. An Index can store ranges having start, step, and end +for multiple dimensions. +Matrix.get, Matrix.set, and math.subset accept an Index as input. + + +## Syntax + +```js +math.index(range1, range2, ...) +``` + +### Where + +- A number +- A string for getting/setting an object property +- An instance of `Range` +- A one-dimensional Array or a Matrix with numbers + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`ranges` | ...* | Zero or more ranges or numbers. + +### Returns + +Type | Description +---- | ----------- +Index | Returns the created index + + +## Examples + +```js +const b = [1, 2, 3, 4, 5] +math.subset(b, math.index([1, 2, 3])) // returns [2, 3, 4] + +const a = math.matrix([[1, 2], [3, 4]]) +a.subset(math.index(0, 1)) // returns 2 +``` + + +## See also + +[bignumber](bignumber.md), +[boolean](boolean.md), +[complex](complex.md), +[matrix](matrix.md), +[number](number.md), +[string](string.md), +[unit](unit.md) diff --git a/node_modules/mathjs/docs/reference/functions/intersect.md b/node_modules/mathjs/docs/reference/functions/intersect.md new file mode 100644 index 0000000..839c16c --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/intersect.md @@ -0,0 +1,50 @@ + + +# Function intersect + +Calculates the point of intersection of two lines in two or three dimensions +and of a line and a plane in three dimensions. The inputs are in the form of +arrays or 1 dimensional matrices. The line intersection functions return null +if the lines do not meet. + +Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`. + + +## Syntax + +```js +math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2) +math.intersect(endPoint1, endPoint2, planeCoefficients) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`w` | Array | Matrix | Co-ordinates of first end-point of first line +`x` | Array | Matrix | Co-ordinates of second end-point of first line +`y` | Array | Matrix | Co-ordinates of first end-point of second line OR Co-efficients of the plane's equation +`z` | Array | Matrix | Co-ordinates of second end-point of second line OR undefined if the calculation is for line and plane + +### Returns + +Type | Description +---- | ----------- +Array | Returns the point of intersection of lines/lines-planes + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5] +math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0] +math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3] +``` + + diff --git a/node_modules/mathjs/docs/reference/functions/inv.md b/node_modules/mathjs/docs/reference/functions/inv.md new file mode 100644 index 0000000..5fc36cb --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/inv.md @@ -0,0 +1,45 @@ + + +# Function inv + +Calculate the inverse of a square matrix. + + +## Syntax + +```js +math.inv(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Array | Matrix | Matrix to be inversed + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | The inverse of `x`. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.inv([[1, 2], [3, 4]]) // returns [[-2, 1], [1.5, -0.5]] +math.inv(4) // returns 0.25 +1 / 4 // returns 0.25 +``` + + +## See also + +[det](det.md), +[transpose](transpose.md) diff --git a/node_modules/mathjs/docs/reference/functions/invmod.md b/node_modules/mathjs/docs/reference/functions/invmod.md new file mode 100644 index 0000000..825f9a0 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/invmod.md @@ -0,0 +1,47 @@ + + +# Function invmod + +Calculate the (modular) multiplicative inverse of a modulo b. Solution to the equation `ax ≣ 1 (mod b)` +See https://en.wikipedia.org/wiki/Modular_multiplicative_inverse. + + +## Syntax + +```js +math.invmod(a, b) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a` | number | BigNumber | An integer number +`b` | number | BigNumber | An integer number + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Returns an integer number where `invmod(a,b)*a ≣ 1 (mod b)` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.invmod(8, 12) // returns NaN +math.invmod(7, 13) // return 2 +math.invmod(15151, 15122) // returns 10429 +``` + + +## See also + +[gcd](gcd.md), +[xgcd](xgcd.md) diff --git a/node_modules/mathjs/docs/reference/functions/isInteger.md b/node_modules/mathjs/docs/reference/functions/isInteger.md new file mode 100644 index 0000000..1e00dac --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/isInteger.md @@ -0,0 +1,55 @@ + + +# Function isInteger + +Test whether a value is an integer number. +The function supports `number`, `BigNumber`, and `Fraction`. + +The function is evaluated element-wise in case of Array or Matrix input. + + +## Syntax + +```js +math.isInteger(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Array | Matrix | Value to be tested + +### Returns + +Type | Description +---- | ----------- +boolean | Returns true when `x` contains a numeric, integer value. Throws an error in case of an unknown data type. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.isInteger(2) // returns true +math.isInteger(0) // returns true +math.isInteger(0.5) // returns false +math.isInteger(math.bignumber(500)) // returns true +math.isInteger(math.fraction(4)) // returns true +math.isInteger('3') // returns true +math.isInteger([3, 0.5, -2]) // returns [true, false, true] +math.isInteger(math.complex('2-4i') // throws an error +``` + + +## See also + +[isNumeric](isNumeric.md), +[isPositive](isPositive.md), +[isNegative](isNegative.md), +[isZero](isZero.md) diff --git a/node_modules/mathjs/docs/reference/functions/isNaN.md b/node_modules/mathjs/docs/reference/functions/isNaN.md new file mode 100644 index 0000000..71984a1 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/isNaN.md @@ -0,0 +1,56 @@ + + +# Function isNaN + +Test whether a value is NaN (not a number). +The function supports types `number`, `BigNumber`, `Fraction`, `Unit` and `Complex`. + +The function is evaluated element-wise in case of Array or Matrix input. + + +## Syntax + +```js +math.isNaN(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Unit | Array | Matrix | Value to be tested + +### Returns + +Type | Description +---- | ----------- +boolean | Returns true when `x` is NaN. Throws an error in case of an unknown data type. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.isNaN(3) // returns false +math.isNaN(NaN) // returns true +math.isNaN(0) // returns false +math.isNaN(math.bignumber(NaN)) // returns true +math.isNaN(math.bignumber(0)) // returns false +math.isNaN(math.fraction(-2, 5)) // returns false +math.isNaN('-2') // returns false +math.isNaN([2, 0, -3, NaN]') // returns [false, false, false, true] +``` + + +## See also + +[isNumeric](isNumeric.md), +[isNegative](isNegative.md), +[isPositive](isPositive.md), +[isZero](isZero.md), +[isInteger](isInteger.md) diff --git a/node_modules/mathjs/docs/reference/functions/isNegative.md b/node_modules/mathjs/docs/reference/functions/isNegative.md new file mode 100644 index 0000000..b0018d9 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/isNegative.md @@ -0,0 +1,55 @@ + + +# Function isNegative + +Test whether a value is negative: smaller than zero. +The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`. + +The function is evaluated element-wise in case of Array or Matrix input. + + +## Syntax + +```js +math.isNegative(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Unit | Array | Matrix | Value to be tested + +### Returns + +Type | Description +---- | ----------- +boolean | Returns true when `x` is larger than zero. Throws an error in case of an unknown data type. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.isNegative(3) // returns false +math.isNegative(-2) // returns true +math.isNegative(0) // returns false +math.isNegative(-0) // returns false +math.isNegative(math.bignumber(2)) // returns false +math.isNegative(math.fraction(-2, 5)) // returns true +math.isNegative('-2') // returns true +math.isNegative([2, 0, -3]') // returns [false, false, true] +``` + + +## See also + +[isNumeric](isNumeric.md), +[isPositive](isPositive.md), +[isZero](isZero.md), +[isInteger](isInteger.md) diff --git a/node_modules/mathjs/docs/reference/functions/isNumeric.md b/node_modules/mathjs/docs/reference/functions/isNumeric.md new file mode 100644 index 0000000..9188bc9 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/isNumeric.md @@ -0,0 +1,55 @@ + + +# Function isNumeric + +Test whether a value is an numeric value. + +The function is evaluated element-wise in case of Array or Matrix input. + + +## Syntax + +```js +math.isNumeric(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | * | Value to be tested + +### Returns + +Type | Description +---- | ----------- +boolean | Returns true when `x` is a `number`, `BigNumber`, `Fraction`, or `boolean`. Returns false for other types. Throws an error in case of unknown types. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.isNumeric(2) // returns true +math.isNumeric('2') // returns false +math.hasNumericValue('2') // returns true +math.isNumeric(0) // returns true +math.isNumeric(math.bignumber(500)) // returns true +math.isNumeric(math.fraction(4)) // returns true +math.isNumeric(math.complex('2-4i') // returns false +math.isNumeric([2.3, 'foo', false]) // returns [true, false, true] +``` + + +## See also + +[isZero](isZero.md), +[isPositive](isPositive.md), +[isNegative](isNegative.md), +[isInteger](isInteger.md), +[hasNumericValue](hasNumericValue.md) diff --git a/node_modules/mathjs/docs/reference/functions/isPositive.md b/node_modules/mathjs/docs/reference/functions/isPositive.md new file mode 100644 index 0000000..44caf46 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/isPositive.md @@ -0,0 +1,57 @@ + + +# Function isPositive + +Test whether a value is positive: larger than zero. +The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`. + +The function is evaluated element-wise in case of Array or Matrix input. + + +## Syntax + +```js +math.isPositive(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Unit | Array | Matrix | Value to be tested + +### Returns + +Type | Description +---- | ----------- +boolean | Returns true when `x` is larger than zero. Throws an error in case of an unknown data type. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.isPositive(3) // returns true +math.isPositive(-2) // returns false +math.isPositive(0) // returns false +math.isPositive(-0) // returns false +math.isPositive(0.5) // returns true +math.isPositive(math.bignumber(2)) // returns true +math.isPositive(math.fraction(-2, 5)) // returns false +math.isPositive(math.fraction(1,3)) // returns false +math.isPositive('2') // returns true +math.isPositive([2, 0, -3]) // returns [true, false, false] +``` + + +## See also + +[isNumeric](isNumeric.md), +[isZero](isZero.md), +[isNegative](isNegative.md), +[isInteger](isInteger.md) diff --git a/node_modules/mathjs/docs/reference/functions/isPrime.md b/node_modules/mathjs/docs/reference/functions/isPrime.md new file mode 100644 index 0000000..8403bd4 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/isPrime.md @@ -0,0 +1,54 @@ + + +# Function isPrime + +Test whether a value is prime: has no divisors other than itself and one. +The function supports type `number`, `bignumber`. + +The function is evaluated element-wise in case of Array or Matrix input. + + +## Syntax + +```js +math.isPrime(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Array | Matrix | Value to be tested + +### Returns + +Type | Description +---- | ----------- +boolean | Returns true when `x` is larger than zero. Throws an error in case of an unknown data type. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.isPrime(3) // returns true +math.isPrime(-2) // returns false +math.isPrime(0) // returns false +math.isPrime(-0) // returns false +math.isPrime(0.5) // returns false +math.isPrime('2') // returns true +math.isPrime([2, 17, 100]) // returns [true, true, false] +``` + + +## See also + +[isNumeric](isNumeric.md), +[isZero](isZero.md), +[isNegative](isNegative.md), +[isInteger](isInteger.md) diff --git a/node_modules/mathjs/docs/reference/functions/isZero.md b/node_modules/mathjs/docs/reference/functions/isZero.md new file mode 100644 index 0000000..9ce8032 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/isZero.md @@ -0,0 +1,59 @@ + + +# Function isZero + +Test whether a value is zero. +The function can check for zero for types `number`, `BigNumber`, `Fraction`, +`Complex`, and `Unit`. + +The function is evaluated element-wise in case of Array or Matrix input. + + +## Syntax + +```js +math.isZero(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Fraction | Unit | Array | Matrix | Value to be tested + +### Returns + +Type | Description +---- | ----------- +boolean | Returns true when `x` is zero. Throws an error in case of an unknown data type. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.isZero(0) // returns true +math.isZero(2) // returns false +math.isZero(0.5) // returns false +math.isZero(math.bignumber(0)) // returns true +math.isZero(math.fraction(0)) // returns true +math.isZero(math.fraction(1,3)) // returns false +math.isZero(math.complex('2 - 4i') // returns false +math.isZero(math.complex('0i') // returns true +math.isZero('0') // returns true +math.isZero('2') // returns false +math.isZero([2, 0, -3]') // returns [false, true, false] +``` + + +## See also + +[isNumeric](isNumeric.md), +[isPositive](isPositive.md), +[isNegative](isNegative.md), +[isInteger](isInteger.md) diff --git a/node_modules/mathjs/docs/reference/functions/kldivergence.md b/node_modules/mathjs/docs/reference/functions/kldivergence.md new file mode 100644 index 0000000..f95b381 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/kldivergence.md @@ -0,0 +1,41 @@ + + +# Function kldivergence + +Calculate the Kullback-Leibler (KL) divergence between two distributions + + +## Syntax + +```js +math.kldivergence(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`q` | Array | Matrix | First vector +`p` | Array | Matrix | Second vector + +### Returns + +Type | Description +---- | ----------- +number | Returns distance between q and p + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5]) //returns 0.24376698773121153 + +``` + + diff --git a/node_modules/mathjs/docs/reference/functions/kron.md b/node_modules/mathjs/docs/reference/functions/kron.md new file mode 100644 index 0000000..cde5165 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/kron.md @@ -0,0 +1,53 @@ + + +# Function kron + +Calculates the kronecker product of 2 matrices or vectors. + +NOTE: If a one dimensional vector / matrix is given, it will be +wrapped so its two dimensions. +See the examples. + + +## Syntax + +```js +math.kron(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Array | Matrix | First vector +`y` | Array | Matrix | Second vector + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | Returns the kronecker product of `x` and `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]]) +// returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ] + +math.kron([1,1], [2,3,4]) +// returns [ [ 2, 3, 4, 2, 3, 4 ] ] +``` + + +## See also + +[multiply](multiply.md), +[dot](dot.md), +[cross](cross.md) diff --git a/node_modules/mathjs/docs/reference/functions/larger.md b/node_modules/mathjs/docs/reference/functions/larger.md new file mode 100644 index 0000000..083d1c1 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/larger.md @@ -0,0 +1,60 @@ + + +# Function larger + +Test whether value x is larger than y. + +The function returns true when x is larger than y and the relative +difference between x and y is larger than the configured epsilon. The +function cannot be used to compare values smaller than approximately 2.22e-16. + +For matrices, the function is evaluated element wise. +Strings are compared by their numerical value. + + +## Syntax + +```js +math.larger(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix | First value to compare +`y` | number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix | Second value to compare + +### Returns + +Type | Description +---- | ----------- +boolean | Array | Matrix | Returns true when the x is larger than y, else returns false + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.larger(2, 3) // returns false +math.larger(5, 2 + 2) // returns true + +const a = math.unit('5 cm') +const b = math.unit('2 inch') +math.larger(a, b) // returns false +``` + + +## See also + +[equal](equal.md), +[unequal](unequal.md), +[smaller](smaller.md), +[smallerEq](smallerEq.md), +[largerEq](largerEq.md), +[compare](compare.md) diff --git a/node_modules/mathjs/docs/reference/functions/largerEq.md b/node_modules/mathjs/docs/reference/functions/largerEq.md new file mode 100644 index 0000000..cd3400a --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/largerEq.md @@ -0,0 +1,56 @@ + + +# Function largerEq + +Test whether value x is larger or equal to y. + +The function returns true when x is larger than y or the relative +difference between x and y is smaller than the configured epsilon. The +function cannot be used to compare values smaller than approximately 2.22e-16. + +For matrices, the function is evaluated element wise. +Strings are compared by their numerical value. + + +## Syntax + +```js +math.largerEq(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix | First value to compare +`y` | number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix | Second value to compare + +### Returns + +Type | Description +---- | ----------- +boolean | Array | Matrix | Returns true when the x is larger or equal to y, else returns false + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.larger(2, 1 + 1) // returns false +math.largerEq(2, 1 + 1) // returns true +``` + + +## See also + +[equal](equal.md), +[unequal](unequal.md), +[smaller](smaller.md), +[smallerEq](smallerEq.md), +[larger](larger.md), +[compare](compare.md) diff --git a/node_modules/mathjs/docs/reference/functions/lcm.md b/node_modules/mathjs/docs/reference/functions/lcm.md new file mode 100644 index 0000000..bf9876e --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/lcm.md @@ -0,0 +1,54 @@ + + +# Function lcm + +Calculate the least common multiple for two or more values or arrays. + +lcm is defined as: + + lcm(a, b) = abs(a * b) / gcd(a, b) + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.lcm(a, b) +math.lcm(a, b, c, ...) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... number | BigNumber | Array | Matrix | Two or more integer numbers + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Array | Matrix | The least common multiple + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.lcm(4, 6) // returns 12 +math.lcm(6, 21) // returns 42 +math.lcm(6, 21, 5) // returns 210 + +math.lcm([4, 6], [6, 21]) // returns [12, 42] +``` + + +## See also + +[gcd](gcd.md), +[xgcd](xgcd.md) diff --git a/node_modules/mathjs/docs/reference/functions/leafCount.md b/node_modules/mathjs/docs/reference/functions/leafCount.md new file mode 100644 index 0000000..00c3b2a --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/leafCount.md @@ -0,0 +1,52 @@ + + +# Function leafCount + +Gives the number of "leaf nodes" in the parse tree of the given expression +A leaf node is one that has no subexpressions, essentially either a +symbol or a constant. Note that `5!` has just one leaf, the '5'; the +unary factorial operator does not add a leaf. On the other hand, +function symbols do add leaves, so `sin(x)/cos(x)` has four leaves. + +The `simplify()` function should generally not increase the `leafCount()` +of an expression, although currently there is no guarantee that it never +does so. In many cases, `simplify()` reduces the leaf count. + + +## Syntax + +```js +leafCount(expr) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`expr` | Node | string | The expression to count the leaves of + +### Returns + +Type | Description +---- | ----------- +number | The number of leaves of `expr` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.leafCount('x') // 1 +math.leafCount(math.parse('a*d-b*c')) // 4 +math.leafCount('[a,b;c,d][0,1]') // 6 +``` + + +## See also + +[simplify](simplify.md) diff --git a/node_modules/mathjs/docs/reference/functions/leftShift.md b/node_modules/mathjs/docs/reference/functions/leftShift.md new file mode 100644 index 0000000..587bdd5 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/leftShift.md @@ -0,0 +1,52 @@ + + +# Function leftShift + +Bitwise left logical shift of a value x by y number of bits, `x << y`. +For matrices, the function is evaluated element wise. +For units, the function is evaluated on the best prefix base. + + +## Syntax + +```js +math.leftShift(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Array | Matrix | Value to be shifted +`y` | number | BigNumber | Amount of shifts + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Array | Matrix | `x` shifted left `y` times + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.leftShift(1, 2) // returns number 4 + +math.leftShift([1, 2, 3], 4) // returns Array [16, 32, 64] +``` + + +## See also + +[leftShift](leftShift.md), +[bitNot](bitNot.md), +[bitOr](bitOr.md), +[bitXor](bitXor.md), +[rightArithShift](rightArithShift.md), +[rightLogShift](rightLogShift.md) diff --git a/node_modules/mathjs/docs/reference/functions/log.md b/node_modules/mathjs/docs/reference/functions/log.md new file mode 100644 index 0000000..7cb39bd --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/log.md @@ -0,0 +1,57 @@ + + +# Function log + +Calculate the logarithm of a value. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.log(x) +math.log(x, base) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | Value for which to calculate the logarithm. +`base` | number | BigNumber | Complex | Optional base for the logarithm. If not provided, the natural logarithm of `x` is calculated. Default value: e. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Returns the logarithm of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.log(3.5) // returns 1.252762968495368 +math.exp(math.log(2.4)) // returns 2.4 + +math.pow(10, 4) // returns 10000 +math.log(10000, 10) // returns 4 +math.log(10000) / math.log(10) // returns 4 + +math.log(1024, 2) // returns 10 +math.pow(2, 10) // returns 1024 +``` + + +## See also + +[exp](exp.md), +[log2](log2.md), +[log10](log10.md), +[log1p](log1p.md) diff --git a/node_modules/mathjs/docs/reference/functions/log10.md b/node_modules/mathjs/docs/reference/functions/log10.md new file mode 100644 index 0000000..b710efd --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/log10.md @@ -0,0 +1,50 @@ + + +# Function log10 + +Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.log10(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | Value for which to calculate the logarithm. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Returns the 10-base logarithm of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.log10(0.00001) // returns -5 +math.log10(10000) // returns 4 +math.log(10000) / math.log(10) // returns 4 +math.pow(10, 4) // returns 10000 +``` + + +## See also + +[exp](exp.md), +[log](log.md), +[log1p](log1p.md), +[log2](log2.md) diff --git a/node_modules/mathjs/docs/reference/functions/log1p.md b/node_modules/mathjs/docs/reference/functions/log1p.md new file mode 100644 index 0000000..fdc9b4d --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/log1p.md @@ -0,0 +1,54 @@ + + +# Function log1p + +Calculate the logarithm of a `value+1`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.log1p(x) +math.log1p(x, base) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | Value for which to calculate the logarithm of `x+1`. +`base` | number | BigNumber | Complex | Optional base for the logarithm. If not provided, the natural logarithm of `x+1` is calculated. Default value: e. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Returns the logarithm of `x+1` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.log1p(2.5) // returns 1.252762968495368 +math.exp(math.log1p(1.4)) // returns 2.4 + +math.pow(10, 4) // returns 10000 +math.log1p(9999, 10) // returns 4 +math.log1p(9999) / math.log(10) // returns 4 +``` + + +## See also + +[exp](exp.md), +[log](log.md), +[log2](log2.md), +[log10](log10.md) diff --git a/node_modules/mathjs/docs/reference/functions/log2.md b/node_modules/mathjs/docs/reference/functions/log2.md new file mode 100644 index 0000000..1697061 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/log2.md @@ -0,0 +1,50 @@ + + +# Function log2 + +Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.log2(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | Value for which to calculate the logarithm. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Returns the 2-base logarithm of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.log2(0.03125) // returns -5 +math.log2(16) // returns 4 +math.log2(16) / math.log2(2) // returns 4 +math.pow(2, 4) // returns 16 +``` + + +## See also + +[exp](exp.md), +[log](log.md), +[log1p](log1p.md), +[log10](log10.md) diff --git a/node_modules/mathjs/docs/reference/functions/lsolve.md b/node_modules/mathjs/docs/reference/functions/lsolve.md new file mode 100644 index 0000000..97b59d5 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/lsolve.md @@ -0,0 +1,51 @@ + + +# Function lsolve + +Finds one solution of a linear equation system by forwards substitution. Matrix must be a lower triangular matrix. Throws an error if there's no solution. + +`L * x = b` + + +## Syntax + +```js +math.lsolve(L, b) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`L` | Matrix, Array | A N x N matrix or array (L) +`b` | Matrix, Array | A column vector with the b values + +### Returns + +Type | Description +---- | ----------- +DenseMatrix | Array | A column vector with the linear system solution (x) + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const a = [[-2, 3], [2, 1]] +const b = [11, 9] +const x = lsolve(a, b) // [[-5.5], [20]] +``` + + +## See also + +[lsolveAll](lsolveAll.md), +[lup](lup.md), +[slu](slu.md), +[usolve](usolve.md), +[lusolve](lusolve.md) diff --git a/node_modules/mathjs/docs/reference/functions/lsolveAll.md b/node_modules/mathjs/docs/reference/functions/lsolveAll.md new file mode 100644 index 0000000..4e264df --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/lsolveAll.md @@ -0,0 +1,51 @@ + + +# Function lsolveAll + +Finds all solutions of a linear equation system by forwards substitution. Matrix must be a lower triangular matrix. + +`L * x = b` + + +## Syntax + +```js +math.lsolveAll(L, b) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`L` | Matrix, Array | A N x N matrix or array (L) +`b` | Matrix, Array | A column vector with the b values + +### Returns + +Type | Description +---- | ----------- +DenseMatrix[] | Array[] | An array of affine-independent column vectors (x) that solve the linear system + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const a = [[-2, 3], [2, 1]] +const b = [11, 9] +const x = lsolveAll(a, b) // [ [[-5.5], [20]] ] +``` + + +## See also + +[lsolve](lsolve.md), +[lup](lup.md), +[slu](slu.md), +[usolve](usolve.md), +[lusolve](lusolve.md) diff --git a/node_modules/mathjs/docs/reference/functions/lup.md b/node_modules/mathjs/docs/reference/functions/lup.md new file mode 100644 index 0000000..629c207 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/lup.md @@ -0,0 +1,52 @@ + + +# Function lup + +Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a +row permutation vector `p` where `A[p,:] = L * U` + + +## Syntax + +```js +math.lup(A) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`A` | Matrix | Array | A two dimensional matrix or array for which to get the LUP decomposition. + +### Returns + +Type | Description +---- | ----------- +{L: Array | Matrix, U: Array | Matrix, P: Array.<number>} | The lower triangular matrix, the upper triangular matrix and the permutation matrix. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const m = [[2, 1], [1, 4]] +const r = math.lup(m) +// r = { +// L: [[1, 0], [0.5, 1]], +// U: [[2, 1], [0, 3.5]], +// P: [0, 1] +// } +``` + + +## See also + +[slu](slu.md), +[lsolve](lsolve.md), +[lusolve](lusolve.md), +[usolve](usolve.md) diff --git a/node_modules/mathjs/docs/reference/functions/lusolve.md b/node_modules/mathjs/docs/reference/functions/lusolve.md new file mode 100644 index 0000000..c00ec9a --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/lusolve.md @@ -0,0 +1,59 @@ + + +# Function lusolve + +Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector. + + +## Syntax + +```js +math.lusolve(A, b) // returns column vector with the solution to the linear system A * x = b +math.lusolve(lup, b) // returns column vector with the solution to the linear system A * x = b, lup = math.lup(A) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`A` | Matrix | Array | Object | Invertible Matrix or the Matrix LU decomposition +`b` | Matrix | Array | Column Vector +`order` | number | The Symbolic Ordering and Analysis order, see slu for details. Matrix must be a SparseMatrix +`threshold` | Number | Partial pivoting threshold (1 for partial pivoting), see slu for details. Matrix must be a SparseMatrix. + +### Returns + +Type | Description +---- | ----------- +DenseMatrix | Array | Column vector with the solution to the linear system A * x = b + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const m = [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]] + +const x = math.lusolve(m, [-1, -1, -1, -1]) // x = [[-1], [-0.5], [-1/3], [-0.25]] + +const f = math.lup(m) +const x1 = math.lusolve(f, [-1, -1, -1, -1]) // x1 = [[-1], [-0.5], [-1/3], [-0.25]] +const x2 = math.lusolve(f, [1, 2, 1, -1]) // x2 = [[1], [1], [1/3], [-0.25]] + +const a = [[-2, 3], [2, 1]] +const b = [11, 9] +const x = math.lusolve(a, b) // [[2], [5]] +``` + + +## See also + +[lup](lup.md), +[slu](slu.md), +[lsolve](lsolve.md), +[usolve](usolve.md) diff --git a/node_modules/mathjs/docs/reference/functions/mad.md b/node_modules/mathjs/docs/reference/functions/mad.md new file mode 100644 index 0000000..768a082 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/mad.md @@ -0,0 +1,50 @@ + + +# Function mad + +Compute the median absolute deviation of a matrix or a list with values. +The median absolute deviation is defined as the median of the absolute +deviations from the median. + + +## Syntax + +```js +math.mad(a, b, c, ...) +math.mad(A) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`array` | Array | Matrix | A single matrix or multiple scalar values. + +### Returns + +Type | Description +---- | ----------- +* | The median absolute deviation. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.mad(10, 20, 30) // returns 10 +math.mad([1, 2, 3]) // returns 1 +math.mad([[1, 2, 3], [4, 5, 6]]) // returns 1.5 +``` + + +## See also + +[median](median.md), +[mean](mean.md), +[std](std.md), +[abs](abs.md) diff --git a/node_modules/mathjs/docs/reference/functions/map.md b/node_modules/mathjs/docs/reference/functions/map.md new file mode 100644 index 0000000..110c576 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/map.md @@ -0,0 +1,65 @@ + + +# Function map + +Create a new matrix or array with the results of a callback function executed on +each entry of a given matrix/array. + +For each entry of the input, the callback is invoked with three arguments: +the value of the entry, the index at which that entry occurs, and the full +matrix/array being traversed. Note that because the matrix/array might be +multidimensional, the "index" argument is always an array of numbers giving +the index in each dimension. This is true even for vectors: the "index" +argument is an array of length 1, rather than simply a number. + + +## Syntax + +```js +math.map(x, callback) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Matrix | Array | The input to iterate on. +`callback` | Function | The function to call (as described above) on each entry of the input + +### Returns + +Type | Description +---- | ----------- +Matrix | array | Transformed map of x; always has the same type and shape as x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.map([1, 2, 3], function(value) { + return value * value +}) // returns [1, 4, 9] + +// The calling convention for the callback can cause subtleties: +math.map([1, 2, 3], math.format) +// throws TypeError: map attempted to call 'format(1,[0])' but argument 2 of type Array does not match expected type number or function or Object or string or boolean +// [This happens because `format` _can_ take a second argument, +// but its semantics don't match that of the 2nd argument `map` provides] + +// To avoid this error, use a function that takes exactly the +// desired arguments: +math.map([1, 2, 3], x => math.format(x)) // returns ['1', '2', '3'] +``` + + +## See also + +[filter](filter.md), +[forEach](forEach.md), +[sort](sort.md) diff --git a/node_modules/mathjs/docs/reference/functions/matrix.md b/node_modules/mathjs/docs/reference/functions/matrix.md new file mode 100644 index 0000000..4f61539 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/matrix.md @@ -0,0 +1,56 @@ + + +# Function matrix + +Create a Matrix. The function creates a new `math.Matrix` object from +an `Array`. A Matrix has utility functions to manipulate the data in the +matrix, like getting the size and getting or setting values in the matrix. +Supported storage formats are 'dense' and 'sparse'. + + +## Syntax + +```js +math.matrix() // creates an empty matrix using default storage format (dense). +math.matrix(data) // creates a matrix with initial data using default storage format (dense). +math.matrix('dense') // creates an empty matrix using the given storage format. +math.matrix(data, 'dense') // creates a matrix with initial data using the given storage format. +math.matrix(data, 'sparse') // creates a sparse matrix with initial data. +math.matrix(data, 'sparse', 'number') // creates a sparse matrix with initial data, number data type. +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`data` | Array | Matrix | A multi dimensional array +`format` | string | The Matrix storage format + +### Returns + +Type | Description +---- | ----------- +Matrix | The created matrix + + +## Examples + +```js +let m = math.matrix([[1, 2], [3, 4]]) +m.size() // Array [2, 2] +m.resize([3, 2], 5) +m.valueOf() // Array [[1, 2], [3, 4], [5, 5]] +m.get([1, 0]) // number 3 +``` + + +## See also + +[bignumber](bignumber.md), +[boolean](boolean.md), +[complex](complex.md), +[index](index.md), +[number](number.md), +[string](string.md), +[unit](unit.md), +[sparse](sparse.md) diff --git a/node_modules/mathjs/docs/reference/functions/matrixFromColumns.md b/node_modules/mathjs/docs/reference/functions/matrixFromColumns.md new file mode 100644 index 0000000..e0c7995 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/matrixFromColumns.md @@ -0,0 +1,49 @@ + + +# Function matrixFromColumns + +Create a dense matrix from vectors as individual columns. +If you pass row vectors, they will be transposed (but not conjugated!) + + +## Syntax + +```js +math.matrixFromColumns(...arr) +math.matrixFromColumns(col1, col2) +math.matrixFromColumns(col1, col2, col3) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`cols` | ... Array | Matrix | Multiple columns + +### Returns + +Type | Description +---- | ----------- +number[][] | Matrix | if at least one of the arguments is an array, an array will be returned + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.matrixFromColumns([1, 2, 3], [[4],[5],[6]]) +math.matrixFromColumns(...vectors) +``` + + +## See also + +[matrix](matrix.md), +[matrixFromRows](matrixFromRows.md), +[matrixFromFunction](matrixFromFunction.md), +[zeros](zeros.md) diff --git a/node_modules/mathjs/docs/reference/functions/matrixFromFunction.md b/node_modules/mathjs/docs/reference/functions/matrixFromFunction.md new file mode 100644 index 0000000..8529643 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/matrixFromFunction.md @@ -0,0 +1,54 @@ + + +# Function matrixFromFunction + +Create a matrix by evaluating a generating function at each index. +The simplest overload returns a multi-dimensional array as long as `size` is an array. +Passing `size` as a Matrix or specifying a `format` will result in returning a Matrix. + + +## Syntax + +```js +math.matrixFromFunction(size, fn) +math.matrixFromFunction(size, fn, format) +math.matrixFromFunction(size, fn, format, datatype) +math.matrixFromFunction(size, format, fn) +math.matrixFromFunction(size, format, datatype, fn) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`size` | Array | Matrix | The size of the matrix to be created +`fn` | function | Callback function invoked for every entry in the matrix +`format` | string | The Matrix storage format, either `'dense'` or `'sparse'` +`datatype` | string | Type of the values + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | Returns the created matrix + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.matrixFromFunction([3,3], i => i[0] - i[1]) // an antisymmetric matrix +math.matrixFromFunction([100, 100], 'sparse', i => i[0] - i[1] === 1 ? 4 : 0) // a sparse subdiagonal matrix +math.matrixFromFunction([5], i => math.random()) // a random vector +``` + + +## See also + +[matrix](matrix.md), +[zeros](zeros.md) diff --git a/node_modules/mathjs/docs/reference/functions/matrixFromRows.md b/node_modules/mathjs/docs/reference/functions/matrixFromRows.md new file mode 100644 index 0000000..a7de41f --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/matrixFromRows.md @@ -0,0 +1,49 @@ + + +# Function matrixFromRows + +Create a dense matrix from vectors as individual rows. +If you pass column vectors, they will be transposed (but not conjugated!) + + +## Syntax + +```js +math.matrixFromRows(...arr) +math.matrixFromRows(row1, row2) +math.matrixFromRows(row1, row2, row3) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`rows` | ... Array | Matrix | Multiple rows + +### Returns + +Type | Description +---- | ----------- +number[][] | Matrix | if at least one of the arguments is an array, an array will be returned + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.matrixFromRows([1, 2, 3], [[4],[5],[6]]) +math.matrixFromRows(...vectors) +``` + + +## See also + +[matrix](matrix.md), +[matrixFromColumns](matrixFromColumns.md), +[matrixFromFunction](matrixFromFunction.md), +[zeros](zeros.md) diff --git a/node_modules/mathjs/docs/reference/functions/max.md b/node_modules/mathjs/docs/reference/functions/max.md new file mode 100644 index 0000000..4ffc4d0 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/max.md @@ -0,0 +1,61 @@ + + +# Function max + +Compute the maximum value of a matrix or a list with values. +In case of a multi dimensional array, the maximum of the flattened array +will be calculated. When `dim` is provided, the maximum over the selected +dimension will be calculated. Parameter `dim` is zero-based. + + +## Syntax + +```js +math.max(a, b, c, ...) +math.max(A) +math.max(A, dim) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... * | A single matrix or or multiple scalar values + +### Returns + +Type | Description +---- | ----------- +* | The maximum value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.max(2, 1, 4, 3) // returns 4 +math.max([2, 1, 4, 3]) // returns 4 + +// maximum over a specified dimension (zero-based) +math.max([[2, 5], [4, 3], [1, 7]], 0) // returns [4, 7] +math.max([[2, 5], [4, 3]], [1, 7], 1) // returns [5, 4, 7] + +math.max(2.7, 7.1, -4.5, 2.0, 4.1) // returns 7.1 +math.min(2.7, 7.1, -4.5, 2.0, 4.1) // returns -4.5 +``` + + +## See also + +[mean](mean.md), +[median](median.md), +[min](min.md), +[prod](prod.md), +[std](std.md), +[sum](sum.md), +[variance](variance.md) diff --git a/node_modules/mathjs/docs/reference/functions/mean.md b/node_modules/mathjs/docs/reference/functions/mean.md new file mode 100644 index 0000000..ae921f6 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/mean.md @@ -0,0 +1,57 @@ + + +# Function mean + +Compute the mean value of matrix or a list with values. +In case of a multi dimensional array, the mean of the flattened array +will be calculated. When `dim` is provided, the maximum over the selected +dimension will be calculated. Parameter `dim` is zero-based. + + +## Syntax + +```js +math.mean(a, b, c, ...) +math.mean(A) +math.mean(A, dim) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... * | A single matrix or or multiple scalar values + +### Returns + +Type | Description +---- | ----------- +* | The mean of all values + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.mean(2, 1, 4, 3) // returns 2.5 +math.mean([1, 2.7, 3.2, 4]) // returns 2.725 + +math.mean([[2, 5], [6, 3], [1, 7]], 0) // returns [3, 5] +math.mean([[2, 5], [6, 3], [1, 7]], 1) // returns [3.5, 4.5, 4] +``` + + +## See also + +[median](median.md), +[min](min.md), +[max](max.md), +[sum](sum.md), +[prod](prod.md), +[std](std.md), +[variance](variance.md) diff --git a/node_modules/mathjs/docs/reference/functions/median.md b/node_modules/mathjs/docs/reference/functions/median.md new file mode 100644 index 0000000..6d7134c --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/median.md @@ -0,0 +1,57 @@ + + +# Function median + +Compute the median of a matrix or a list with values. The values are +sorted and the middle value is returned. In case of an even number of +values, the average of the two middle values is returned. +Supported types of values are: Number, BigNumber, Unit + +In case of a (multi dimensional) array or matrix, the median of all +elements will be calculated. + + +## Syntax + +```js +math.median(a, b, c, ...) +math.median(A) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... * | A single matrix or or multiple scalar values + +### Returns + +Type | Description +---- | ----------- +* | The median + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.median(5, 2, 7) // returns 5 +math.median([3, -1, 5, 7]) // returns 4 +``` + + +## See also + +[mean](mean.md), +[min](min.md), +[max](max.md), +[sum](sum.md), +[prod](prod.md), +[std](std.md), +[variance](variance.md), +[quantileSeq](quantileSeq.md) diff --git a/node_modules/mathjs/docs/reference/functions/min.md b/node_modules/mathjs/docs/reference/functions/min.md new file mode 100644 index 0000000..799e42f --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/min.md @@ -0,0 +1,61 @@ + + +# Function min + +Compute the minimum value of a matrix or a list of values. +In case of a multi dimensional array, the minimum of the flattened array +will be calculated. When `dim` is provided, the minimum over the selected +dimension will be calculated. Parameter `dim` is zero-based. + + +## Syntax + +```js +math.min(a, b, c, ...) +math.min(A) +math.min(A, dim) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... * | A single matrix or or multiple scalar values + +### Returns + +Type | Description +---- | ----------- +* | The minimum value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.min(2, 1, 4, 3) // returns 1 +math.min([2, 1, 4, 3]) // returns 1 + +// minimum over a specified dimension (zero-based) +math.min([[2, 5], [4, 3], [1, 7]], 0) // returns [1, 3] +math.min([[2, 5], [4, 3], [1, 7]], 1) // returns [2, 3, 1] + +math.max(2.7, 7.1, -4.5, 2.0, 4.1) // returns 7.1 +math.min(2.7, 7.1, -4.5, 2.0, 4.1) // returns -4.5 +``` + + +## See also + +[mean](mean.md), +[median](median.md), +[max](max.md), +[prod](prod.md), +[std](std.md), +[sum](sum.md), +[variance](variance.md) diff --git a/node_modules/mathjs/docs/reference/functions/mod.md b/node_modules/mathjs/docs/reference/functions/mod.md new file mode 100644 index 0000000..271c097 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/mod.md @@ -0,0 +1,59 @@ + + +# Function mod + +Calculates the modulus, the remainder of an integer division. + +For matrices, the function is evaluated element wise. + +The modulus is defined as: + + x - y * floor(x / y) + +See https://en.wikipedia.org/wiki/Modulo_operation. + + +## Syntax + +```js +math.mod(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Array | Matrix | Dividend +`y` | number | BigNumber | Fraction | Array | Matrix | Divisor + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Array | Matrix | Returns the remainder of `x` divided by `y`. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.mod(8, 3) // returns 2 +math.mod(11, 2) // returns 1 + +function isOdd(x) { + return math.mod(x, 2) != 0 +} + +isOdd(2) // returns false +isOdd(3) // returns true +``` + + +## See also + +[divide](divide.md) diff --git a/node_modules/mathjs/docs/reference/functions/mode.md b/node_modules/mathjs/docs/reference/functions/mode.md new file mode 100644 index 0000000..744ed41 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/mode.md @@ -0,0 +1,50 @@ + + +# Function mode + +Computes the mode of a set of numbers or a list with values(numbers or characters). +If there are more than one modes, it returns a list of those values. + + +## Syntax + +```js +math.mode(a, b, c, ...) +math.mode(A) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... * | A single matrix + +### Returns + +Type | Description +---- | ----------- +* | The mode of all values + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.mode(2, 1, 4, 3, 1) // returns [1] +math.mode([1, 2.7, 3.2, 4, 2.7]) // returns [2.7] +math.mode(1, 4, 6, 1, 6) // returns [1, 6] +math.mode('a','a','b','c') // returns ["a"] +math.mode(1, 1.5, 'abc') // returns [1, 1.5, "abc"] +``` + + +## See also + +[median](median.md), +[](.md), +[mean](mean.md) diff --git a/node_modules/mathjs/docs/reference/functions/multinomial.md b/node_modules/mathjs/docs/reference/functions/multinomial.md new file mode 100644 index 0000000..a98b580 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/multinomial.md @@ -0,0 +1,46 @@ + + +# Function multinomial + +Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities. + +multinomial takes one array of integers as an argument. +The following condition must be enforced: every ai <= 0 + + +## Syntax + +```js +math.multinomial(a) // a is an array type +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a` | number[] | BigNumber[] | Integer numbers of objects in the subset + +### Returns + +Type | Description +---- | ----------- +Number | BigNumber | Multinomial coefficient. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.multinomial([1,2,1]) // returns 12 +``` + + +## See also + +[combinations](combinations.md), +[factorial](factorial.md) diff --git a/node_modules/mathjs/docs/reference/functions/multiply.md b/node_modules/mathjs/docs/reference/functions/multiply.md new file mode 100644 index 0000000..f85c2cd --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/multiply.md @@ -0,0 +1,60 @@ + + +# Function multiply + +Multiply two or more values, `x * y`. +For matrices, the matrix product is calculated. + + +## Syntax + +```js +math.multiply(x, y) +math.multiply(x, y, z, ...) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | First value to multiply +`y` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Second value to multiply + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Multiplication of `x` and `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.multiply(4, 5.2) // returns number 20.8 +math.multiply(2, 3, 4) // returns number 24 + +const a = math.complex(2, 3) +const b = math.complex(4, 1) +math.multiply(a, b) // returns Complex 5 + 14i + +const c = [[1, 2], [4, 3]] +const d = [[1, 2, 3], [3, -4, 7]] +math.multiply(c, d) // returns Array [[7, -6, 17], [13, -4, 33]] + +const e = math.unit('2.1 km') +math.multiply(3, e) // returns Unit 6.3 km +``` + + +## See also + +[divide](divide.md), +[prod](prod.md), +[cross](cross.md), +[dot](dot.md) diff --git a/node_modules/mathjs/docs/reference/functions/norm.md b/node_modules/mathjs/docs/reference/functions/norm.md new file mode 100644 index 0000000..a531a95 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/norm.md @@ -0,0 +1,59 @@ + + +# Function norm + +Calculate the norm of a number, vector or matrix. + +The second parameter p is optional. If not provided, it defaults to 2. + + +## Syntax + +```js +math.norm(x) +math.norm(x, p) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | Value for which to calculate the norm +`p` | number | BigNumber | string | Vector space. Supported numbers include Infinity and -Infinity. Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm) Default value: 2. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | the p-norm + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.abs(-3.5) // returns 3.5 +math.norm(-3.5) // returns 3.5 + +math.norm(math.complex(3, -4)) // returns 5 + +math.norm([1, 2, -3], Infinity) // returns 3 +math.norm([1, 2, -3], -Infinity) // returns 1 + +math.norm([3, 4], 2) // returns 5 + +math.norm([[1, 2], [3, 4]], 1) // returns 6 +math.norm([[1, 2], [3, 4]], 'inf') // returns 7 +math.norm([[1, 2], [3, 4]], 'fro') // returns 5.477225575051661 +``` + + +## See also + +[abs](abs.md), +[hypot](hypot.md) diff --git a/node_modules/mathjs/docs/reference/functions/not.md b/node_modules/mathjs/docs/reference/functions/not.md new file mode 100644 index 0000000..3ab29d4 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/not.md @@ -0,0 +1,50 @@ + + +# Function not + +Logical `not`. Flips boolean value of a given parameter. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.not(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | First value to check + +### Returns + +Type | Description +---- | ----------- +boolean | Array | Matrix | Returns true when input is a zero or empty value. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.not(2) // returns false +math.not(0) // returns true +math.not(true) // returns false + +a = [2, -7, 0] +math.not(a) // returns [false, false, true] +``` + + +## See also + +[and](and.md), +[or](or.md), +[xor](xor.md) diff --git a/node_modules/mathjs/docs/reference/functions/nthRoot.md b/node_modules/mathjs/docs/reference/functions/nthRoot.md new file mode 100644 index 0000000..be8b7ad --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/nthRoot.md @@ -0,0 +1,53 @@ + + +# Function nthRoot + +Calculate the nth root of a value. +The principal nth root of a positive real number A, is the positive real +solution of the equation + + x^root = A + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.nthRoot(a) +math.nthRoot(a, root) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a` | number | BigNumber | Array | Matrix | Complex | Value for which to calculate the nth root +`root` | number | BigNumber | The root. Default value: 2. + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Returns the nth root of `a` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.nthRoot(9, 2) // returns 3, as 3^2 == 9 +math.sqrt(9) // returns 3, as 3^2 == 9 +math.nthRoot(64, 3) // returns 4, as 4^3 == 64 +``` + + +## See also + +[sqrt](sqrt.md), +[pow](pow.md) diff --git a/node_modules/mathjs/docs/reference/functions/nthRoots.md b/node_modules/mathjs/docs/reference/functions/nthRoots.md new file mode 100644 index 0000000..f655845 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/nthRoots.md @@ -0,0 +1,58 @@ + + +# Function nthRoots + +Calculate the nth roots of a value. +An nth root of a positive real number A, +is a positive real solution of the equation "x^root = A". +This function returns an array of complex values. + + +## Syntax + +```js +math.nthRoots(x) +math.nthRoots(x, root) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Number to be rounded + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Rounded value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.nthRoots(1) +// returns [ +// {re: 1, im: 0}, +// {re: -1, im: 0} +// ] +nthRoots(1, 3) +// returns [ +// { re: 1, im: 0 }, +// { re: -0.4999999999999998, im: 0.8660254037844387 }, +// { re: -0.5000000000000004, im: -0.8660254037844385 } +] +``` + + +## See also + +[nthRoot](nthRoot.md), +[pow](pow.md), +[sqrt](sqrt.md) diff --git a/node_modules/mathjs/docs/reference/functions/number.md b/node_modules/mathjs/docs/reference/functions/number.md new file mode 100644 index 0000000..61bc017 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/number.md @@ -0,0 +1,49 @@ + + +# Function number + +Create a number or convert a string, boolean, or unit to a number. +When value is a matrix, all elements will be converted to number. + + +## Syntax + +```js +math.number(value) +math.number(unit, valuelessUnit) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null | Value to be converted +`valuelessUnit` | Unit | string | A valueless unit, used to convert a unit to a number + +### Returns + +Type | Description +---- | ----------- +number | Array | Matrix | The created number + + +## Examples + +```js +math.number(2) // returns number 2 +math.number('7.2') // returns number 7.2 +math.number(true) // returns number 1 +math.number([true, false, true, true]) // returns [1, 0, 1, 1] +math.number(math.unit('52cm'), 'm') // returns 0.52 +``` + + +## See also + +[bignumber](bignumber.md), +[boolean](boolean.md), +[complex](complex.md), +[index](index.md), +[matrix](matrix.md), +[string](string.md), +[unit](unit.md) diff --git a/node_modules/mathjs/docs/reference/functions/numeric.md b/node_modules/mathjs/docs/reference/functions/numeric.md new file mode 100644 index 0000000..fa58b35 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/numeric.md @@ -0,0 +1,52 @@ + + +# Function numeric + +Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction. + + +## Syntax + +```js +math.numeric(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | string | number | BigNumber | Fraction | A numeric value or a string containing a numeric value +`outputType` | string | Desired numeric output type. Available values: 'number', 'BigNumber', or 'Fraction' + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Returns an instance of the numeric in the requested type + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.numeric('4') // returns number 4 +math.numeric('4', 'number') // returns number 4 +math.numeric('4', 'BigNumber') // returns BigNumber 4 +math.numeric('4', 'Fraction') // returns Fraction 4 +math.numeric(4, 'Fraction') // returns Fraction 4 +math.numeric(math.fraction(2, 5), 'number') // returns number 0.4 +``` + + +## See also + +[number](number.md), +[fraction](fraction.md), +[bignumber](bignumber.md), +[string](string.md), +[format](format.md) diff --git a/node_modules/mathjs/docs/reference/functions/oct.md b/node_modules/mathjs/docs/reference/functions/oct.md new file mode 100644 index 0000000..71d87b5 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/oct.md @@ -0,0 +1,45 @@ + + +# Function oct + +Format a number as octal. + + +## Syntax + +```js +math.oct(value) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | number | Value to be stringified +`wordSize` | number | Optional word size (see `format`) + +### Returns + +Type | Description +---- | ----------- +string | The formatted value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +//the following outputs "0o70" +math.oct(56) +``` + + +## See also + +[bin](bin.md), +[hex](hex.md) diff --git a/node_modules/mathjs/docs/reference/functions/ones.md b/node_modules/mathjs/docs/reference/functions/ones.md new file mode 100644 index 0000000..5e372d8 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/ones.md @@ -0,0 +1,59 @@ + + +# Function ones + +Create a matrix filled with ones. The created matrix can have one or +multiple dimensions. + + +## Syntax + +```js +math.ones(m) +math.ones(m, format) +math.ones(m, n) +math.ones(m, n, format) +math.ones([m, n]) +math.ones([m, n], format) +math.ones([m, n, p, ...]) +math.ones([m, n, p, ...], format) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`size` | ...number | Array | The size of each dimension of the matrix +`format` | string | The Matrix storage format + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | number | A matrix filled with ones + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.ones(3) // returns [1, 1, 1] +math.ones(3, 2) // returns [[1, 1], [1, 1], [1, 1]] +math.ones(3, 2, 'dense') // returns Dense Matrix [[1, 1], [1, 1], [1, 1]] + +const A = [[1, 2, 3], [4, 5, 6]] +math.ones(math.size(A)) // returns [[1, 1, 1], [1, 1, 1]] +``` + + +## See also + +[zeros](zeros.md), +[identity](identity.md), +[size](size.md), +[range](range.md) diff --git a/node_modules/mathjs/docs/reference/functions/or.md b/node_modules/mathjs/docs/reference/functions/or.md new file mode 100644 index 0000000..2e565e2 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/or.md @@ -0,0 +1,53 @@ + + +# Function or + +Logical `or`. Test if at least one value is defined with a nonzero/nonempty value. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.or(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | First value to check +`y` | number | BigNumber | Complex | Unit | Array | Matrix | Second value to check + +### Returns + +Type | Description +---- | ----------- +boolean | Array | Matrix | Returns true when one of the inputs is defined with a nonzero/nonempty value. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.or(2, 4) // returns true + +a = [2, 5, 0] +b = [0, 22, 0] +c = 0 + +math.or(a, b) // returns [true, true, false] +math.or(b, c) // returns [false, true, false] +``` + + +## See also + +[and](and.md), +[not](not.md), +[xor](xor.md) diff --git a/node_modules/mathjs/docs/reference/functions/parse.md b/node_modules/mathjs/docs/reference/functions/parse.md new file mode 100644 index 0000000..5370b95 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/parse.md @@ -0,0 +1,56 @@ + + +# Function parse + +Parse an expression. Returns a node tree, which can be evaluated by +invoking node.evaluate(). + +Note the evaluating arbitrary expressions may involve security risks, +see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information. + + +## Syntax + +```js +math.parse(expr) +math.parse(expr, options) +math.parse([expr1, expr2, expr3, ...]) +math.parse([expr1, expr2, expr3, ...], options) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`expr` | string | string[] | Matrix | Expression to be parsed +`options` | {nodes: Object<string, Node>} | Available options:
    - `nodes` a set of custom nodes + +### Returns + +Type | Description +---- | ----------- +Node | Node[] | node + + +## Examples + +```js +const node1 = math.parse('sqrt(3^2 + 4^2)') +node1.compile().evaluate() // 5 + +let scope = {a:3, b:4} +const node2 = math.parse('a * b') // 12 +const code2 = node2.compile() +code2.evaluate(scope) // 12 +scope.a = 5 +code2.evaluate(scope) // 20 + +const nodes = math.parse(['a = 3', 'b = 4', 'a * b']) +nodes[2].compile().evaluate() // 12 +``` + + +## See also + +[evaluate](evaluate.md), +[compile](compile.md) diff --git a/node_modules/mathjs/docs/reference/functions/parser.md b/node_modules/mathjs/docs/reference/functions/parser.md new file mode 100644 index 0000000..1027709 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/parser.md @@ -0,0 +1,70 @@ + + +# Function parser + +Create a parser. The function creates a new `math.Parser` object. + + +## Syntax + +```js +math.parser() +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- + + +### Returns + +Type | Description +---- | ----------- +Parser | Parser + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const parser = new math.parser() + +// evaluate expressions +const a = parser.evaluate('sqrt(3^2 + 4^2)') // 5 +const b = parser.evaluate('sqrt(-4)') // 2i +const c = parser.evaluate('2 inch in cm') // 5.08 cm +const d = parser.evaluate('cos(45 deg)') // 0.7071067811865476 + +// define variables and functions +parser.evaluate('x = 7 / 2') // 3.5 +parser.evaluate('x + 3') // 6.5 +parser.evaluate('f(x, y) = x^y') // f(x, y) +parser.evaluate('f(2, 3)') // 8 + +// get and set variables and functions +const x = parser.get('x') // 7 +const f = parser.get('f') // function +const g = f(3, 2) // 9 +parser.set('h', 500) +const i = parser.evaluate('h / 2') // 250 +parser.set('hello', function (name) { + return 'hello, ' + name + '!' +}) +parser.evaluate('hello("user")') // "hello, user!" + +// clear defined functions and variables +parser.clear() +``` + + +## See also + +[evaluate](evaluate.md), +[compile](compile.md), +[parse](parse.md) diff --git a/node_modules/mathjs/docs/reference/functions/partitionSelect.md b/node_modules/mathjs/docs/reference/functions/partitionSelect.md new file mode 100644 index 0000000..1ab1e01 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/partitionSelect.md @@ -0,0 +1,53 @@ + + +# Function partitionSelect + +Partition-based selection of an array or 1D matrix. +Will find the kth smallest value, and mutates the input array. +Uses Quickselect. + + +## Syntax + +```js +math.partitionSelect(x, k) +math.partitionSelect(x, k, compare) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Matrix | Array | A one dimensional matrix or array to sort +`k` | Number | The kth smallest value to be retrieved zero-based index +`compare` | Function | 'asc' | 'desc' | An optional comparator function. The function is called as `compare(a, b)`, and must return 1 when a > b, -1 when a < b, and 0 when a == b. Default value: 'asc'. + +### Returns + +Type | Description +---- | ----------- +* | Returns the kth lowest value. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.partitionSelect([5, 10, 1], 2) // returns 10 +math.partitionSelect(['C', 'B', 'A', 'D'], 1) // returns 'B' + +function sortByLength (a, b) { + return a.length - b.length +} +math.partitionSelect(['Langdon', 'Tom', 'Sara'], 2, sortByLength) // returns 'Langdon' +``` + + +## See also + +[sort](sort.md) diff --git a/node_modules/mathjs/docs/reference/functions/permutations.md b/node_modules/mathjs/docs/reference/functions/permutations.md new file mode 100644 index 0000000..46853a5 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/permutations.md @@ -0,0 +1,51 @@ + + +# Function permutations + +Compute the number of ways of obtaining an ordered subset of `k` elements +from a set of `n` elements. + +Permutations only takes integer arguments. +The following condition must be enforced: k <= n. + + +## Syntax + +```js +math.permutations(n) +math.permutations(n, k) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`n` | number | BigNumber | The number of objects in total +`k` | number | BigNumber | The number of objects in the subset + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | The number of permutations + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.permutations(5) // 120 +math.permutations(5, 3) // 60 +``` + + +## See also + +[combinations](combinations.md), +[combinationsWithRep](combinationsWithRep.md), +[factorial](factorial.md) diff --git a/node_modules/mathjs/docs/reference/functions/pickRandom.md b/node_modules/mathjs/docs/reference/functions/pickRandom.md new file mode 100644 index 0000000..a945714 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/pickRandom.md @@ -0,0 +1,59 @@ + + +# Function pickRandom + +Random pick one or more values from a one dimensional array. +Array elements are picked using a random function with uniform or weighted distribution. + + +## Syntax + +```js +math.pickRandom(array) +math.pickRandom(array, number) +math.pickRandom(array, weights) +math.pickRandom(array, number, weights) +math.pickRandom(array, weights, number) +math.pickRandom(array, { weights, number, elementWise }) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`array` | Array | Matrix | A one dimensional array +`number` | Int | An int or float +`weights` | Array | Matrix | An array of ints or floats + +### Returns + +Type | Description +---- | ----------- +number | Array | Returns a single random value from array when number is 1 or undefined. Returns an array with the configured number of elements when number is > 1. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.pickRandom([3, 6, 12, 2]) // returns one of the values in the array +math.pickRandom([3, 6, 12, 2], 2) // returns an array of two of the values in the array +math.pickRandom([3, 6, 12, 2], { number: 2 }) // returns an array of two of the values in the array +math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1]) // returns one of the values in the array with weighted distribution +math.pickRandom([3, 6, 12, 2], 2, [1, 3, 2, 1]) // returns an array of two of the values in the array with weighted distribution +math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1], 2) // returns an array of two of the values in the array with weighted distribution + +math.pickRandom([{x: 1.0, y: 2.0}, {x: 1.1, y: 2.0}], { elementWise: false }) + // returns one of the items in the array +``` + + +## See also + +[random](random.md), +[randomInt](randomInt.md) diff --git a/node_modules/mathjs/docs/reference/functions/pow.md b/node_modules/mathjs/docs/reference/functions/pow.md new file mode 100644 index 0000000..bd75d21 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/pow.md @@ -0,0 +1,59 @@ + + +# Function pow + +Calculates the power of x to y, `x ^ y`. +Matrix exponentiation is supported for square matrices `x`, and positive +integer exponents `y`. + +For cubic roots of negative numbers, the function returns the principal +root by default. In order to let the function return the real root, +math.js can be configured with `math.config({predictable: true})`. +To retrieve all cubic roots of a value, use `math.cbrt(x, true)`. + + +## Syntax + +```js +math.pow(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | The base +`y` | number | BigNumber | Complex | The exponent + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | The value of `x` to the power `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.pow(2, 3) // returns number 8 + +const a = math.complex(2, 3) +math.pow(a, 2) // returns Complex -5 + 12i + +const b = [[1, 2], [4, 3]] +math.pow(b, 2) // returns Array [[9, 8], [16, 17]] +``` + + +## See also + +[multiply](multiply.md), +[sqrt](sqrt.md), +[cbrt](cbrt.md), +[nthRoot](nthRoot.md) diff --git a/node_modules/mathjs/docs/reference/functions/print.md b/node_modules/mathjs/docs/reference/functions/print.md new file mode 100644 index 0000000..442f2d1 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/print.md @@ -0,0 +1,64 @@ + + +# Function print + +Interpolate values into a string template. + + +## Syntax + +```js +math.print(template, values) +math.print(template, values, precision) +math.print(template, values, options) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`template` | string | A string containing variable placeholders. +`values` | Object | Array | Matrix | An object or array containing variables which will be filled in in the template. +`options` | number | Object | Formatting options, or the number of digits to format numbers. See function math.format for a description of all options. + +### Returns + +Type | Description +---- | ----------- +string | Interpolated string + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +// the following outputs: 'Lucy is 5 years old' +math.print('Lucy is $age years old', {age: 5}) + +// the following outputs: 'The value of pi is 3.141592654' +math.print('The value of pi is $pi', {pi: math.pi}, 10) + +// the following outputs: 'hello Mary! The date is 2013-03-23' +math.print('Hello $user.name! The date is $date', { + user: { + name: 'Mary', + }, + date: new Date(2013, 2, 23).toISOString().substring(0, 10) +}) + +// the following outputs: 'My favorite fruits are apples and bananas !' +math.print('My favorite fruits are $0 and $1 !', [ + 'apples', + 'bananas' +]) +``` + + +## See also + +[format](format.md) diff --git a/node_modules/mathjs/docs/reference/functions/prod.md b/node_modules/mathjs/docs/reference/functions/prod.md new file mode 100644 index 0000000..3c2812c --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/prod.md @@ -0,0 +1,55 @@ + + +# Function prod + +Compute the product of a matrix or a list with values. +In case of a (multi dimensional) array or matrix, the sum of all +elements will be calculated. + + +## Syntax + +```js +math.prod(a, b, c, ...) +math.prod(A) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... * | A single matrix or or multiple scalar values + +### Returns + +Type | Description +---- | ----------- +* | The product of all values + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.multiply(2, 3) // returns 6 +math.prod(2, 3) // returns 6 +math.prod(2, 3, 4) // returns 24 +math.prod([2, 3, 4]) // returns 24 +math.prod([[2, 5], [4, 3]]) // returns 120 +``` + + +## See also + +[mean](mean.md), +[median](median.md), +[min](min.md), +[max](max.md), +[sum](sum.md), +[std](std.md), +[variance](variance.md) diff --git a/node_modules/mathjs/docs/reference/functions/qr.md b/node_modules/mathjs/docs/reference/functions/qr.md new file mode 100644 index 0000000..327f93c --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/qr.md @@ -0,0 +1,65 @@ + + +# Function qr + +Calculate the Matrix QR decomposition. Matrix `A` is decomposed in +two matrices (`Q`, `R`) where `Q` is an +orthogonal matrix and `R` is an upper triangular matrix. + + +## Syntax + +```js +math.qr(A) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`A` | Matrix | Array | A two dimensional matrix or array for which to get the QR decomposition. + +### Returns + +Type | Description +---- | ----------- +{Q: Array | Matrix, R: Array | Matrix} | Q: the orthogonal matrix and R: the upper triangular matrix + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const m = [ + [1, -1, 4], + [1, 4, -2], + [1, 4, 2], + [1, -1, 0] +] +const result = math.qr(m) +// r = { +// Q: [ +// [0.5, -0.5, 0.5], +// [0.5, 0.5, -0.5], +// [0.5, 0.5, 0.5], +// [0.5, -0.5, -0.5], +// ], +// R: [ +// [2, 3, 2], +// [0, 5, -2], +// [0, 0, 4], +// [0, 0, 0] +// ] +// } +``` + + +## See also + +[lup](lup.md), +[lusolve](lusolve.md) diff --git a/node_modules/mathjs/docs/reference/functions/quantileSeq.md b/node_modules/mathjs/docs/reference/functions/quantileSeq.md new file mode 100644 index 0000000..c3518fb --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/quantileSeq.md @@ -0,0 +1,62 @@ + + +# Function quantileSeq + +Compute the prob order quantile of a matrix or a list with values. +The sequence is sorted and the middle value is returned. +Supported types of sequence values are: Number, BigNumber, Unit +Supported types of probability are: Number, BigNumber + +In case of a (multi dimensional) array or matrix, the prob order quantile +of all elements will be calculated. + + +## Syntax + +```js +math.quantileSeq(A, prob[, sorted]) +math.quantileSeq(A, [prob1, prob2, ...][, sorted]) +math.quantileSeq(A, N[, sorted]) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`data` | Array, Matrix | A single matrix or Array +`probOrN` | Number, BigNumber, Array | prob is the order of the quantile, while N is the amount of evenly distributed steps of probabilities; only one of these options can be provided +`sorted` | Boolean | =false is data sorted in ascending order + +### Returns + +Type | Description +---- | ----------- +Number, BigNumber, Unit, Array | Quantile(s) + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.quantileSeq([3, -1, 5, 7], 0.5) // returns 4 +math.quantileSeq([3, -1, 5, 7], [1/3, 2/3]) // returns [3, 5] +math.quantileSeq([3, -1, 5, 7], 2) // returns [3, 5] +math.quantileSeq([-1, 3, 5, 7], 0.5, true) // returns 4 +``` + + +## See also + +[median](median.md), +[mean](mean.md), +[min](min.md), +[max](max.md), +[sum](sum.md), +[prod](prod.md), +[std](std.md), +[variance](variance.md) diff --git a/node_modules/mathjs/docs/reference/functions/random.md b/node_modules/mathjs/docs/reference/functions/random.md new file mode 100644 index 0000000..3d7a27f --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/random.md @@ -0,0 +1,54 @@ + + +# Function random + +Return a random number larger or equal to `min` and smaller than `max` +using a uniform distribution. + + +## Syntax + +```js +math.random() // generate a random number between 0 and 1 +math.random(max) // generate a random number between 0 and max +math.random(min, max) // generate a random number between min and max +math.random(size) // generate a matrix with random numbers between 0 and 1 +math.random(size, max) // generate a matrix with random numbers between 0 and max +math.random(size, min, max) // generate a matrix with random numbers between min and max +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`size` | Array | Matrix | If provided, an array or matrix with given size and filled with random values is returned +`min` | number | Minimum boundary for the random value, included +`max` | number | Maximum boundary for the random value, excluded + +### Returns + +Type | Description +---- | ----------- +number | Array | Matrix | A random number + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.random() // returns a random number between 0 and 1 +math.random(100) // returns a random number between 0 and 100 +math.random(30, 40) // returns a random number between 30 and 40 +math.random([2, 3]) // returns a 2x3 matrix with random numbers between 0 and 1 +``` + + +## See also + +[randomInt](randomInt.md), +[pickRandom](pickRandom.md) diff --git a/node_modules/mathjs/docs/reference/functions/randomInt.md b/node_modules/mathjs/docs/reference/functions/randomInt.md new file mode 100644 index 0000000..7706888 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/randomInt.md @@ -0,0 +1,53 @@ + + +# Function randomInt + +Return a random integer number larger or equal to `min` and smaller than `max` +using a uniform distribution. + + +## Syntax + +```js +math.randomInt() // generate a random integer between 0 and 1 +math.randomInt(max) // generate a random integer between 0 and max +math.randomInt(min, max) // generate a random integer between min and max +math.randomInt(size) // generate a matrix with random integer between 0 and 1 +math.randomInt(size, max) // generate a matrix with random integer between 0 and max +math.randomInt(size, min, max) // generate a matrix with random integer between min and max +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`size` | Array | Matrix | If provided, an array or matrix with given size and filled with random values is returned +`min` | number | Minimum boundary for the random value, included +`max` | number | Maximum boundary for the random value, excluded + +### Returns + +Type | Description +---- | ----------- +number | Array | Matrix | A random integer value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.randomInt(100) // returns a random integer between 0 and 100 +math.randomInt(30, 40) // returns a random integer between 30 and 40 +math.randomInt([2, 3]) // returns a 2x3 matrix with random integers between 0 and 1 +``` + + +## See also + +[random](random.md), +[pickRandom](pickRandom.md) diff --git a/node_modules/mathjs/docs/reference/functions/range.md b/node_modules/mathjs/docs/reference/functions/range.md new file mode 100644 index 0000000..79c9295 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/range.md @@ -0,0 +1,70 @@ + + +# Function range + +Create an array from a range. +By default, the range end is excluded. This can be customized by providing +an extra parameter `includeEnd`. + + +## Syntax + +```js +math.range(str [, includeEnd]) // Create a range from a string, + // where the string contains the + // start, optional step, and end, + // separated by a colon. +math.range(start, end [, includeEnd]) // Create a range with start and + // end and a step size of 1. +math.range(start, end, step [, includeEnd]) // Create a range with start, step, + // and end. +``` + +### Where + +- `str: string` + A string 'start:end' or 'start:step:end' +- `start: {number | BigNumber}` + Start of the range +- `end: number | BigNumber` + End of the range, excluded by default, included when parameter includeEnd=true +- `step: number | BigNumber` + Step size. Default value is 1. +- `includeEnd: boolean` + Option to specify whether to include the end or not. False by default. + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | * | Parameters describing the ranges `start`, `end`, and optional `step`. + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | range + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.range(2, 6) // [2, 3, 4, 5] +math.range(2, -3, -1) // [2, 1, 0, -1, -2] +math.range('2:1:6') // [2, 3, 4, 5] +math.range(2, 6, true) // [2, 3, 4, 5, 6] +``` + + +## See also + +[ones](ones.md), +[zeros](zeros.md), +[size](size.md), +[subset](subset.md) diff --git a/node_modules/mathjs/docs/reference/functions/rationalize.md b/node_modules/mathjs/docs/reference/functions/rationalize.md new file mode 100644 index 0000000..51fa391 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/rationalize.md @@ -0,0 +1,68 @@ + + +# Function rationalize + +Transform a rationalizable expression in a rational fraction. +If rational fraction is one variable polynomial then converts +the numerator and denominator in canonical form, with decreasing +exponents, returning the coefficients of numerator. + + +## Syntax + +```js +rationalize(expr) +rationalize(expr, detailed) +rationalize(expr, scope) +rationalize(expr, scope, detailed) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`expr` | Node | string | The expression to check if is a polynomial expression +`optional` | Object | boolean | scope of expression or true for already evaluated rational expression at input +`detailed` | Boolean | optional True if return an object, false if return expression node (default) + +### Returns + +Type | Description +---- | ----------- +Object | Node | The rational polynomial of `expr` or an object `{expression, numerator, denominator, variables, coefficients}`, where `expression` is a `Node` with the node simplified expression, `numerator` is a `Node` with the simplified numerator of expression, `denominator` is a `Node` or `boolean` with the simplified denominator or `false` (if there is no denominator), `variables` is an array with variable names, and `coefficients` is an array with coefficients of numerator sorted by increased exponent {Expression Node} node simplified expression + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.rationalize('sin(x)+y') + // Error: There is an unsolved function call +math.rationalize('2x/y - y/(x+1)') + // (2*x^2-y^2+2*x)/(x*y+y) +math.rationalize('(2x+1)^6') + // 64*x^6+192*x^5+240*x^4+160*x^3+60*x^2+12*x+1 +math.rationalize('2x/( (2x-1) / (3x+2) ) - 5x/ ( (3x+4) / (2x^2-5) ) + 3') + // -20*x^4+28*x^3+104*x^2+6*x-12)/(6*x^2+5*x-4) +math.rationalize('x/(1-x)/(x-2)/(x-3)/(x-4) + 2x/ ( (1-2x)/(2-3x) )/ ((3-4x)/(4-5x) )') = + // (-30*x^7+344*x^6-1506*x^5+3200*x^4-3472*x^3+1846*x^2-381*x)/ + // (-8*x^6+90*x^5-383*x^4+780*x^3-797*x^2+390*x-72) + +math.rationalize('x+x+x+y',{y:1}) // 3*x+1 +math.rationalize('x+x+x+y',{}) // 3*x+y + +const ret = math.rationalize('x+x+x+y',{},true) + // ret.expression=3*x+y, ret.variables = ["x","y"] +const ret = math.rationalize('-2+5x^2',{},true) + // ret.expression=5*x^2-2, ret.variables = ["x"], ret.coefficients=[-2,0,5] +``` + + +## See also + +[simplify](simplify.md) diff --git a/node_modules/mathjs/docs/reference/functions/re.md b/node_modules/mathjs/docs/reference/functions/re.md new file mode 100644 index 0000000..95fc28e --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/re.md @@ -0,0 +1,53 @@ + + +# Function re + +Get the real part of a complex number. +For a complex number `a + bi`, the function returns `a`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.re(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | A complex number or array with complex numbers + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Array | Matrix | The real part of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const a = math.complex(2, 3) +math.re(a) // returns number 2 +math.im(a) // returns number 3 + +math.re(math.complex('-5.2i')) // returns number 0 +math.re(math.complex(2.4)) // returns number 2.4 +``` + + +## See also + +[im](im.md), +[conj](conj.md), +[abs](abs.md), +[arg](arg.md) diff --git a/node_modules/mathjs/docs/reference/functions/reshape.md b/node_modules/mathjs/docs/reference/functions/reshape.md new file mode 100644 index 0000000..97dee1c --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/reshape.md @@ -0,0 +1,60 @@ + + +# Function reshape + +Reshape a multi dimensional array to fit the specified dimensions + + +## Syntax + +```js +math.reshape(x, sizes) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Array | Matrix | * | Matrix to be reshaped +`sizes` | number[] | One dimensional array with integral sizes for each dimension. One -1 is allowed as wildcard, which calculates this dimension automatically. + +### Returns + +Type | Description +---- | ----------- +* | Array | Matrix | A reshaped clone of matrix `x` + + +### Throws + +Type | Description +---- | ----------- +TypeError | If `sizes` does not contain solely integers +DimensionError | If the product of the new dimension sizes does not equal that of the old ones + +## Examples + +```js + math.reshape([1, 2, 3, 4, 5, 6], [2, 3]) + // returns Array [[1, 2, 3], [4, 5, 6]] + + math.reshape([[1, 2], [3, 4]], [1, 4]) + // returns Array [[1, 2, 3, 4]] + + math.reshape([[1, 2], [3, 4]], [4]) + // returns Array [1, 2, 3, 4] + + const x = math.matrix([1, 2, 3, 4, 5, 6, 7, 8]) + math.reshape(x, [2, 2, 2]) + // returns Matrix [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + +math.reshape([1, 2, 3, 4], [-1, 2]) +// returns Matrix [[1, 2], [3, 4]] +``` + + +## See also + +[size](size.md), +[squeeze](squeeze.md), +[resize](resize.md) diff --git a/node_modules/mathjs/docs/reference/functions/resize.md b/node_modules/mathjs/docs/reference/functions/resize.md new file mode 100644 index 0000000..40fc149 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/resize.md @@ -0,0 +1,51 @@ + + +# Function resize + +Resize a matrix + + +## Syntax + +```js +math.resize(x, size) +math.resize(x, size, defaultValue) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Array | Matrix | * | Matrix to be resized +`size` | Array | Matrix | One dimensional array with numbers +`defaultValue` | number | string | Zero by default, except in case of a string, in that case defaultValue = ' ' Default value: 0. + +### Returns + +Type | Description +---- | ----------- +* | Array | Matrix | A resized clone of matrix `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.resize([1, 2, 3, 4, 5], [3]) // returns Array [1, 2, 3] +math.resize([1, 2, 3], [5], 0) // returns Array [1, 2, 3, 0, 0] +math.resize(2, [2, 3], 0) // returns Matrix [[2, 0, 0], [0, 0, 0]] +math.resize("hello", [8], "!") // returns string 'hello!!!' +``` + + +## See also + +[size](size.md), +[squeeze](squeeze.md), +[subset](subset.md), +[reshape](reshape.md) diff --git a/node_modules/mathjs/docs/reference/functions/resolve.md b/node_modules/mathjs/docs/reference/functions/resolve.md new file mode 100644 index 0000000..f7cc590 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/resolve.md @@ -0,0 +1,46 @@ + + +# Function resolve + +resolve(expr, scope) replaces variable nodes with their scoped values + + +## Syntax + +```js +resolve(expr, scope) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`node` | Node | The expression tree to be simplified +`scope` | Object | Scope specifying variables to be resolved + +### Returns + +Type | Description +---- | ----------- +Node | Returns `node` with variables recursively substituted. + + +### Throws + +Type | Description +---- | ----------- +ReferenceError | If there is a cyclic dependency among the variables in `scope`, resolution is impossible and a ReferenceError is thrown. + +## Examples + +```js +math.resolve('x + y', {x:1, y:2}) // Node {1 + 2} +math.resolve(math.parse('x+y'), {x:1, y:2}) // Node {1 + 2} +math.simplify('x+y', {x:2, y:'x+x'}).toString() // "6" +``` + + +## See also + +[simplify](simplify.md), +[evaluate](evaluate.md) diff --git a/node_modules/mathjs/docs/reference/functions/rightArithShift.md b/node_modules/mathjs/docs/reference/functions/rightArithShift.md new file mode 100644 index 0000000..bf62d95 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/rightArithShift.md @@ -0,0 +1,52 @@ + + +# Function rightArithShift + +Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`. +For matrices, the function is evaluated element wise. +For units, the function is evaluated on the best prefix base. + + +## Syntax + +```js +math.rightArithShift(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Array | Matrix | Value to be shifted +`y` | number | BigNumber | Amount of shifts + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Array | Matrix | `x` sign-filled shifted right `y` times + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.rightArithShift(4, 2) // returns number 1 + +math.rightArithShift([16, -32, 64], 4) // returns Array [1, -2, 3] +``` + + +## See also + +[bitAnd](bitAnd.md), +[bitNot](bitNot.md), +[bitOr](bitOr.md), +[bitXor](bitXor.md), +[rightArithShift](rightArithShift.md), +[rightLogShift](rightLogShift.md) diff --git a/node_modules/mathjs/docs/reference/functions/rightLogShift.md b/node_modules/mathjs/docs/reference/functions/rightLogShift.md new file mode 100644 index 0000000..a268a25 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/rightLogShift.md @@ -0,0 +1,52 @@ + + +# Function rightLogShift + +Bitwise right logical shift of value x by y number of bits, `x >>> y`. +For matrices, the function is evaluated element wise. +For units, the function is evaluated on the best prefix base. + + +## Syntax + +```js +math.rightLogShift(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Array | Matrix | Value to be shifted +`y` | number | Amount of shifts + +### Returns + +Type | Description +---- | ----------- +number | Array | Matrix | `x` zero-filled shifted right `y` times + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.rightLogShift(4, 2) // returns number 1 + +math.rightLogShift([16, -32, 64], 4) // returns Array [1, 2, 3] +``` + + +## See also + +[bitAnd](bitAnd.md), +[bitNot](bitNot.md), +[bitOr](bitOr.md), +[bitXor](bitXor.md), +[leftShift](leftShift.md), +[rightLogShift](rightLogShift.md) diff --git a/node_modules/mathjs/docs/reference/functions/rotate.md b/node_modules/mathjs/docs/reference/functions/rotate.md new file mode 100644 index 0000000..e7ace0f --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/rotate.md @@ -0,0 +1,53 @@ + + +# Function rotate + +Rotate a vector of size 1x2 counter-clockwise by a given angle +Rotate a vector of size 1x3 counter-clockwise by a given angle around the given axis + + +## Syntax + +```js +math.rotate(w, theta) +math.rotate(w, theta, v) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`w` | Array | Matrix | Vector to rotate +`theta` | number | BigNumber | Complex | Unit | Rotation angle +`v` | Array | Matrix | Rotation axis + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | Multiplication of the rotation matrix and w + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.rotate([11, 12], math.pi / 2) // returns matrix([-12, 11]) +math.rotate(matrix([11, 12]), math.pi / 2) // returns matrix([-12, 11]) + +math.rotate([1, 0, 0], unit('90deg'), [0, 0, 1]) // returns matrix([0, 1, 0]) +math.rotate(matrix([1, 0, 0]), unit('90deg'), [0, 0, 1]) // returns matrix([0, 1, 0]) + +math.rotate([1, 0], math.complex(1 + i)) // returns matrix([cos(1 + i) - sin(1 + i), sin(1 + i) + cos(1 + i)]) +``` + + +## See also + +[matrix](matrix.md), +[rotationMatrix](rotationMatrix.md) diff --git a/node_modules/mathjs/docs/reference/functions/rotationMatrix.md b/node_modules/mathjs/docs/reference/functions/rotationMatrix.md new file mode 100644 index 0000000..34bca0d --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/rotationMatrix.md @@ -0,0 +1,57 @@ + + +# Function rotationMatrix + +Create a 2-dimensional counter-clockwise rotation matrix (2x2) for a given angle (expressed in radians). +Create a 2-dimensional counter-clockwise rotation matrix (3x3) by a given angle (expressed in radians) around a given axis (1x3). + + +## Syntax + +```js +math.rotationMatrix(theta) +math.rotationMatrix(theta, format) +math.rotationMatrix(theta, [v]) +math.rotationMatrix(theta, [v], format) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`theta` | number | BigNumber | Complex | Unit | Rotation angle +`v` | Array | Matrix | Rotation axis +`format` | string | Result Matrix storage format + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | Rotation matrix + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.rotationMatrix(math.pi / 2) // returns [[0, -1], [1, 0]] +math.rotationMatrix(math.bignumber(1)) // returns [[bignumber(cos(1)), bignumber(-sin(1))], [bignumber(sin(1)), bignumber(cos(1))]] +math.rotationMatrix(math.complex(1 + i)) // returns [[cos(1 + i), -sin(1 + i)], [sin(1 + i), cos(1 + i)]] +math.rotationMatrix(math.unit('1rad')) // returns [[cos(1), -sin(1)], [sin(1), cos(1)]] + +math.rotationMatrix(math.pi / 2, [0, 1, 0]) // returns [[0, 0, 1], [0, 1, 0], [-1, 0, 0]] +math.rotationMatrix(math.pi / 2, matrix([0, 1, 0])) // returns matrix([[0, 0, 1], [0, 1, 0], [-1, 0, 0]]) + +``` + + +## See also + +[matrix](matrix.md), +[cos](cos.md), +[sin](sin.md) diff --git a/node_modules/mathjs/docs/reference/functions/round.md b/node_modules/mathjs/docs/reference/functions/round.md new file mode 100644 index 0000000..c4d43dd --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/round.md @@ -0,0 +1,61 @@ + + +# Function round + +Round a value towards the nearest integer. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.round(x) +math.round(x, n) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Array | Matrix | Number to be rounded +`n` | number | BigNumber | Array | Number of decimals Default value: 0. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Array | Matrix | Rounded value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.round(3.22) // returns number 3 +math.round(3.82) // returns number 4 +math.round(-4.2) // returns number -4 +math.round(-4.7) // returns number -5 +math.round(3.22, 1) // returns number 3.2 +math.round(3.88, 1) // returns number 3.9 +math.round(-4.21, 1) // returns number -4.2 +math.round(-4.71, 1) // returns number -4.7 +math.round(math.pi, 3) // returns number 3.142 +math.round(123.45678, 2) // returns number 123.46 + +const c = math.complex(3.2, -2.7) +math.round(c) // returns Complex 3 - 3i + +math.round([3.2, 3.8, -4.7]) // returns Array [3, 4, -5] +``` + + +## See also + +[ceil](ceil.md), +[fix](fix.md), +[floor](floor.md) diff --git a/node_modules/mathjs/docs/reference/functions/row.md b/node_modules/mathjs/docs/reference/functions/row.md new file mode 100644 index 0000000..34d8a59 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/row.md @@ -0,0 +1,45 @@ + + +# Function row + +Return a row from a Matrix. + + +## Syntax + +```js +math.row(value, index) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | Array | Matrix | An array or matrix +`row` | number | The index of the row + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | The retrieved row + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +// get a row +const d = [[1, 2], [3, 4]] +math.row(d, 1) // returns [[3, 4]] +``` + + +## See also + +[column](column.md) diff --git a/node_modules/mathjs/docs/reference/functions/sec.md b/node_modules/mathjs/docs/reference/functions/sec.md new file mode 100644 index 0000000..f939d04 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/sec.md @@ -0,0 +1,47 @@ + + +# Function sec + +Calculate the secant of a value, defined as `sec(x) = 1/cos(x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.sec(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Secant of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.sec(2) // returns number -2.4029979617223822 +1 / math.cos(2) // returns number -2.4029979617223822 +``` + + +## See also + +[cos](cos.md), +[csc](csc.md), +[cot](cot.md) diff --git a/node_modules/mathjs/docs/reference/functions/sech.md b/node_modules/mathjs/docs/reference/functions/sech.md new file mode 100644 index 0000000..13582f4 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/sech.md @@ -0,0 +1,49 @@ + + +# Function sech + +Calculate the hyperbolic secant of a value, +defined as `sech(x) = 1 / cosh(x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.sech(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | Complex | Array | Matrix | Hyperbolic secant of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +// sech(x) = 1/ cosh(x) +math.sech(0.5) // returns 0.886818883970074 +1 / math.cosh(0.5) // returns 0.886818883970074 +``` + + +## See also + +[cosh](cosh.md), +[csch](csch.md), +[coth](coth.md) diff --git a/node_modules/mathjs/docs/reference/functions/setCartesian.md b/node_modules/mathjs/docs/reference/functions/setCartesian.md new file mode 100644 index 0000000..da3acfb --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/setCartesian.md @@ -0,0 +1,49 @@ + + +# Function setCartesian + +Create the cartesian product of two (multi)sets. +Multi-dimension arrays will be converted to single-dimension arrays +and the values will be sorted in ascending order before the operation. + + +## Syntax + +```js +math.setCartesian(set1, set2) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a1` | Array | Matrix | A (multi)set +`a2` | Array | Matrix | A (multi)set + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | The cartesian product of two (multi)sets + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.setCartesian([1, 2], [3, 4]) // returns [[1, 3], [1, 4], [2, 3], [2, 4]] +math.setCartesian([4, 3], [2, 1]) // returns [[3, 1], [3, 2], [4, 1], [4, 2]] +``` + + +## See also + +[setUnion](setUnion.md), +[setIntersect](setIntersect.md), +[setDifference](setDifference.md), +[setPowerset](setPowerset.md) diff --git a/node_modules/mathjs/docs/reference/functions/setDifference.md b/node_modules/mathjs/docs/reference/functions/setDifference.md new file mode 100644 index 0000000..7182764 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/setDifference.md @@ -0,0 +1,47 @@ + + +# Function setDifference + +Create the difference of two (multi)sets: every element of set1, that is not the element of set2. +Multi-dimension arrays will be converted to single-dimension arrays before the operation. + + +## Syntax + +```js +math.setDifference(set1, set2) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a1` | Array | Matrix | A (multi)set +`a2` | Array | Matrix | A (multi)set + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | The difference of two (multi)sets + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.setDifference([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2] +math.setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2] +``` + + +## See also + +[setUnion](setUnion.md), +[setIntersect](setIntersect.md), +[setSymDifference](setSymDifference.md) diff --git a/node_modules/mathjs/docs/reference/functions/setDistinct.md b/node_modules/mathjs/docs/reference/functions/setDistinct.md new file mode 100644 index 0000000..703d3dc --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/setDistinct.md @@ -0,0 +1,43 @@ + + +# Function setDistinct + +Collect the distinct elements of a multiset. +A multi-dimension array will be converted to a single-dimension array before the operation. + + +## Syntax + +```js +math.setDistinct(set) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a` | Array | Matrix | A multiset + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | A set containing the distinc elements of the multiset + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.setDistinct([1, 1, 1, 2, 2, 3]) // returns [1, 2, 3] +``` + + +## See also + +[setMultiplicity](setMultiplicity.md) diff --git a/node_modules/mathjs/docs/reference/functions/setIntersect.md b/node_modules/mathjs/docs/reference/functions/setIntersect.md new file mode 100644 index 0000000..b6e2f6a --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/setIntersect.md @@ -0,0 +1,46 @@ + + +# Function setIntersect + +Create the intersection of two (multi)sets. +Multi-dimension arrays will be converted to single-dimension arrays before the operation. + + +## Syntax + +```js +math.setIntersect(set1, set2) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a1` | Array | Matrix | A (multi)set +`a2` | Array | Matrix | A (multi)set + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | The intersection of two (multi)sets + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.setIntersect([1, 2, 3, 4], [3, 4, 5, 6]) // returns [3, 4] +math.setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [3, 4] +``` + + +## See also + +[setUnion](setUnion.md), +[setDifference](setDifference.md) diff --git a/node_modules/mathjs/docs/reference/functions/setIsSubset.md b/node_modules/mathjs/docs/reference/functions/setIsSubset.md new file mode 100644 index 0000000..ee64402 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/setIsSubset.md @@ -0,0 +1,47 @@ + + +# Function setIsSubset + +Check whether a (multi)set is a subset of another (multi)set. (Every element of set1 is the element of set2.) +Multi-dimension arrays will be converted to single-dimension arrays before the operation. + + +## Syntax + +```js +math.setIsSubset(set1, set2) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a1` | Array | Matrix | A (multi)set +`a2` | Array | Matrix | A (multi)set + +### Returns + +Type | Description +---- | ----------- +boolean | true | false + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.setIsSubset([1, 2], [3, 4, 5, 6]) // returns false +math.setIsSubset([3, 4], [3, 4, 5, 6]) // returns true +``` + + +## See also + +[setUnion](setUnion.md), +[setIntersect](setIntersect.md), +[setDifference](setDifference.md) diff --git a/node_modules/mathjs/docs/reference/functions/setMultiplicity.md b/node_modules/mathjs/docs/reference/functions/setMultiplicity.md new file mode 100644 index 0000000..9b6decb --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/setMultiplicity.md @@ -0,0 +1,46 @@ + + +# Function setMultiplicity + +Count the multiplicity of an element in a multiset. +A multi-dimension array will be converted to a single-dimension array before the operation. + + +## Syntax + +```js +math.setMultiplicity(element, set) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`e` | number | BigNumber | Fraction | Complex | An element in the multiset +`a` | Array | Matrix | A multiset + +### Returns + +Type | Description +---- | ----------- +number | The number of how many times the multiset contains the element + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.setMultiplicity(1, [1, 2, 2, 4]) // returns 1 +math.setMultiplicity(2, [1, 2, 2, 4]) // returns 2 +``` + + +## See also + +[setDistinct](setDistinct.md), +[setSize](setSize.md) diff --git a/node_modules/mathjs/docs/reference/functions/setPowerset.md b/node_modules/mathjs/docs/reference/functions/setPowerset.md new file mode 100644 index 0000000..757ee44 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/setPowerset.md @@ -0,0 +1,43 @@ + + +# Function setPowerset + +Create the powerset of a (multi)set. (The powerset contains very possible subsets of a (multi)set.) +A multi-dimension array will be converted to a single-dimension array before the operation. + + +## Syntax + +```js +math.setPowerset(set) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a` | Array | Matrix | A (multi)set + +### Returns + +Type | Description +---- | ----------- +Array | The powerset of the (multi)set + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.setPowerset([1, 2, 3]) // returns [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] +``` + + +## See also + +[setCartesian](setCartesian.md) diff --git a/node_modules/mathjs/docs/reference/functions/setSize.md b/node_modules/mathjs/docs/reference/functions/setSize.md new file mode 100644 index 0000000..133a3d5 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/setSize.md @@ -0,0 +1,47 @@ + + +# Function setSize + +Count the number of elements of a (multi)set. When a second parameter is 'true', count only the unique values. +A multi-dimension array will be converted to a single-dimension array before the operation. + + +## Syntax + +```js +math.setSize(set) +math.setSize(set, unique) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a` | Array | Matrix | A multiset + +### Returns + +Type | Description +---- | ----------- +number | The number of elements of the (multi)set + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.setSize([1, 2, 2, 4]) // returns 4 +math.setSize([1, 2, 2, 4], true) // returns 3 +``` + + +## See also + +[setUnion](setUnion.md), +[setIntersect](setIntersect.md), +[setDifference](setDifference.md) diff --git a/node_modules/mathjs/docs/reference/functions/setSymDifference.md b/node_modules/mathjs/docs/reference/functions/setSymDifference.md new file mode 100644 index 0000000..51a2642 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/setSymDifference.md @@ -0,0 +1,47 @@ + + +# Function setSymDifference + +Create the symmetric difference of two (multi)sets. +Multi-dimension arrays will be converted to single-dimension arrays before the operation. + + +## Syntax + +```js +math.setSymDifference(set1, set2) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a1` | Array | Matrix | A (multi)set +`a2` | Array | Matrix | A (multi)set + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | The symmetric difference of two (multi)sets + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.setSymDifference([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2, 5, 6] +math.setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2, 5, 6] +``` + + +## See also + +[setUnion](setUnion.md), +[setIntersect](setIntersect.md), +[setDifference](setDifference.md) diff --git a/node_modules/mathjs/docs/reference/functions/setUnion.md b/node_modules/mathjs/docs/reference/functions/setUnion.md new file mode 100644 index 0000000..6e62fc5 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/setUnion.md @@ -0,0 +1,46 @@ + + +# Function setUnion + +Create the union of two (multi)sets. +Multi-dimension arrays will be converted to single-dimension arrays before the operation. + + +## Syntax + +```js +math.setUnion(set1, set2) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a1` | Array | Matrix | A (multi)set +`a2` | Array | Matrix | A (multi)set + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | The union of two (multi)sets + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.setUnion([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2, 3, 4, 5, 6] +math.setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2, 3, 4, 5, 6] +``` + + +## See also + +[setIntersect](setIntersect.md), +[setDifference](setDifference.md) diff --git a/node_modules/mathjs/docs/reference/functions/sign.md b/node_modules/mathjs/docs/reference/functions/sign.md new file mode 100644 index 0000000..37123f6 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/sign.md @@ -0,0 +1,52 @@ + + +# Function sign + +Compute the sign of a value. The sign of a value x is: + +- 1 when x > 0 +- -1 when x < 0 +- 0 when x == 0 + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.sign(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Array | Matrix | Unit | The number for which to determine the sign + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Array | Matrix | Unit | e The sign of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.sign(3.5) // returns 1 +math.sign(-4.2) // returns -1 +math.sign(0) // returns 0 + +math.sign([3, 5, -2, 0, 2]) // returns [1, 1, -1, 0, 1] +``` + + +## See also + +[abs](abs.md) diff --git a/node_modules/mathjs/docs/reference/functions/simplify.md b/node_modules/mathjs/docs/reference/functions/simplify.md new file mode 100644 index 0000000..8605787 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/simplify.md @@ -0,0 +1,130 @@ + + +# Function simplify + +Simplify an expression tree. + +A list of rules are applied to an expression, repeating over the list until +no further changes are made. +It's possible to pass a custom set of rules to the function as second +argument. A rule can be specified as an object, string, or function: + + const rules = [ + { l: 'n1*n3 + n2*n3', r: '(n1+n2)*n3' }, + 'n1*n3 + n2*n3 -> (n1+n2)*n3', + function (node) { + // ... return a new node or return the node unchanged + return node + } + ] + +String and object rules consist of a left and right pattern. The left is +used to match against the expression and the right determines what matches +are replaced with. The main difference between a pattern and a normal +expression is that variables starting with the following characters are +interpreted as wildcards: + +- 'n' - matches any Node +- 'c' - matches any ConstantNode +- 'v' - matches any Node that is not a ConstantNode + +The default list of rules is exposed on the function as `simplify.rules` +and can be used as a basis to built a set of custom rules. + +To specify a rule as a string, separate the left and right pattern by '->' +When specifying a rule as an object, the following keys are meaningful: +- l - the left pattern +- r - the right pattern +- s - in lieu of l and r, the string form that is broken at -> to give them +- repeat - whether to repeat this rule until the expression stabilizes +- assuming - gives a context object, as in the 'context' option to + simplify. Every property in the context object must match the current + context in order, or else the rule will not be applied. +- imposeContext - gives a context object, as in the 'context' option to + simplify. Any settings specified will override the incoming context + for all matches of this rule. + +For more details on the theory, see: + +- [Strategies for simplifying math expressions (Stackoverflow)](https://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions) +- [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification) + + An optional `options` argument can be passed as last argument of `simplify`. + Currently available options (defaults in parentheses): + - `consoleDebug` (false): whether to write the expression being simplified + and any changes to it, along with the rule responsible, to console + - `context` (simplify.defaultContext): an object giving properties of + each operator, which determine what simplifications are allowed. The + currently meaningful properties are commutative, associative, + total (whether the operation is defined for all arguments), and + trivial (whether the operation applied to a single argument leaves + that argument unchanged). The default context is very permissive and + allows almost all simplifications. Only properties differing from + the default need to be specified; the default context is used as a + fallback. Additional contexts `simplify.realContext` and + `simplify.positiveContext` are supplied to cause simplify to perform + just simplifications guaranteed to preserve all values of the expression + assuming all variables and subexpressions are real numbers or + positive real numbers, respectively. (Note that these are in some cases + more restrictive than the default context; for example, the default + context will allow `x/x` to simplify to 1, whereas + `simplify.realContext` will not, as `0/0` is not equal to 1.) + - `exactFractions` (true): whether to try to convert all constants to + exact rational numbers. + - `fractionsLimit` (10000): when `exactFractions` is true, constants will + be expressed as fractions only when both numerator and denominator + are smaller than `fractionsLimit`. + + +## Syntax + +```js +simplify(expr) +simplify(expr, rules) +simplify(expr, rules) +simplify(expr, rules, scope) +simplify(expr, rules, scope, options) +simplify(expr, scope) +simplify(expr, scope, options) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`expr` | Node | string | The expression to be simplified +`rules` | Array<{l:string, r: string} | string | function> | Optional list with custom rules + +### Returns + +Type | Description +---- | ----------- +Node | Returns the simplified form of `expr` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.simplify('2 * 1 * x ^ (2 - 1)') // Node "2 * x" +math.simplify('2 * 3 * x', {x: 4}) // Node "24" +const f = math.parse('2 * 1 * x ^ (2 - 1)') +math.simplify(f) // Node "2 * x" +math.simplify('0.4 * x', {}, {exactFractions: true}) // Node "x * 2 / 5" +math.simplify('0.4 * x', {}, {exactFractions: false}) // Node "0.4 * x" +``` + + +## See also + +[simplifyCore](simplifyCore.md), +[derivative](derivative.md), +[evaluate](evaluate.md), +[parse](parse.md), +[rationalize](rationalize.md), +[resolve](resolve.md) diff --git a/node_modules/mathjs/docs/reference/functions/simplifyCore.md b/node_modules/mathjs/docs/reference/functions/simplifyCore.md new file mode 100644 index 0000000..df89ab9 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/simplifyCore.md @@ -0,0 +1,50 @@ + + +# Function simplifyCore + +simplifyCore() performs single pass simplification suitable for +applications requiring ultimate performance. In contrast, simplify() +extends simplifyCore() with additional passes to provide deeper +simplification. + + +## Syntax + +```js +simplifyCore(expr) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`node` | Node | The expression to be simplified +`options` | Object | Simplification options, as per simplify() + +### Returns + +Type | Description +---- | ----------- +Node | Returns expression with basic simplifications applied + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const f = math.parse('2 * 1 * x ^ (2 - 1)') +math.simpifyCore(f) // Node {2 * x} +math.simplify('2 * 1 * x ^ (2 - 1)', [math.simplifyCore]) // Node {2 * x} +``` + + +## See also + +[simplify](simplify.md), +[resolve](resolve.md), +[derivative](derivative.md) diff --git a/node_modules/mathjs/docs/reference/functions/sin.md b/node_modules/mathjs/docs/reference/functions/sin.md new file mode 100644 index 0000000..c9a0485 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/sin.md @@ -0,0 +1,51 @@ + + +# Function sin + +Calculate the sine of a value. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.sin(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Sine of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.sin(2) // returns number 0.9092974268256813 +math.sin(math.pi / 4) // returns number 0.7071067811865475 +math.sin(math.unit(90, 'deg')) // returns number 1 +math.sin(math.unit(30, 'deg')) // returns number 0.5 + +const angle = 0.2 +math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2) // returns number ~1 +``` + + +## See also + +[cos](cos.md), +[tan](tan.md) diff --git a/node_modules/mathjs/docs/reference/functions/sinh.md b/node_modules/mathjs/docs/reference/functions/sinh.md new file mode 100644 index 0000000..52dae97 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/sinh.md @@ -0,0 +1,46 @@ + + +# Function sinh + +Calculate the hyperbolic sine of a value, +defined as `sinh(x) = 1/2 * (exp(x) - exp(-x))`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.sinh(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Hyperbolic sine of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.sinh(0.5) // returns number 0.5210953054937474 +``` + + +## See also + +[cosh](cosh.md), +[tanh](tanh.md) diff --git a/node_modules/mathjs/docs/reference/functions/size.md b/node_modules/mathjs/docs/reference/functions/size.md new file mode 100644 index 0000000..d91e58b --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/size.md @@ -0,0 +1,50 @@ + + +# Function size + +Calculate the size of a matrix or scalar. + + +## Syntax + +```js +math.size(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | boolean | number | Complex | Unit | string | Array | Matrix | A matrix + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | A vector with size of `x`. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.size(2.3) // returns [] +math.size('hello world') // returns [11] + +const A = [[1, 2, 3], [4, 5, 6]] +math.size(A) // returns [2, 3] +math.size(math.range(1,6)) // returns [5] +``` + + +## See also + +[count](count.md), +[resize](resize.md), +[squeeze](squeeze.md), +[subset](subset.md) diff --git a/node_modules/mathjs/docs/reference/functions/slu.md b/node_modules/mathjs/docs/reference/functions/slu.md new file mode 100644 index 0000000..9d03038 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/slu.md @@ -0,0 +1,57 @@ + + +# Function slu + +Calculate the Sparse Matrix LU decomposition with full pivoting. Sparse Matrix `A` is decomposed in two matrices (`L`, `U`) and two permutation vectors (`pinv`, `q`) where + +`P * A * Q = L * U` + + +## Syntax + +```js +math.slu(A, order, threshold) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`A` | SparseMatrix | A two dimensional sparse matrix for which to get the LU decomposition. +`order` | Number | The Symbolic Ordering and Analysis order: 0 - Natural ordering, no permutation vector q is returned 1 - Matrix must be square, symbolic ordering and analisis is performed on M = A + A' 2 - Symbolic ordering and analisis is performed on M = A' * A. Dense columns from A' are dropped, A recreated from A'. This is appropriatefor LU factorization of unsymmetric matrices. 3 - Symbolic ordering and analisis is performed on M = A' * A. This is best used for LU factorization is matrix M has no dense rows. A dense row is a row with more than 10*sqr(columns) entries. +`threshold` | Number | Partial pivoting threshold (1 for partial pivoting) + +### Returns + +Type | Description +---- | ----------- +Object | The lower triangular matrix, the upper triangular matrix and the permutation vectors. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const A = math.sparse([[4,3], [6, 3]]) +math.slu(A, 1, 0.001) +// returns: +// { +// L: [[1, 0], [1.5, 1]] +// U: [[4, 3], [0, -1.5]] +// p: [0, 1] +// q: [0, 1] +// } +``` + + +## See also + +[lup](lup.md), +[lsolve](lsolve.md), +[usolve](usolve.md), +[lusolve](lusolve.md) diff --git a/node_modules/mathjs/docs/reference/functions/smaller.md b/node_modules/mathjs/docs/reference/functions/smaller.md new file mode 100644 index 0000000..5ef2be5 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/smaller.md @@ -0,0 +1,60 @@ + + +# Function smaller + +Test whether value x is smaller than y. + +The function returns true when x is smaller than y and the relative +difference between x and y is smaller than the configured epsilon. The +function cannot be used to compare values smaller than approximately 2.22e-16. + +For matrices, the function is evaluated element wise. +Strings are compared by their numerical value. + + +## Syntax + +```js +math.smaller(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix | First value to compare +`y` | number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix | Second value to compare + +### Returns + +Type | Description +---- | ----------- +boolean | Array | Matrix | Returns true when the x is smaller than y, else returns false + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.smaller(2, 3) // returns true +math.smaller(5, 2 * 2) // returns false + +const a = math.unit('5 cm') +const b = math.unit('2 inch') +math.smaller(a, b) // returns true +``` + + +## See also + +[equal](equal.md), +[unequal](unequal.md), +[smallerEq](smallerEq.md), +[smaller](smaller.md), +[smallerEq](smallerEq.md), +[compare](compare.md) diff --git a/node_modules/mathjs/docs/reference/functions/smallerEq.md b/node_modules/mathjs/docs/reference/functions/smallerEq.md new file mode 100644 index 0000000..e14ec28 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/smallerEq.md @@ -0,0 +1,56 @@ + + +# Function smallerEq + +Test whether value x is smaller or equal to y. + +The function returns true when x is smaller than y or the relative +difference between x and y is smaller than the configured epsilon. The +function cannot be used to compare values smaller than approximately 2.22e-16. + +For matrices, the function is evaluated element wise. +Strings are compared by their numerical value. + + +## Syntax + +```js +math.smallerEq(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix | First value to compare +`y` | number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix | Second value to compare + +### Returns + +Type | Description +---- | ----------- +boolean | Array | Matrix | Returns true when the x is smaller than y, else returns false + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.smaller(1 + 2, 3) // returns false +math.smallerEq(1 + 2, 3) // returns true +``` + + +## See also + +[equal](equal.md), +[unequal](unequal.md), +[smaller](smaller.md), +[larger](larger.md), +[largerEq](largerEq.md), +[compare](compare.md) diff --git a/node_modules/mathjs/docs/reference/functions/sort.md b/node_modules/mathjs/docs/reference/functions/sort.md new file mode 100644 index 0000000..8d10583 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/sort.md @@ -0,0 +1,56 @@ + + +# Function sort + +Sort the items in a matrix. + + +## Syntax + +```js +math.sort(x) +math.sort(x, compare) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Matrix | Array | A one dimensional matrix or array to sort +`compare` | Function | 'asc' | 'desc' | 'natural' | An optional _comparator function or name. The function is called as `compare(a, b)`, and must return 1 when a > b, -1 when a < b, and 0 when a == b. Default value: 'asc'. + +### Returns + +Type | Description +---- | ----------- +Matrix | Array | Returns the sorted matrix. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.sort([5, 10, 1]) // returns [1, 5, 10] +math.sort(['C', 'B', 'A', 'D'], math.compareNatural) +// returns ['A', 'B', 'C', 'D'] + +function sortByLength (a, b) { + return a.length - b.length +} +math.sort(['Langdon', 'Tom', 'Sara'], sortByLength) +// returns ['Tom', 'Sara', 'Langdon'] +``` + + +## See also + +[filter](filter.md), +[forEach](forEach.md), +[map](map.md), +[compare](compare.md), +[compareNatural](compareNatural.md) diff --git a/node_modules/mathjs/docs/reference/functions/sparse.md b/node_modules/mathjs/docs/reference/functions/sparse.md new file mode 100644 index 0000000..083034d --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/sparse.md @@ -0,0 +1,51 @@ + + +# Function sparse + +Create a Sparse Matrix. The function creates a new `math.Matrix` object from +an `Array`. A Matrix has utility functions to manipulate the data in the +matrix, like getting the size and getting or setting values in the matrix. + + +## Syntax + +```js +math.sparse() // creates an empty sparse matrix. +math.sparse(data) // creates a sparse matrix with initial data. +math.sparse(data, 'number') // creates a sparse matrix with initial data, number datatype. +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`data` | Array | Matrix | A two dimensional array + +### Returns + +Type | Description +---- | ----------- +Matrix | The created matrix + + +## Examples + +```js +let m = math.sparse([[1, 2], [3, 4]]) +m.size() // Array [2, 2] +m.resize([3, 2], 5) +m.valueOf() // Array [[1, 2], [3, 4], [5, 5]] +m.get([1, 0]) // number 3 +``` + + +## See also + +[bignumber](bignumber.md), +[boolean](boolean.md), +[complex](complex.md), +[index](index.md), +[number](number.md), +[string](string.md), +[unit](unit.md), +[matrix](matrix.md) diff --git a/node_modules/mathjs/docs/reference/functions/splitUnit.md b/node_modules/mathjs/docs/reference/functions/splitUnit.md new file mode 100644 index 0000000..5011952 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/splitUnit.md @@ -0,0 +1,37 @@ + + +# Function splitUnit + +Split a unit in an array of units whose sum is equal to the original unit. + + +## Syntax + +```js +splitUnit(unit: Unit, parts: Array.) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`parts` | Array | An array of strings or valueless units. + +### Returns + +Type | Description +---- | ----------- +Array | An array of units. + + +## Examples + +```js +math.splitUnit(new Unit(1, 'm'), ['feet', 'inch']) +// [ 3 feet, 3.3700787401575 inch ] +``` + + +## See also + +[unit](unit.md) diff --git a/node_modules/mathjs/docs/reference/functions/sqrt.md b/node_modules/mathjs/docs/reference/functions/sqrt.md new file mode 100644 index 0000000..cc5c1f8 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/sqrt.md @@ -0,0 +1,50 @@ + + +# Function sqrt + +Calculate the square root of a value. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.sqrt(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Array | Matrix | Unit | Value for which to calculate the square root. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Unit | Returns the square root of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.sqrt(25) // returns 5 +math.square(5) // returns 25 +math.sqrt(-4) // returns Complex 2i +``` + + +## See also + +[square](square.md), +[multiply](multiply.md), +[cube](cube.md), +[cbrt](cbrt.md), +[sqrtm](sqrtm.md) diff --git a/node_modules/mathjs/docs/reference/functions/sqrtm.md b/node_modules/mathjs/docs/reference/functions/sqrtm.md new file mode 100644 index 0000000..c694cf3 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/sqrtm.md @@ -0,0 +1,46 @@ + + +# Function sqrtm + +Calculate the principal square root of a square matrix. +The principal square root matrix `X` of another matrix `A` is such that `X * X = A`. + +https://en.wikipedia.org/wiki/Square_root_of_a_matrix + + +## Syntax + +```js +X = math.sqrtm(A) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`A` | Array | Matrix | The square matrix `A` + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | The principal square root of matrix `A` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.sqrtm([[1, 2], [3, 4]]) // returns [[-2, 1], [1.5, -0.5]] +``` + + +## See also + +[sqrt](sqrt.md), +[pow](pow.md) diff --git a/node_modules/mathjs/docs/reference/functions/square.md b/node_modules/mathjs/docs/reference/functions/square.md new file mode 100644 index 0000000..b540c9e --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/square.md @@ -0,0 +1,51 @@ + + +# Function square + +Compute the square of a value, `x * x`. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.square(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Array | Matrix | Unit | Number for which to calculate the square + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Array | Matrix | Unit | Squared value + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.square(2) // returns number 4 +math.square(3) // returns number 9 +math.pow(3, 2) // returns number 9 +math.multiply(3, 3) // returns number 9 + +math.square([1, 2, 3, 4]) // returns Array [1, 4, 9, 16] +``` + + +## See also + +[multiply](multiply.md), +[cube](cube.md), +[sqrt](sqrt.md), +[pow](pow.md) diff --git a/node_modules/mathjs/docs/reference/functions/squeeze.md b/node_modules/mathjs/docs/reference/functions/squeeze.md new file mode 100644 index 0000000..7a772fa --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/squeeze.md @@ -0,0 +1,53 @@ + + +# Function squeeze + +Squeeze a matrix, remove inner and outer singleton dimensions from a matrix. + + +## Syntax + +```js +math.squeeze(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Matrix | Array | Matrix to be squeezed + +### Returns + +Type | Description +---- | ----------- +Matrix | Array | Squeezed matrix + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.squeeze([3]) // returns 3 +math.squeeze([[3]]) // returns 3 + +const A = math.zeros(3, 1) // returns [[0], [0], [0]] (size 3x1) +math.squeeze(A) // returns [0, 0, 0] (size 3) + +const B = math.zeros(1, 3) // returns [[0, 0, 0]] (size 1x3) +math.squeeze(B) // returns [0, 0, 0] (size 3) + +// only inner and outer dimensions are removed +const C = math.zeros(2, 1, 3) // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3) +math.squeeze(C) // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3) +``` + + +## See also + +[subset](subset.md) diff --git a/node_modules/mathjs/docs/reference/functions/std.md b/node_modules/mathjs/docs/reference/functions/std.md new file mode 100644 index 0000000..dc348d2 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/std.md @@ -0,0 +1,76 @@ + + +# Function std + +Compute the standard deviation of a matrix or a list with values. +The standard deviations is defined as the square root of the variance: +`std(A) = sqrt(variance(A))`. +In case of a (multi dimensional) array or matrix, the standard deviation +over all elements will be calculated by default, unless an axis is specified +in which case the standard deviation will be computed along that axis. + +Additionally, it is possible to compute the standard deviation along the rows +or columns of a matrix by specifying the dimension as the second argument. + +Optionally, the type of normalization can be specified as the final +parameter. The parameter `normalization` can be one of the following values: + +- 'unbiased' (default) The sum of squared errors is divided by (n - 1) +- 'uncorrected' The sum of squared errors is divided by n +- 'biased' The sum of squared errors is divided by (n + 1) + + +## Syntax + +```js +math.std(a, b, c, ...) +math.std(A) +math.std(A, normalization) +math.std(A, dimension) +math.std(A, dimension, normalization) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`array` | Array | Matrix | A single matrix or or multiple scalar values +`normalization` | string | Determines how to normalize the variance. Choose 'unbiased' (default), 'uncorrected', or 'biased'. Default value: 'unbiased'. + +### Returns + +Type | Description +---- | ----------- +* | The standard deviation + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.std(2, 4, 6) // returns 2 +math.std([2, 4, 6, 8]) // returns 2.581988897471611 +math.std([2, 4, 6, 8], 'uncorrected') // returns 2.23606797749979 +math.std([2, 4, 6, 8], 'biased') // returns 2 + +math.std([[1, 2, 3], [4, 5, 6]]) // returns 1.8708286933869707 +math.std([[1, 2, 3], [4, 6, 8]], 0) // returns [2.1213203435596424, 2.8284271247461903, 3.5355339059327378] +math.std([[1, 2, 3], [4, 6, 8]], 1) // returns [1, 2] +math.std([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.7071067811865476, 1.4142135623730951] +``` + + +## See also + +[mean](mean.md), +[median](median.md), +[max](max.md), +[min](min.md), +[prod](prod.md), +[sum](sum.md), +[variance](variance.md) diff --git a/node_modules/mathjs/docs/reference/functions/stirlingS2.md b/node_modules/mathjs/docs/reference/functions/stirlingS2.md new file mode 100644 index 0000000..0c7ba0c --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/stirlingS2.md @@ -0,0 +1,52 @@ + + +# Function stirlingS2 + +The Stirling numbers of the second kind, counts the number of ways to partition +a set of n labelled objects into k nonempty unlabelled subsets. +stirlingS2 only takes integer arguments. +The following condition must be enforced: k <= n. + + If n = k or k = 1 <= n, then s(n,k) = 1 + If k = 0 < n, then s(n,k) = 0 + +Note that if either n or k is supplied as a BigNumber, the result will be +as well. + + +## Syntax + +```js +math.stirlingS2(n, k) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`n` | Number | BigNumber | Total number of objects in the set +`k` | Number | BigNumber | Number of objects in the subset + +### Returns + +Type | Description +---- | ----------- +Number | BigNumber | S(n,k) + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.stirlingS2(5, 3) //returns 25 +``` + + +## See also + +[bellNumbers](bellNumbers.md) diff --git a/node_modules/mathjs/docs/reference/functions/string.md b/node_modules/mathjs/docs/reference/functions/string.md new file mode 100644 index 0000000..88d0b54 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/string.md @@ -0,0 +1,49 @@ + + +# Function string + +Create a string or convert any object into a string. +Elements of Arrays and Matrices are processed element wise. + + +## Syntax + +```js +math.string(value) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`value` | * | Array | Matrix | null | A value to convert to a string + +### Returns + +Type | Description +---- | ----------- +string | Array | Matrix | The created string + + +## Examples + +```js +math.string(4.2) // returns string '4.2' +math.string(math.complex(3, 2) // returns string '3 + 2i' + +const u = math.unit(5, 'km') +math.string(u.to('m')) // returns string '5000 m' + +math.string([true, false]) // returns ['true', 'false'] +``` + + +## See also + +[bignumber](bignumber.md), +[boolean](boolean.md), +[complex](complex.md), +[index](index.md), +[matrix](matrix.md), +[number](number.md), +[unit](unit.md) diff --git a/node_modules/mathjs/docs/reference/functions/subset.md b/node_modules/mathjs/docs/reference/functions/subset.md new file mode 100644 index 0000000..06b614f --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/subset.md @@ -0,0 +1,65 @@ + + +# Function subset + +Get or set a subset of a matrix or string. + + +## Syntax + +```js +math.subset(value, index) // retrieve a subset +math.subset(value, index, replacement [, defaultValue]) // replace a subset +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`matrix` | Array | Matrix | string | An array, matrix, or string +`index` | Index | For each dimension of the target, specifies an index or a list of indices to fetch or set. `subset` uses the cartesian product of the indices specified in each dimension. +`replacement` | * | An array, matrix, or scalar. If provided, the subset is replaced with replacement. If not provided, the subset is returned +`defaultValue` | * | Default value, filled in on new entries when the matrix is resized. If not provided, math.matrix elements will be left undefined. Default value: undefined. + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | string | Either the retrieved subset or the updated matrix. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +// get a subset +const d = [[1, 2], [3, 4]] +math.subset(d, math.index(1, 0)) // returns 3 +math.subset(d, math.index([0, 1], 1)) // returns [[2], [4]] + +// replace a subset +const e = [] +const f = math.subset(e, math.index(0, [0, 2]), [5, 6]) // f = [[5, 6]] and e = [[5, 0, 6]] +const g = math.subset(f, math.index(1, 1), 7, 0) // g = [[5, 6], [0, 7]] + +// get submatrix using ranges +const M = [ + [1,2,3], + [4,5,6], + [7,8,9] +] +math.subset(M, math.index(math.range(0,2), math.range(0,3))) // [[1,2,3],[4,5,6]] +``` + + +## See also + +[size](size.md), +[resize](resize.md), +[squeeze](squeeze.md), +[index](index.md) diff --git a/node_modules/mathjs/docs/reference/functions/subtract.md b/node_modules/mathjs/docs/reference/functions/subtract.md new file mode 100644 index 0000000..d3cc04b --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/subtract.md @@ -0,0 +1,54 @@ + + +# Function subtract + +Subtract two values, `x - y`. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.subtract(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Initial value +`y` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Value to subtract from `x` + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Subtraction of `x` and `y` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.subtract(5.3, 2) // returns number 3.3 + +const a = math.complex(2, 3) +const b = math.complex(4, 1) +math.subtract(a, b) // returns Complex -2 + 2i + +math.subtract([5, 7, 4], 4) // returns Array [1, 3, 0] + +const c = math.unit('2.1 km') +const d = math.unit('500m') +math.subtract(c, d) // returns Unit 1.6 km +``` + + +## See also + +[add](add.md) diff --git a/node_modules/mathjs/docs/reference/functions/sum.md b/node_modules/mathjs/docs/reference/functions/sum.md new file mode 100644 index 0000000..91cce87 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/sum.md @@ -0,0 +1,54 @@ + + +# Function sum + +Compute the sum of a matrix or a list with values. +In case of a (multi dimensional) array or matrix, the sum of all +elements will be calculated. + + +## Syntax + +```js +math.sum(a, b, c, ...) +math.sum(A) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | ... * | A single matrix or or multiple scalar values + +### Returns + +Type | Description +---- | ----------- +* | The sum of all values + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.sum(2, 1, 4, 3) // returns 10 +math.sum([2, 1, 4, 3]) // returns 10 +math.sum([[2, 5], [4, 3], [1, 7]]) // returns 22 +``` + + +## See also + +[mean](mean.md), +[median](median.md), +[min](min.md), +[max](max.md), +[prod](prod.md), +[std](std.md), +[variance](variance.md), +[cumsum](cumsum.md) diff --git a/node_modules/mathjs/docs/reference/functions/symbolicEqual.md b/node_modules/mathjs/docs/reference/functions/symbolicEqual.md new file mode 100644 index 0000000..501f0ef --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/symbolicEqual.md @@ -0,0 +1,62 @@ + + +# Function symbolicEqual + +Attempts to determine if two expressions are symbolically equal, i.e. +one is the result of valid algebraic manipulations on the other. +Currently, this simply checks if the difference of the two expressions +simplifies down to 0. So there are two important caveats: +1. whether two expressions are symbolically equal depends on the + manipulations allowed. Therefore, this function takes an optional + third argument, which are the options that control the behavior + as documented for the `simplify()` function. +2. it is in general intractable to find the minimal simplification of + an arbitrarily complicated expression. So while a `true` value + of `symbolicEqual` ensures that the two expressions can be manipulated + to match each other, a `false` value does not absolutely rule this out. + + +## Syntax + +```js +symbolicEqual(expr1, expr2) +symbolicEqual(expr1, expr2, options) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`expr1` | Node | string | The first expression to compare +`expr2` | Node | string | The second expression to compare +`options` | Object | Optional option object, passed to simplify + +### Returns + +Type | Description +---- | ----------- +boolean | Returns true if a valid manipulation making the expressions equal is found. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +symbolicEqual('x*y', 'y*x') // true +symbolicEqual('x*y', 'y*x', {context: {multiply: {commutative: false}}}) + //false +symbolicEqual('x/y', '(y*x^(-1))^(-1)') // true +symbolicEqual('abs(x)','x') // false +symbolicEqual('abs(x)','x', simplify.positiveContext) // true +``` + + +## See also + +[simplify](simplify.md), +[evaluate](evaluate.md) diff --git a/node_modules/mathjs/docs/reference/functions/tan.md b/node_modules/mathjs/docs/reference/functions/tan.md new file mode 100644 index 0000000..30984a9 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/tan.md @@ -0,0 +1,49 @@ + + +# Function tan + +Calculate the tangent of a value. `tan(x)` is equal to `sin(x) / cos(x)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.tan(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Tangent of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.tan(0.5) // returns number 0.5463024898437905 +math.sin(0.5) / math.cos(0.5) // returns number 0.5463024898437905 +math.tan(math.pi / 4) // returns number 1 +math.tan(math.unit(45, 'deg')) // returns number 1 +``` + + +## See also + +[atan](atan.md), +[sin](sin.md), +[cos](cos.md) diff --git a/node_modules/mathjs/docs/reference/functions/tanh.md b/node_modules/mathjs/docs/reference/functions/tanh.md new file mode 100644 index 0000000..1b0eef0 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/tanh.md @@ -0,0 +1,50 @@ + + +# Function tanh + +Calculate the hyperbolic tangent of a value, +defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.tanh(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | Function input + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Complex | Array | Matrix | Hyperbolic tangent of x + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +// tanh(x) = sinh(x) / cosh(x) = 1 / coth(x) +math.tanh(0.5) // returns 0.46211715726000974 +math.sinh(0.5) / math.cosh(0.5) // returns 0.46211715726000974 +1 / math.coth(0.5) // returns 0.46211715726000974 +``` + + +## See also + +[sinh](sinh.md), +[cosh](cosh.md), +[coth](coth.md) diff --git a/node_modules/mathjs/docs/reference/functions/to.md b/node_modules/mathjs/docs/reference/functions/to.md new file mode 100644 index 0000000..edbaafc --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/to.md @@ -0,0 +1,47 @@ + + +# Function to + +Change the unit of a value. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.to(x, unit) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Unit | Array | Matrix | The unit to be converted. +`unit` | Unit | Array | Matrix | New unit. Can be a string like "cm" or a unit without value. + +### Returns + +Type | Description +---- | ----------- +Unit | Array | Matrix | value with changed, fixed unit. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.to(math.unit('2 inch'), 'cm') // returns Unit 5.08 cm +math.to(math.unit('2 inch'), math.unit(null, 'cm')) // returns Unit 5.08 cm +math.to(math.unit(16, 'bytes'), 'bits') // returns Unit 128 bits +``` + + +## See also + +[unit](unit.md) diff --git a/node_modules/mathjs/docs/reference/functions/trace.md b/node_modules/mathjs/docs/reference/functions/trace.md new file mode 100644 index 0000000..be03119 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/trace.md @@ -0,0 +1,50 @@ + + +# Function trace + +Calculate the trace of a matrix: the sum of the elements on the main +diagonal of a square matrix. + + +## Syntax + +```js +math.trace(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Array | Matrix | A matrix + +### Returns + +Type | Description +---- | ----------- +number | The trace of `x` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.trace([[1, 2], [3, 4]]) // returns 5 + +const A = [ + [1, 2, 3], + [-1, 2, 3], + [2, 0, 3] +] +math.trace(A) // returns 6 +``` + + +## See also + +[diag](diag.md) diff --git a/node_modules/mathjs/docs/reference/functions/transpose.md b/node_modules/mathjs/docs/reference/functions/transpose.md new file mode 100644 index 0000000..ac46903 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/transpose.md @@ -0,0 +1,49 @@ + + +# Function transpose + +Transpose a matrix. All values of the matrix are reflected over its +main diagonal. Only applicable to two dimensional matrices containing +a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional +vectors and scalars return the input unchanged. + + +## Syntax + +```js +math.transpose(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | Array | Matrix | Matrix to be transposed + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | The transposed matrix + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const A = [[1, 2, 3], [4, 5, 6]] +math.transpose(A) // returns [[1, 4], [2, 5], [3, 6]] +``` + + +## See also + +[diag](diag.md), +[inv](inv.md), +[subset](subset.md), +[squeeze](squeeze.md) diff --git a/node_modules/mathjs/docs/reference/functions/typeOf.md b/node_modules/mathjs/docs/reference/functions/typeOf.md new file mode 100644 index 0000000..d79e14c --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/typeOf.md @@ -0,0 +1,81 @@ + + +# Function typeOf + +Determine the type of a variable. + +Function `typeOf` recognizes the following types of objects: + +Object | Returns | Example +---------------------- | ------------- | ------------------------------------------ +null | `'null'` | `math.typeOf(null)` +number | `'number'` | `math.typeOf(3.5)` +boolean | `'boolean'` | `math.typeOf(true)` +string | `'string'` | `math.typeOf('hello world')` +Array | `'Array'` | `math.typeOf([1, 2, 3])` +Date | `'Date'` | `math.typeOf(new Date())` +Function | `'Function'` | `math.typeOf(function () {})` +Object | `'Object'` | `math.typeOf({a: 2, b: 3})` +RegExp | `'RegExp'` | `math.typeOf(/a regexp/)` +undefined | `'undefined'` | `math.typeOf(undefined)` +math.BigNumber | `'BigNumber'` | `math.typeOf(math.bignumber('2.3e500'))` +math.Chain | `'Chain'` | `math.typeOf(math.chain(2))` +math.Complex | `'Complex'` | `math.typeOf(math.complex(2, 3))` +math.Fraction | `'Fraction'` | `math.typeOf(math.fraction(1, 3))` +math.Help | `'Help'` | `math.typeOf(math.help('sqrt'))` +math.Help | `'Help'` | `math.typeOf(math.help('sqrt'))` +math.Index | `'Index'` | `math.typeOf(math.index(1, 3))` +math.Matrix | `'Matrix'` | `math.typeOf(math.matrix([[1,2], [3, 4]]))` +math.Range | `'Range'` | `math.typeOf(math.range(0, 10))` +math.ResultSet | `'ResultSet'` | `math.typeOf(math.evaluate('a=2\nb=3'))` +math.Unit | `'Unit'` | `math.typeOf(math.unit('45 deg'))` +math.AccessorNode | `'AccessorNode'` | `math.typeOf(math.parse('A[2]'))` +math.ArrayNode | `'ArrayNode'` | `math.typeOf(math.parse('[1,2,3]'))` +math.AssignmentNode | `'AssignmentNode'` | `math.typeOf(math.parse('x=2'))` +math.BlockNode | `'BlockNode'` | `math.typeOf(math.parse('a=2; b=3'))` +math.ConditionalNode | `'ConditionalNode'` | `math.typeOf(math.parse('x<0 ? -x : x'))` +math.ConstantNode | `'ConstantNode'` | `math.typeOf(math.parse('2.3'))` +math.FunctionAssignmentNode | `'FunctionAssignmentNode'` | `math.typeOf(math.parse('f(x)=x^2'))` +math.FunctionNode | `'FunctionNode'` | `math.typeOf(math.parse('sqrt(4)'))` +math.IndexNode | `'IndexNode'` | `math.typeOf(math.parse('A[2]').index)` +math.ObjectNode | `'ObjectNode'` | `math.typeOf(math.parse('{a:2}'))` +math.ParenthesisNode | `'ParenthesisNode'` | `math.typeOf(math.parse('(2+3)'))` +math.RangeNode | `'RangeNode'` | `math.typeOf(math.parse('1:10'))` +math.SymbolNode | `'SymbolNode'` | `math.typeOf(math.parse('x'))` + + +## Syntax + +```js +math.typeOf(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | * | The variable for which to test the type. + +### Returns + +Type | Description +---- | ----------- +string | Returns the name of the type. Primitive types are lower case, non-primitive types are upper-camel-case. For example 'number', 'string', 'Array', 'Date'. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.typeOf(3.5) // returns 'number' +math.typeOf(math.complex('2-4i')) // returns 'Complex' +math.typeOf(math.unit('45 deg')) // returns 'Unit' +math.typeOf('hello world') // returns 'string' +``` + + diff --git a/node_modules/mathjs/docs/reference/functions/typed.md b/node_modules/mathjs/docs/reference/functions/typed.md new file mode 100644 index 0000000..db84e40 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/typed.md @@ -0,0 +1,56 @@ + + +# Function typed + +Create a typed-function which checks the types of the arguments and +can match them against multiple provided signatures. The typed-function +automatically converts inputs in order to find a matching signature. +Typed functions throw informative errors in case of wrong input arguments. + +See the library [typed-function](https://github.com/josdejong/typed-function) +for detailed documentation. + + +## Syntax + +```js +math.typed(name, signatures) : function +math.typed(signatures) : function +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`name` | string | Optional name for the typed-function +`signatures` | Object<string, function> | Object with one or multiple function signatures + +### Returns + +Type | Description +---- | ----------- +function | The created typed-function. + + +## Examples + +```js +// create a typed function with multiple types per argument (type union) +const fn2 = typed({ + 'number | boolean': function (b) { + return 'b is a number or boolean' + }, + 'string, number | boolean': function (a, b) { + return 'a is a string, b is a number or boolean' + } +}) + +// create a typed function with an any type argument +const log = typed({ + 'string, any': function (event, data) { + console.log('event: ' + event + ', data: ' + JSON.stringify(data)) + } +}) +``` + + diff --git a/node_modules/mathjs/docs/reference/functions/unaryMinus.md b/node_modules/mathjs/docs/reference/functions/unaryMinus.md new file mode 100644 index 0000000..46858b1 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/unaryMinus.md @@ -0,0 +1,49 @@ + + +# Function unaryMinus + +Inverse the sign of a value, apply a unary minus operation. + +For matrices, the function is evaluated element wise. Boolean values and +strings will be converted to a number. For complex numbers, both real and +complex value are inverted. + + +## Syntax + +```js +math.unaryMinus(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Number to be inverted. + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Returns the value with inverted sign. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.unaryMinus(3.5) // returns -3.5 +math.unaryMinus(-4.2) // returns 4.2 +``` + + +## See also + +[add](add.md), +[subtract](subtract.md), +[unaryPlus](unaryPlus.md) diff --git a/node_modules/mathjs/docs/reference/functions/unaryPlus.md b/node_modules/mathjs/docs/reference/functions/unaryPlus.md new file mode 100644 index 0000000..117b179 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/unaryPlus.md @@ -0,0 +1,48 @@ + + +# Function unaryPlus + +Unary plus operation. +Boolean values and strings will be converted to a number, numeric values will be returned as is. + +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.unaryPlus(x) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | string | Complex | Unit | Array | Matrix | Input value + +### Returns + +Type | Description +---- | ----------- +number | BigNumber | Fraction | Complex | Unit | Array | Matrix | Returns the input value when numeric, converts to a number when input is non-numeric. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.unaryPlus(3.5) // returns 3.5 +math.unaryPlus(1) // returns 1 +``` + + +## See also + +[unaryMinus](unaryMinus.md), +[add](add.md), +[subtract](subtract.md) diff --git a/node_modules/mathjs/docs/reference/functions/unequal.md b/node_modules/mathjs/docs/reference/functions/unequal.md new file mode 100644 index 0000000..3738276 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/unequal.md @@ -0,0 +1,74 @@ + + +# Function unequal + +Test whether two values are unequal. + +The function tests whether the relative difference between x and y is +larger than the configured epsilon. The function cannot be used to compare +values smaller than approximately 2.22e-16. + +For matrices, the function is evaluated element wise. +In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im. +Strings are compared by their numerical value. + +Values `null` and `undefined` are compared strictly, thus `null` is unequal +with everything except `null`, and `undefined` is unequal with everything +except `undefined`. + + +## Syntax + +```js +math.unequal(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined | First value to compare +`y` | number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined | Second value to compare + +### Returns + +Type | Description +---- | ----------- +boolean | Array | Matrix | Returns true when the compared values are unequal, else returns false + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.unequal(2 + 2, 3) // returns true +math.unequal(2 + 2, 4) // returns false + +const a = math.unit('50 cm') +const b = math.unit('5 m') +math.unequal(a, b) // returns false + +const c = [2, 5, 1] +const d = [2, 7, 1] + +math.unequal(c, d) // returns [false, true, false] +math.deepEqual(c, d) // returns false + +math.unequal(0, null) // returns true +``` + + +## See also + +[equal](equal.md), +[deepEqual](deepEqual.md), +[smaller](smaller.md), +[smallerEq](smallerEq.md), +[larger](larger.md), +[largerEq](largerEq.md), +[compare](compare.md) diff --git a/node_modules/mathjs/docs/reference/functions/unit.md b/node_modules/mathjs/docs/reference/functions/unit.md new file mode 100644 index 0000000..e81d94c --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/unit.md @@ -0,0 +1,48 @@ + + +# Function unit + +Create a unit. Depending on the passed arguments, the function +will create and return a new math.Unit object. +When a matrix is provided, all elements will be converted to units. + + +## Syntax + +```js +math.unit(unit : string) +math.unit(value : number, unit : string) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`args` | * | Array | Matrix | A number and unit. + +### Returns + +Type | Description +---- | ----------- +Unit | Array | Matrix | The created unit + + +## Examples + +```js +const a = math.unit(5, 'cm') // returns Unit 50 mm +const b = math.unit('23 kg') // returns Unit 23 kg +a.to('m') // returns Unit 0.05 m +``` + + +## See also + +[bignumber](bignumber.md), +[boolean](boolean.md), +[complex](complex.md), +[index](index.md), +[matrix](matrix.md), +[number](number.md), +[string](string.md), +[createUnit](createUnit.md) diff --git a/node_modules/mathjs/docs/reference/functions/usolve.md b/node_modules/mathjs/docs/reference/functions/usolve.md new file mode 100644 index 0000000..d3783a8 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/usolve.md @@ -0,0 +1,51 @@ + + +# Function usolve + +Finds one solution of a linear equation system by backward substitution. Matrix must be an upper triangular matrix. Throws an error if there's no solution. + +`U * x = b` + + +## Syntax + +```js +math.usolve(U, b) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`U` | Matrix, Array | A N x N matrix or array (U) +`b` | Matrix, Array | A column vector with the b values + +### Returns + +Type | Description +---- | ----------- +DenseMatrix | Array | A column vector with the linear system solution (x) + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const a = [[-2, 3], [2, 1]] +const b = [11, 9] +const x = usolve(a, b) // [[8], [9]] +``` + + +## See also + +[usolveAll](usolveAll.md), +[lup](lup.md), +[slu](slu.md), +[usolve](usolve.md), +[lusolve](lusolve.md) diff --git a/node_modules/mathjs/docs/reference/functions/usolveAll.md b/node_modules/mathjs/docs/reference/functions/usolveAll.md new file mode 100644 index 0000000..38e4618 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/usolveAll.md @@ -0,0 +1,51 @@ + + +# Function usolveAll + +Finds all solutions of a linear equation system by backward substitution. Matrix must be an upper triangular matrix. + +`U * x = b` + + +## Syntax + +```js +math.usolveAll(U, b) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`U` | Matrix, Array | A N x N matrix or array (U) +`b` | Matrix, Array | A column vector with the b values + +### Returns + +Type | Description +---- | ----------- +DenseMatrix[] | Array[] | An array of affine-independent column vectors (x) that solve the linear system + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +const a = [[-2, 3], [2, 1]] +const b = [11, 9] +const x = usolveAll(a, b) // [ [[8], [9]] ] +``` + + +## See also + +[usolve](usolve.md), +[lup](lup.md), +[slu](slu.md), +[usolve](usolve.md), +[lusolve](lusolve.md) diff --git a/node_modules/mathjs/docs/reference/functions/variance.md b/node_modules/mathjs/docs/reference/functions/variance.md new file mode 100644 index 0000000..17bf357 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/variance.md @@ -0,0 +1,78 @@ + + +# Function variance + +Compute the variance of a matrix or a list with values. +In case of a (multi dimensional) array or matrix, the variance over all +elements will be calculated. + +Additionally, it is possible to compute the variance along the rows +or columns of a matrix by specifying the dimension as the second argument. + +Optionally, the type of normalization can be specified as the final +parameter. The parameter `normalization` can be one of the following values: + +- 'unbiased' (default) The sum of squared errors is divided by (n - 1) +- 'uncorrected' The sum of squared errors is divided by n +- 'biased' The sum of squared errors is divided by (n + 1) + + +Note that older browser may not like the variable name `var`. In that +case, the function can be called as `math['var'](...)` instead of +`math.var(...)`. + + +## Syntax + +```js +math.variance(a, b, c, ...) +math.variance(A) +math.variance(A, normalization) +math.variance(A, dimension) +math.variance(A, dimension, normalization) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`array` | Array | Matrix | A single matrix or or multiple scalar values +`normalization` | string | Determines how to normalize the variance. Choose 'unbiased' (default), 'uncorrected', or 'biased'. Default value: 'unbiased'. + +### Returns + +Type | Description +---- | ----------- +* | The variance + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.variance(2, 4, 6) // returns 4 +math.variance([2, 4, 6, 8]) // returns 6.666666666666667 +math.variance([2, 4, 6, 8], 'uncorrected') // returns 5 +math.variance([2, 4, 6, 8], 'biased') // returns 4 + +math.variance([[1, 2, 3], [4, 5, 6]]) // returns 3.5 +math.variance([[1, 2, 3], [4, 6, 8]], 0) // returns [4.5, 8, 12.5] +math.variance([[1, 2, 3], [4, 6, 8]], 1) // returns [1, 4] +math.variance([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.5, 2] +``` + + +## See also + +[mean](mean.md), +[median](median.md), +[max](max.md), +[min](min.md), +[prod](prod.md), +[std](std.md), +[sum](sum.md) diff --git a/node_modules/mathjs/docs/reference/functions/xgcd.md b/node_modules/mathjs/docs/reference/functions/xgcd.md new file mode 100644 index 0000000..4e33656 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/xgcd.md @@ -0,0 +1,47 @@ + + +# Function xgcd + +Calculate the extended greatest common divisor for two values. +See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. + + +## Syntax + +```js +math.xgcd(a, b) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`a` | number | BigNumber | An integer number +`b` | number | BigNumber | An integer number + +### Returns + +Type | Description +---- | ----------- +Array | Returns an array containing 3 integers `[div, m, n]` where `div = gcd(a, b)` and `a*m + b*n = div` + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.xgcd(8, 12) // returns [4, -1, 1] +math.gcd(8, 12) // returns 4 +math.xgcd(36163, 21199) // returns [1247, -7, 12] +``` + + +## See also + +[gcd](gcd.md), +[lcm](lcm.md) diff --git a/node_modules/mathjs/docs/reference/functions/xor.md b/node_modules/mathjs/docs/reference/functions/xor.md new file mode 100644 index 0000000..86959d5 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/xor.md @@ -0,0 +1,53 @@ + + +# Function xor + +Logical `xor`. Test whether one and only one value is defined with a nonzero/nonempty value. +For matrices, the function is evaluated element wise. + + +## Syntax + +```js +math.xor(x, y) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`x` | number | BigNumber | Complex | Unit | Array | Matrix | First value to check +`y` | number | BigNumber | Complex | Unit | Array | Matrix | Second value to check + +### Returns + +Type | Description +---- | ----------- +boolean | Array | Matrix | Returns true when one and only one input is defined with a nonzero/nonempty value. + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.xor(2, 4) // returns false + +a = [2, 0, 0] +b = [2, 7, 0] +c = 0 + +math.xor(a, b) // returns [false, true, false] +math.xor(a, c) // returns [true, false, false] +``` + + +## See also + +[and](and.md), +[not](not.md), +[or](or.md) diff --git a/node_modules/mathjs/docs/reference/functions/zeros.md b/node_modules/mathjs/docs/reference/functions/zeros.md new file mode 100644 index 0000000..6978a33 --- /dev/null +++ b/node_modules/mathjs/docs/reference/functions/zeros.md @@ -0,0 +1,57 @@ + + +# Function zeros + +Create a matrix filled with zeros. The created matrix can have one or +multiple dimensions. + + +## Syntax + +```js +math.zeros(m) +math.zeros(m, format) +math.zeros(m, n) +math.zeros(m, n, format) +math.zeros([m, n]) +math.zeros([m, n], format) +``` + +### Parameters + +Parameter | Type | Description +--------- | ---- | ----------- +`size` | ...number | Array | The size of each dimension of the matrix +`format` | string | The Matrix storage format + +### Returns + +Type | Description +---- | ----------- +Array | Matrix | A matrix filled with zeros + + +### Throws + +Type | Description +---- | ----------- + + +## Examples + +```js +math.zeros(3) // returns [0, 0, 0] +math.zeros(3, 2) // returns [[0, 0], [0, 0], [0, 0]] +math.zeros(3, 'dense') // returns [0, 0, 0] + +const A = [[1, 2, 3], [4, 5, 6]] +math.zeros(math.size(A)) // returns [[0, 0, 0], [0, 0, 0]] +``` + + +## See also + +[ones](ones.md), +[identity](identity.md), +[size](size.md), +[range](range.md) diff --git a/node_modules/mathjs/docs/reference/index.md b/node_modules/mathjs/docs/reference/index.md new file mode 100644 index 0000000..06aa3eb --- /dev/null +++ b/node_modules/mathjs/docs/reference/index.md @@ -0,0 +1,5 @@ +# Reference + +- [Classes](classes.md) +- [Constants](constants.md) +- [Functions](functions.md) diff --git a/node_modules/mathjs/examples/advanced/convert_fraction_to_bignumber.js b/node_modules/mathjs/examples/advanced/convert_fraction_to_bignumber.js new file mode 100644 index 0000000..d3903cd --- /dev/null +++ b/node_modules/mathjs/examples/advanced/convert_fraction_to_bignumber.js @@ -0,0 +1,59 @@ +// Convert from Fraction to BigNumber +// +// In the configuration of math.js one can specify the default number type to +// be `number`, `BigNumber`, or `Fraction`. Not all functions support `Fraction` +// or `BigNumber`, and if not supported these input types will be converted to +// numbers. +// +// When `Fraction` is configured, one may want to fallback to `BigNumber` +// instead of `number`. Also, one may want to be able to mix `Fraction` and +// `BigNumber` in operations like summing them up. This can be achieved by +// adding an extra conversion to the list of conversions as demonstrated in +// this example. + +// Create an empty math.js instance, with only typed +// (every instance contains `import` and `config` also out of the box) +const { create, typedDependencies, all } = require('../..') +const math = create({ + typedDependencies +}) + +// TODO: this should be much easier +const allExceptLoaded = Object.keys(all) + .map(key => all[key]) + .filter(factory => math[factory.fn] === undefined) + +// Configure to use fractions by default +math.config({ number: 'Fraction' }) + +// Add a conversion from Faction -> BigNumber +// this conversion: +// - must be inserted in the conversions list before the conversion Fraction -> number +// - must be added to the conversions before loading functions into math.js +math.typed.conversions.unshift({ + from: 'Fraction', + to: 'BigNumber', + convert: function (fraction) { + return new math.BigNumber(fraction.n).div(fraction.d) + } +}) + +// Import all data types, functions, constants, the expression parser, etc. +math.import(allExceptLoaded) + +// Operators `add` and `divide` do have support for Fractions, so the result +// will simply be a Fraction (default behavior of math.js). +const ans1 = math.evaluate('1/3 + 1/4') +console.log(math.typeOf(ans1), math.format(ans1)) +// outputs "Fraction 7/12" + +// Function sqrt doesn't have Fraction support, will now fall back to BigNumber +// instead of number. +const ans2 = math.evaluate('sqrt(4)') +console.log(math.typeOf(ans2), math.format(ans2)) +// outputs "BigNumber 2" + +// We can now do operations with mixed Fractions and BigNumbers +const ans3 = math.add(math.fraction(2, 5), math.bignumber(3)) +console.log(math.typeOf(ans3), math.format(ans3)) +// outputs "BigNumber 3.4" diff --git a/node_modules/mathjs/examples/advanced/custom_argument_parsing.js b/node_modules/mathjs/examples/advanced/custom_argument_parsing.js new file mode 100644 index 0000000..19198b8 --- /dev/null +++ b/node_modules/mathjs/examples/advanced/custom_argument_parsing.js @@ -0,0 +1,98 @@ +/** + * The expression parser of math.js has support for letting functions + * parse and evaluate arguments themselves, instead of calling them with + * evaluated arguments. + * + * By adding a property `raw` with value true to a function, the function + * will be invoked with unevaluated arguments, allowing the function + * to process the arguments in a customized way. + */ +const { create, all } = require('../..') +const math = create(all) + +/** + * Calculate the numeric integration of a function + * @param {Function} f + * @param {number} start + * @param {number} end + * @param {number} [step=0.01] + */ +function integrate (f, start, end, step) { + let total = 0 + step = step || 0.01 + for (let x = start; x < end; x += step) { + total += f(x + step / 2) * step + } + return total +} + +/** + * A transformation for the integrate function. This transformation will be + * invoked when the function is used via the expression parser of math.js. + * + * Syntax: + * + * integrate(integrand, variable, start, end) + * integrate(integrand, variable, start, end, step) + * + * Usage: + * + * math.evaluate('integrate(2*x, x, 0, 2)') + * math.evaluate('integrate(2*x, x, 0, 2, 0.01)') + * + * @param {Array.} args + * Expects the following arguments: [f, x, start, end, step] + * @param {Object} math + * @param {Object} [scope] + */ +integrate.transform = function (args, math, scope) { + // determine the variable name + if (!args[1].isSymbolNode) { + throw new Error('Second argument must be a symbol') + } + const variable = args[1].name + + // evaluate start, end, and step + const start = args[2].compile().evaluate(scope) + const end = args[3].compile().evaluate(scope) + const step = args[4] && args[4].compile().evaluate(scope) // step is optional + + // create a new scope, linked to the provided scope. We use this new scope + // to apply the variable. + const fnScope = Object.create(scope) + + // construct a function which evaluates the first parameter f after applying + // a value for parameter x. + const fnCode = args[0].compile() + const f = function (x) { + fnScope[variable] = x + return fnCode.evaluate(fnScope) + } + + // execute the integration + return integrate(f, start, end, step) +} + +// mark the transform function with a "rawArgs" property, so it will be called +// with uncompiled, unevaluated arguments. +integrate.transform.rawArgs = true + +// import the function into math.js. Raw functions must be imported in the +// math namespace, they can't be used via `evaluate(scope)`. +math.import({ + integrate: integrate +}) + +// use the function in JavaScript +function f (x) { + return math.pow(x, 0.5) +} +console.log(math.integrate(f, 0, 1)) // outputs 0.6667254718034714 + +// use the function via the expression parser +console.log(math.evaluate('integrate(x^0.5, x, 0, 1)')) // outputs 0.6667254718034714 + +// use the function via the expression parser (2) +const scope = {} +math.evaluate('f(x) = 2 * x', scope) +console.log(math.evaluate('integrate(f(x), x, 0, 2)', scope)) // outputs 4.000000000000003 diff --git a/node_modules/mathjs/examples/advanced/custom_datatype.js b/node_modules/mathjs/examples/advanced/custom_datatype.js new file mode 100644 index 0000000..ea83d3b --- /dev/null +++ b/node_modules/mathjs/examples/advanced/custom_datatype.js @@ -0,0 +1,56 @@ +// This example demonstrates importing a custom data type, +// and extending an existing function (add) with support for this data type. + +const { create, factory, all } = require('../..') +const math = create(all) + +// factory function which defines a new data type CustomValue +const createCustomValue = factory('CustomValue', ['typed'], ({ typed }) => { + // create a new data type + function CustomValue (value) { + this.value = value + } + CustomValue.prototype.isCustomValue = true + CustomValue.prototype.toString = function () { + return 'CustomValue:' + this.value + } + + // define a new data type with typed-function + typed.addType({ + name: 'CustomValue', + test: function (x) { + // test whether x is of type CustomValue + return x && x.isCustomValue === true + } + }) + + return CustomValue +}) + +// function add which can add the CustomValue data type +// When imported in math.js, the existing function `add` with support for +// CustomValue, because both implementations are typed-functions and do not +// have conflicting signatures. +const createAddCustomValue = factory('add', ['typed', 'CustomValue'], ({ typed, CustomValue }) => { + return typed('add', { + 'CustomValue, CustomValue': function (a, b) { + return new CustomValue(a.value + b.value) + } + }) +}) + +// import the new data type and function +math.import([ + createCustomValue, + createAddCustomValue +]) + +// use the new type +const ans1 = math.add(new math.CustomValue(2), new math.CustomValue(3)) +console.log(ans1.toString()) +// outputs 'CustomValue:5' + +// you can automatically use the new type in functions which use `add` under the hood: +const ans2 = math.sum(new math.CustomValue(6), new math.CustomValue(1), new math.CustomValue(2)) +console.log(ans2.toString()) +// outputs 'CustomValue:9' diff --git a/node_modules/mathjs/examples/advanced/custom_evaluate_using_factories.js b/node_modules/mathjs/examples/advanced/custom_evaluate_using_factories.js new file mode 100644 index 0000000..e878845 --- /dev/null +++ b/node_modules/mathjs/examples/advanced/custom_evaluate_using_factories.js @@ -0,0 +1,19 @@ +const { create, evaluateDependencies, factory } = require('../..') + +// custom implementations of all functions you want to support +const add = (a, b) => a + b +const subtract = (a, b) => a - b +const multiply = (a, b) => a * b +const divide = (a, b) => a / b + +// create factories for the functions, and create an evaluate function with those +// these functions will also be used by the classes like Unit. +const { evaluate } = create({ + evaluateDependencies, + createAdd: factory('add', [], () => add), + createSubtract: factory('subtract', [], () => subtract), + createMultiply: factory('multiply', [], () => multiply), + createDivide: factory('divide', [], () => divide) +}) + +console.log(evaluate('2 + 3 * 4')) // 14 diff --git a/node_modules/mathjs/examples/advanced/custom_evaluate_using_import.js b/node_modules/mathjs/examples/advanced/custom_evaluate_using_import.js new file mode 100644 index 0000000..3c486b3 --- /dev/null +++ b/node_modules/mathjs/examples/advanced/custom_evaluate_using_import.js @@ -0,0 +1,18 @@ +const { create, evaluateDependencies } = require('../..') + +// custom implementations of all functions you want to support +const add = (a, b) => a + b +const subtract = (a, b) => a - b +const multiply = (a, b) => a * b +const divide = (a, b) => a / b + +// create a mathjs instance with hardly any functions +// there are some functions created which are used internally by evaluate though, +// for example by the Unit class which has dependencies on addScalar, subtract, +// multiplyScalar, etc. +const math = create(evaluateDependencies) + +// import your own functions +math.import({ add, subtract, multiply, divide }, { override: true }) + +console.log(math.evaluate('2 + 3 * 4')) // 14 diff --git a/node_modules/mathjs/examples/advanced/custom_loading.js b/node_modules/mathjs/examples/advanced/custom_loading.js new file mode 100644 index 0000000..5c0d270 --- /dev/null +++ b/node_modules/mathjs/examples/advanced/custom_loading.js @@ -0,0 +1,33 @@ +import { + create, + fractionDependencies, + addDependencies, + divideDependencies, + formatDependencies +} from '../..' + +const config = { + // optionally, you can specify configuration +} + +// Create just the functions we need +const { fraction, add, divide, format } = create({ + fractionDependencies, + addDependencies, + divideDependencies, + formatDependencies +}, config) + +// Use the created functions +const a = fraction(1, 3) +const b = fraction(3, 7) +const c = add(a, b) +const d = divide(a, b) +console.log('c =', format(c)) // outputs "c = 16/21" +console.log('d =', format(d)) // outputs "d = 7/9" + +// Now, when bundling your application for use in the browser, only the used +// parts of math.js will be bundled. For example to create a bundle using Webpack: +// +// npx webpack custom_loading.js -o custom_loading.bundle.js --mode=production +// diff --git a/node_modules/mathjs/examples/advanced/custom_relational_functions.js b/node_modules/mathjs/examples/advanced/custom_relational_functions.js new file mode 100644 index 0000000..fbcb2ab --- /dev/null +++ b/node_modules/mathjs/examples/advanced/custom_relational_functions.js @@ -0,0 +1,62 @@ +const { create, all, factory } = require('../..') + +// First let's see what the default behavior is: +// strings are compared by their numerical value +console.log('default (compare string by their numerical value)') +const { evaluate } = create(all) +evaluateAndLog(evaluate, '2 < 10') // true +evaluateAndLog(evaluate, '"2" < "10"') // true +evaluateAndLog(evaluate, '"a" == "b"') // Error: Cannot convert "a" to a number +evaluateAndLog(evaluate, '"a" == "a"') // Error: Cannot convert "a" to a number +console.log('') + +// Suppose we want different behavior for string comparisons. To achieve +// this we can replace the factory functions for all relational functions +// with our own. In this simple example we use the JavaScript implementation. +console.log('custom (compare strings lexically)') + +const allWithCustomFunctions = { + ...all, + + createEqual: factory('equal', [], () => function equal (a, b) { + return a === b + }), + + createUnequal: factory('unequal', [], () => function unequal (a, b) { + return a !== b + }), + + createSmaller: factory('smaller', [], () => function smaller (a, b) { + return a < b + }), + + createSmallerEq: factory('smallerEq', [], () => function smallerEq (a, b) { + return a <= b + }), + + createLarger: factory('larger', [], () => function larger (a, b) { + return a > b + }), + + createLargerEq: factory('largerEq', [], () => function largerEq (a, b) { + return a >= b + }), + + createCompare: factory('compare', [], () => function compare (a, b) { + return a > b ? 1 : a < b ? -1 : 0 + }) +} +const evaluateCustom = create(allWithCustomFunctions).evaluate +evaluateAndLog(evaluateCustom, '2 < 10') // true +evaluateAndLog(evaluateCustom, '"2" < "10"') // false +evaluateAndLog(evaluateCustom, '"a" == "b"') // false +evaluateAndLog(evaluateCustom, '"a" == "a"') // true + +// helper function to evaluate an expression and print the results +function evaluateAndLog (evaluate, expression) { + try { + console.log(expression, evaluate(expression)) + } catch (err) { + console.error(expression, err.toString()) + } +} diff --git a/node_modules/mathjs/examples/advanced/custom_scope_objects.js b/node_modules/mathjs/examples/advanced/custom_scope_objects.js new file mode 100644 index 0000000..2114d04 --- /dev/null +++ b/node_modules/mathjs/examples/advanced/custom_scope_objects.js @@ -0,0 +1,115 @@ +const { create, all } = require('../..') + +const math = create(all) + +// The expression evaluator accepts an optional scope object. +// This is the symbol table for variable defintions and function declations. + +// Scope can be a bare object. +function withObjectScope () { + const scope = { x: 3 } + + math.evaluate('x', scope) // 1 + math.evaluate('y = 2 x', scope) + math.evaluate('scalar = 1', scope) + math.evaluate('area(length, width) = length * width * scalar', scope) + math.evaluate('A = area(x, y)', scope) + + console.log('Object scope:', scope) +} + +// Where flexibility is important, scope can duck type appear to be a Map. +function withMapScope (scope, name) { + scope.set('x', 3) + + math.evaluate('x', scope) // 1 + math.evaluate('y = 2 x', scope) + math.evaluate('scalar = 1', scope) + math.evaluate('area(length, width) = length * width * scalar', scope) + math.evaluate('A = area(x, y)', scope) + + console.log(`Map-like scope (${name}):`, scope.localScope) +} + +// This is a minimal set of functions to look like a Map. +class MapScope { + constructor () { + this.localScope = new Map() + } + + get (key) { + // Remember to sanitize your inputs, or use + // a datastructure that isn't a footgun. + return this.localScope.get(key) + } + + set (key, value) { + return this.localScope.set(key, value) + } + + has (key) { + return this.localScope.has(key) + } + + keys () { + return this.localScope.keys() + } +} + +/* + * This is a more fully featured example, with all methods + * used in mathjs. + * + */ +class AdvancedMapScope extends MapScope { + constructor (parent) { + super() + this.parentScope = parent + } + + get (key) { + return this.localScope.get(key) ?? this.parentScope?.get(key) + } + + has (key) { + return this.localScope.has(key) ?? this.parentScope?.get(key) + } + + keys () { + if (this.parentScope) { + return new Set([...this.localScope.keys(), ...this.parentScope.keys()]) + } else { + return this.localScope.keys() + } + } + + delete () { + return this.localScope.delete() + } + + clear () { + return this.localScope.clear() + } + + /** + * Creates a child scope from this one. This is used in function calls. + * + * @returns a new Map scope that has access to the symbols in the parent, but + * cannot overwrite them. + */ + createSubScope () { + return new AdvancedMapScope(this) + } + + toString () { + return this.localScope.toString() + } +} + +withObjectScope() +// Where safety is important, scope can also be a Map +withMapScope(new Map(), 'simple Map') +// Where flexibility is important, scope can duck type appear to be a Map. +withMapScope(new MapScope(), 'MapScope example') +// Extra methods allow even finer grain control. +withMapScope(new AdvancedMapScope(), 'AdvancedScope example') diff --git a/node_modules/mathjs/examples/advanced/expression_trees.js b/node_modules/mathjs/examples/advanced/expression_trees.js new file mode 100644 index 0000000..eaa956b --- /dev/null +++ b/node_modules/mathjs/examples/advanced/expression_trees.js @@ -0,0 +1,55 @@ +const { parse, ConstantNode } = require('../..') + +// Filter an expression tree +console.log('Filter all symbol nodes "x" in the expression "x^2 + x/4 + 3*y"') +const node = parse('x^2 + x/4 + 3*y') +const filtered = node.filter(function (node) { + return node.isSymbolNode && node.name === 'x' +}) +// returns an array with two entries: two SymbolNodes 'x' + +filtered.forEach(function (node) { + console.log(node.type, node.toString()) +}) +// outputs: +// SymbolNode x +// SymbolNode x + +// Traverse an expression tree +console.log() +console.log('Traverse the expression tree of expression "3 * x + 2"') +const node1 = parse('3 * x + 2') +node1.traverse(function (node, path, parent) { + switch (node.type) { + case 'OperatorNode': + console.log(node.type, node.op) + break + case 'ConstantNode': + console.log(node.type, node.value) + break + case 'SymbolNode': + console.log(node.type, node.name) + break + default: console.log(node.type) + } +}) +// outputs: +// OperatorNode + +// OperatorNode * +// ConstantNode 3 +// SymbolNode x +// ConstantNode 2 + +// transform an expression tree +console.log() +console.log('Replace all symbol nodes "x" in expression "x^2 + 5*x" with a constant 3') +const node2 = parse('x^2 + 5*x') +const transformed = node2.transform(function (node, path, parent) { + if (node.isSymbolNode && node.name === 'x') { + return new ConstantNode(3) + } else { + return node + } +}) +console.log(transformed.toString()) +// outputs: '3 ^ 2 + 5 * 3' diff --git a/node_modules/mathjs/examples/advanced/function_transform.js b/node_modules/mathjs/examples/advanced/function_transform.js new file mode 100644 index 0000000..ae212f2 --- /dev/null +++ b/node_modules/mathjs/examples/advanced/function_transform.js @@ -0,0 +1,50 @@ +/** + * Function transforms + * + * When using functions via the expression parser, it is possible to preprocess + * function arguments and post process a functions return value by writing a + * *transform* for the function. A transform is a function wrapping around a + * function to be transformed or completely replaces a function. + */ +const { create, all } = require('../..') +const math = create(all) + +// create a function +function addIt (a, b) { + return a + b +} + +// attach a transform function to the function addIt +addIt.transform = function (a, b) { + console.log('input: a=' + a + ', b=' + b) + // we can manipulate the input arguments here before executing addIt + + const res = addIt(a, b) + + console.log('result: ' + res) + // we can manipulate the result here before returning + + return res +} + +// import the function into math.js +math.import({ + addIt: addIt +}) + +// use the function via the expression parser +console.log('Using expression parser:') +console.log('2+4=' + math.evaluate('addIt(2, 4)')) +// This will output: +// +// input: a=2, b=4 +// result: 6 +// 2+4=6 + +// when used via plain JavaScript, the transform is not invoked +console.log('') +console.log('Using plain JavaScript:') +console.log('2+4=' + math.addIt(2, 4)) +// This will output: +// +// 6 diff --git a/node_modules/mathjs/examples/advanced/more_secure_eval.js b/node_modules/mathjs/examples/advanced/more_secure_eval.js new file mode 100644 index 0000000..46329ba --- /dev/null +++ b/node_modules/mathjs/examples/advanced/more_secure_eval.js @@ -0,0 +1,36 @@ +// Expression parser security +// +// Executing arbitrary expressions like enabled by the expression parser of +// mathjs involves a risk in general. When you're using mathjs to let users +// execute arbitrary expressions, it's good to take a moment to think about +// possible security and stability implications, especially when running the +// code server side. +// +// There is a small number of functions which yield the biggest security risk +// in the expression parser of math.js: +// +// - `import` and `createUnit` which alter the built-in functionality and allow +// overriding existing functions and units. +// - `evaluate`, `parse`, `simplify`, and `derivative` which parse arbitrary input +// into a manipulable expression tree. +// +// To make the expression parser less vulnerable whilst still supporting most +// functionality, these functions can be disabled, as demonstrated in this +// example. + +const { create, all } = require('../..') +const math = create(all) + +const limitedEvaluate = math.evaluate + +math.import({ + import: function () { throw new Error('Function import is disabled') }, + createUnit: function () { throw new Error('Function createUnit is disabled') }, + evaluate: function () { throw new Error('Function evaluate is disabled') }, + parse: function () { throw new Error('Function parse is disabled') }, + simplify: function () { throw new Error('Function simplify is disabled') }, + derivative: function () { throw new Error('Function derivative is disabled') } +}, { override: true }) + +console.log(limitedEvaluate('sqrt(16)')) // Ok, 4 +console.log(limitedEvaluate('parse("2+3")')) // Error: Function parse is disabled diff --git a/node_modules/mathjs/examples/advanced/use_bigint.js b/node_modules/mathjs/examples/advanced/use_bigint.js new file mode 100644 index 0000000..79780fa --- /dev/null +++ b/node_modules/mathjs/examples/advanced/use_bigint.js @@ -0,0 +1,43 @@ +// This example demonstrates how you could integrate support for BigInt +// in mathjs. It's just a proof of concept, for full support you will +// have to defined more functions and define conversions from and to +// other data types. + +const { create, all, factory } = require('../..') +const math = create(all) + +// we can also add conversions here from number or string to BigInt +// and vice versa using math.typed.addConversion(...) + +math.import([ + factory('BigInt', ['typed'], function createBigInt ({ typed }) { + typed.addType({ + name: 'BigInt', + test: (x) => typeof x === 'bigint' // eslint-disable-line + }) + + return BigInt // eslint-disable-line + }, { lazy: false }), + + factory('bigint', ['typed', 'BigInt'], function createBigint ({ typed, BigInt }) { + return typed('bigint', { + 'number | string ': (x) => BigInt(x) // eslint-disable-line + }) + }), + + factory('add', ['typed'], function createBigIntAdd ({ typed }) { + return typed('add', { + 'BigInt, BigInt': (a, b) => a + b + }) + }), + + factory('pow', ['typed'], function createBigIntPow ({ typed }) { + return typed('pow', { + 'BigInt, BigInt': (a, b) => a ** b + }) + }) +]) + +console.log(math.evaluate('4349 + 5249')) +console.log(math.evaluate('bigint(4349) + bigint(5249)')) +console.log(math.evaluate('bigint(4349) ^ bigint(5249)')) diff --git a/node_modules/mathjs/examples/advanced/web_server/math_worker.js b/node_modules/mathjs/examples/advanced/web_server/math_worker.js new file mode 100644 index 0000000..56cd497 --- /dev/null +++ b/node_modules/mathjs/examples/advanced/web_server/math_worker.js @@ -0,0 +1,24 @@ +const { create, all } = require('../../..') +const workerpool = require('workerpool') +const math = create(all) + +// disable the import function so the math.js instance cannot be changed +function noImport () { + throw new Error('function import is disabled.') +} +math.import({ import: noImport }, { override: true }) + +/** + * Evaluate an expression + * @param {string} expr + * @return {string} result + */ +function evaluate (expr) { + const ans = math.evaluate(expr) + return math.format(ans) +} + +// create a worker and register public functions +workerpool.worker({ + evaluate: evaluate +}) diff --git a/node_modules/mathjs/examples/advanced/web_server/server.js b/node_modules/mathjs/examples/advanced/web_server/server.js new file mode 100644 index 0000000..24dba89 --- /dev/null +++ b/node_modules/mathjs/examples/advanced/web_server/server.js @@ -0,0 +1,80 @@ +/** + * This example demonstrates how to run math.js in a child process with limited + * execution time. + * + * Prerequisites: + * + * npm install express workerpool + * + * Start the server: + * + * node ./server.js + * + * Make a request to the server: + * + * GET http://localhost:8080/mathjs?expr=sqrt(16) + * + * Note that the query parameter `expr` should be properly url encoded. + */ +const path = require('path') + +let express +let workerpool +try { + express = require('express') + workerpool = require('workerpool') +} catch (err) { + console.log('Error: To run this example, install express and workerpool first via:\n\n' + + ' npm install express workerpool\n') + process.exit() +} + +const app = express() +const pool = workerpool.pool(path.join(__dirname, '/math_worker.js')) + +const TIMEOUT = 10000 // milliseconds + +/** + * GET /mathjs?expr=... + */ +app.get('/mathjs', function (req, res) { + const expr = req.query.expr + if (expr === undefined) { + return res.status(400).send('Error: Required query parameter "expr" missing in url.') + } + + pool.exec('evaluate', [expr]) + .timeout(TIMEOUT) + .then(function (result) { + res.send(result) + }) + .catch(function (err) { + res.status(400).send(formatError(err)) + }) +}) + +/** + * Format error messages as string + * @param {Error} err + * @return {String} message + */ +function formatError (err) { + if (err instanceof workerpool.Promise.TimeoutError) { + return 'TimeoutError: Evaluation exceeded maximum duration of ' + TIMEOUT / 1000 + ' seconds' + } else { + return err.toString() + } +} + +// handle uncaught exceptions so the application cannot crash +process.on('uncaughtException', function (err) { + console.log('Caught exception: ' + err) + console.trace() +}) + +// start the server +const PORT = process.env.PORT || 8080 +app.listen(PORT, function () { + console.log('Listening at http://localhost:' + PORT) + console.log('Example request:\n GET http://localhost:' + PORT + '/mathjs?expr=sqrt(16)') +}) diff --git a/node_modules/mathjs/examples/algebra.js b/node_modules/mathjs/examples/algebra.js new file mode 100644 index 0000000..080c47d --- /dev/null +++ b/node_modules/mathjs/examples/algebra.js @@ -0,0 +1,34 @@ +// algebra +// +// math.js has support for symbolic computation (CAS). It can parse +// expressions in an expression tree and do algebraic operations like +// simplification and derivation on this tree. + +// load math.js (using node.js) +const { simplify, parse, derivative } = require('..') + +// simplify an expression +console.log('simplify expressions') +console.log(simplify('3 + 2 / 4').toString()) // '7 / 2' +console.log(simplify('2x + 3x').toString()) // '5 * x' +console.log(simplify('2 * 3 * x', { x: 4 }).toString()) // '24' +console.log(simplify('x^2 + x + 3 + x^2').toString()) // '2 * x ^ 2 + x + 3' +console.log(simplify('x * y * -x / (x ^ 2)').toString()) // '-y' + +// work with an expression tree, evaluate results +const f = parse('2x + x') +const simplified = simplify(f) +console.log(simplified.toString()) // '3 * x' +console.log(simplified.evaluate({ x: 4 })) // 12 +console.log() + +// calculate a derivative +console.log('calculate derivatives') +console.log(derivative('2x^2 + 3x + 4', 'x').toString()) // '4 * x + 3' +console.log(derivative('sin(2x)', 'x').toString()) // '2 * cos(2 * x)' + +// work with an expression tree, evaluate results +const h = parse('x^2 + x') +const dh = derivative(h, 'x') +console.log(dh.toString()) // '2 * x + 1' +console.log(dh.evaluate({ x: 3 })) // '7' diff --git a/node_modules/mathjs/examples/basic_usage.js b/node_modules/mathjs/examples/basic_usage.js new file mode 100644 index 0000000..82af46d --- /dev/null +++ b/node_modules/mathjs/examples/basic_usage.js @@ -0,0 +1,49 @@ +// basic usage + +// load math.js (using node.js) +const math = require('..') + +// functions and constants +console.log('functions and constants') +print(math.round(math.e, 3)) // 2.718 +print(math.atan2(3, -3) / math.pi) // 0.75 +print(math.log(10000, 10)) // 4 +print(math.sqrt(-4)) // 2i +print(math.pow([[-1, 2], [3, 1]], 2)) // [[7, 0], [0, 7]] +print(math.derivative('x^2 + x', 'x')) // 2 * x + 1 +console.log() + +// expressions +console.log('expressions') +print(math.evaluate('1.2 * (2 + 4.5)')) // 7.8 +print(math.evaluate('12.7 cm to inch')) // 5 inch +print(math.evaluate('sin(45 deg) ^ 2')) // 0.5 +print(math.evaluate('9 / 3 + 2i')) // 3 + 2i +print(math.evaluate('det([-1, 2; 3, 1])')) // -7 +console.log() + +// chained operations +console.log('chained operations') +const a = math.chain(3) + .add(4) + .multiply(2) + .done() +print(a) // 14 +console.log() + +// mixed use of different data types in functions +console.log('mixed use of data types') +print(math.add(4, [5, 6])) // number + Array, [9, 10] +print(math.multiply(math.unit('5 mm'), 3)) // Unit * number, 15 mm +print(math.subtract([2, 3, 4], 5)) // Array - number, [-3, -2, -1] +print(math.add(math.matrix([2, 3]), [4, 5])) // Matrix + Array, [6, 8] +console.log() + +/** + * Helper function to output a value in the console. Value will be formatted. + * @param {*} value + */ +function print (value) { + const precision = 14 + console.log(math.format(value, precision)) +} diff --git a/node_modules/mathjs/examples/bignumbers.js b/node_modules/mathjs/examples/bignumbers.js new file mode 100644 index 0000000..bebc210 --- /dev/null +++ b/node_modules/mathjs/examples/bignumbers.js @@ -0,0 +1,52 @@ +/* eslint-disable no-loss-of-precision */ + +// BigNumbers + +const { create, all } = require('..') + +// configure the default type of numbers as BigNumbers +const config = { + // Default type of number + // Available options: 'number' (default), 'BigNumber', or 'Fraction' + number: 'BigNumber', + + // Number of significant digits for BigNumbers + precision: 20 +} +const math = create(all, config) + +console.log('round-off errors with numbers') +print(math.add(0.1, 0.2)) // number, 0.30000000000000004 +print(math.divide(0.3, 0.2)) // number, 1.4999999999999998 +console.log() + +console.log('no round-off errors with BigNumbers') +print(math.add(math.bignumber(0.1), math.bignumber(0.2))) // BigNumber, 0.3 +print(math.divide(math.bignumber(0.3), math.bignumber(0.2))) // BigNumber, 1.5 +console.log() + +console.log('create BigNumbers from strings when exceeding the range of a number') +print(math.bignumber(1.2e+500)) // BigNumber, Infinity WRONG +print(math.bignumber('1.2e+500')) // BigNumber, 1.2e+500 +console.log() + +console.log('BigNumbers still have a limited precision and are no silve bullet') +const third = math.divide(math.bignumber(1), math.bignumber(3)) +const total = math.add(third, third, third) +print(total) // BigNumber, 0.99999999999999999999 +console.log() + +// one can work conveniently with BigNumbers using the expression parser. +// note though that BigNumbers are only supported in arithmetic functions +console.log('use BigNumbers in the expression parser') +print(math.evaluate('0.1 + 0.2')) // BigNumber, 0.3 +print(math.evaluate('0.3 / 0.2')) // BigNumber, 1.5 +console.log() + +/** + * Helper function to output a value in the console. Value will be formatted. + * @param {*} value + */ +function print (value) { + console.log(math.format(value)) +} diff --git a/node_modules/mathjs/examples/browser/angle_configuration.html b/node_modules/mathjs/examples/browser/angle_configuration.html new file mode 100644 index 0000000..d5f66cd --- /dev/null +++ b/node_modules/mathjs/examples/browser/angle_configuration.html @@ -0,0 +1,134 @@ + + + + + math.js | angle configuration + + + + + + +

    + This code example extends the trigonometric functions of math.js with configurable angles: degrees, radians, or gradians. +

    + + + + + + + + + + + + + + +
    Angles + +
    Expression + + +
    Result
    + + + + + + \ No newline at end of file diff --git a/node_modules/mathjs/examples/browser/basic_usage.html b/node_modules/mathjs/examples/browser/basic_usage.html new file mode 100644 index 0000000..28ecc06 --- /dev/null +++ b/node_modules/mathjs/examples/browser/basic_usage.html @@ -0,0 +1,39 @@ + + + + + math.js | basic usage + + + + + + + + \ No newline at end of file diff --git a/node_modules/mathjs/examples/browser/currency_conversion.html b/node_modules/mathjs/examples/browser/currency_conversion.html new file mode 100644 index 0000000..4b826b8 --- /dev/null +++ b/node_modules/mathjs/examples/browser/currency_conversion.html @@ -0,0 +1,125 @@ + + + + + math.js | currency conversion + + + + + + + +

    Currency conversion with math.js

    + +

    + This example demonstrates how you can fetch actual currencies from fixer.io and use them in math.js. +

    + +

    + Create a (free) account at fixer.io and fill in your API access key below: +

    + +
    + + +
    + +

    +

    + + + + + \ No newline at end of file diff --git a/node_modules/mathjs/examples/browser/custom_separators.html b/node_modules/mathjs/examples/browser/custom_separators.html new file mode 100644 index 0000000..e81a813 --- /dev/null +++ b/node_modules/mathjs/examples/browser/custom_separators.html @@ -0,0 +1,81 @@ + + + + + math.js | custom separators + + + + + + +

    + This code example shows how to apply custom separators for function arguments and decimal separator. +

    + + + + + + + + + + + + + + + + + + +
    Argument separator + +
    Decimal separator + +
    Expression + + +
    Result
    + + + + + + \ No newline at end of file diff --git a/node_modules/mathjs/examples/browser/plot.html b/node_modules/mathjs/examples/browser/plot.html new file mode 100644 index 0000000..eefc6bb --- /dev/null +++ b/node_modules/mathjs/examples/browser/plot.html @@ -0,0 +1,78 @@ + + + + + math.js | plot + + + + + + + + +
    + + + +
    + +
    + +

    + Used plot library: Plotly +

    + + + + + diff --git a/node_modules/mathjs/examples/browser/pretty_printing_with_mathjax.html b/node_modules/mathjs/examples/browser/pretty_printing_with_mathjax.html new file mode 100644 index 0000000..1fa2732 --- /dev/null +++ b/node_modules/mathjs/examples/browser/pretty_printing_with_mathjax.html @@ -0,0 +1,122 @@ + + + + + math.js | pretty printing with MathJax + + + + + + + + + +

    + Expression evaluation with math.js, pretty printing with MathJax +

    + + + + + + + + + + + + + + +
    Expression
    Pretty print
    Result
    +Parenthesis option: +keep +auto +all +
    +Implicit multiplication: +hide +show + + + + + + diff --git a/node_modules/mathjs/examples/browser/printing_html.html b/node_modules/mathjs/examples/browser/printing_html.html new file mode 100644 index 0000000..4cf2cdf --- /dev/null +++ b/node_modules/mathjs/examples/browser/printing_html.html @@ -0,0 +1,170 @@ + + + + + math.js | printing HTML + + + + + + +

    Expression evaluation and HTML code generation with math.js

    +
    +
    + Parenthesis option: + + + +
    +
    + Implicit multiplication: + + +
    +
    + + + + + + + + + + + + + + + + + +
    Expression
    Result
    HTML output
    $$$$
    HTML code
    $$$$
    + + + diff --git a/node_modules/mathjs/examples/browser/requirejs_loading.html b/node_modules/mathjs/examples/browser/requirejs_loading.html new file mode 100644 index 0000000..76a1bb9 --- /dev/null +++ b/node_modules/mathjs/examples/browser/requirejs_loading.html @@ -0,0 +1,20 @@ + + + + + math.js | require.js loading + + + + + + + + \ No newline at end of file diff --git a/node_modules/mathjs/examples/browser/rocket_trajectory_optimization.html b/node_modules/mathjs/examples/browser/rocket_trajectory_optimization.html new file mode 100644 index 0000000..7c98c48 --- /dev/null +++ b/node_modules/mathjs/examples/browser/rocket_trajectory_optimization.html @@ -0,0 +1,301 @@ + + + + + + math.js | rocket trajectory optimization + + + + + + + + +

    Rocket trajectory optimization

    +

    + This example simulates the launch of a SpaceX Falcon 9 modeled using a system of ordinary differential equations. +

    + + +
    + + + + + \ No newline at end of file diff --git a/node_modules/mathjs/examples/browser/webworkers/webworkers.html b/node_modules/mathjs/examples/browser/webworkers/webworkers.html new file mode 100644 index 0000000..26a230c --- /dev/null +++ b/node_modules/mathjs/examples/browser/webworkers/webworkers.html @@ -0,0 +1,80 @@ + + + + + math.js | web workers + + + +

    + In this example, a math.js parser is running in a separate + web worker, + preventing the user interface from freezing during heavy calculations. +

    + +

    + + + + + \ No newline at end of file diff --git a/node_modules/mathjs/examples/browser/webworkers/worker.js b/node_modules/mathjs/examples/browser/webworkers/worker.js new file mode 100644 index 0000000..0af5d85 --- /dev/null +++ b/node_modules/mathjs/examples/browser/webworkers/worker.js @@ -0,0 +1,28 @@ +importScripts('../../../lib/browser/math.js') + +// create a parser +const parser = self.math.parser() + +self.addEventListener('message', function (event) { + const request = JSON.parse(event.data) + let result = null + let err = null + + try { + // evaluate the expression + result = parser.evaluate(request.expr) + } catch (e) { + // return the error + err = e + } + + // build a response + const response = { + id: request.id, + result: self.math.format(result), + err: err + } + + // send the response back + self.postMessage(JSON.stringify(response)) +}, false) diff --git a/node_modules/mathjs/examples/chaining.js b/node_modules/mathjs/examples/chaining.js new file mode 100644 index 0000000..a46f9dd --- /dev/null +++ b/node_modules/mathjs/examples/chaining.js @@ -0,0 +1,56 @@ +// chaining + +// load math.js (using node.js) +const math = require('..') + +// create a chained operation using the function `chain(value)` +// end a chain using done(). Let's calculate (3 + 4) * 2 +const a = math.chain(3) + .add(4) + .multiply(2) + .done() +print(a) // 14 + +// Another example, calculate square(sin(pi / 4)) +const b = math.chain(math.pi) + .divide(4) + .sin() + .square() + .done() +print(b) // 0.5 + +// A chain has a few special methods: done, toString, valueOf, get, and set. +// these are demonstrated in the following examples + +// toString will return a string representation of the chain's value +const chain = math.chain(2).divide(3) +const str = chain.toString() +print(str) // "0.6666666666666666" + +// a chain has a function .valueOf(), which returns the value hold by the chain. +// This allows using it in regular operations. The function valueOf() acts the +// same as function done(). +print(chain.valueOf()) // 0.66666666666667 +print(chain + 2) // 2.6666666666667 + +// the function subset can be used to get or replace sub matrices +const array = [[1, 2], [3, 4]] +const v = math.chain(array) + .subset(math.index(1, 0)) + .done() +print(v) // 3 + +const m = math.chain(array) + .subset(math.index(0, 0), 8) + .multiply(3) + .done() +print(m) // [[24, 6], [9, 12]] + +/** + * Helper function to output a value in the console. Value will be formatted. + * @param {*} value + */ +function print (value) { + const precision = 14 + console.log(math.format(value, precision)) +} diff --git a/node_modules/mathjs/examples/complex_numbers.js b/node_modules/mathjs/examples/complex_numbers.js new file mode 100644 index 0000000..7480002 --- /dev/null +++ b/node_modules/mathjs/examples/complex_numbers.js @@ -0,0 +1,67 @@ +// complex numbers + +// load js (using node.js) +const { complex, add, multiply, sin, sqrt, pi, equal, sort, format } = require('..') + +// create a complex number with a numeric real and complex part +console.log('create and manipulate complex numbers') +const a = complex(2, 3) +print(a) // 2 + 3i + +// read the real and complex parts of the complex number +print(a.re) // 2 +print(a.im) // 3 + +// clone a complex value +const clone = a.clone() +print(clone) // 2 + 3i + +// adjust the complex value +a.re = 5 +print(a) // 5 + 3i + +// create a complex number by providing a string with real and complex parts +const b = complex('3-7i') +print(b) // 3 - 7i +console.log() + +// perform operations with complex numbers +console.log('perform operations') +print(add(a, b)) // 8 - 4i +print(multiply(a, b)) // 36 - 26i +print(sin(a)) // -9.6541254768548 + 2.8416922956064i + +// some operations will return a complex number depending on the arguments +print(sqrt(4)) // 2 +print(sqrt(-4)) // 2i +console.log() + +// create a complex number from polar coordinates +console.log('create complex numbers with polar coordinates') +const c = complex({ r: sqrt(2), phi: pi / 4 }) +print(c) // 1 + i + +// get polar coordinates of a complex number +const d = complex(3, 4) +console.log(d.abs(), d.arg()) // radius = 5, phi = 0.9272952180016122 +console.log() + +// comparision operations +// note that there is no mathematical ordering defined for complex numbers +// we can only check equality. To sort a list with complex numbers, +// the natural sorting can be used +console.log('\ncomparision and sorting operations') +console.log('equal', equal(a, b)) // returns false +const values = [a, b, c] +console.log('values:', format(values, 14)) // [5 + 3i, 3 - 7i, 1 + i] +sort(values, 'natural') +console.log('sorted:', format(values, 14)) // [1 + i, 3 - 7i, 5 + 3i] + +/** + * Helper function to output a value in the console. Value will be formatted. + * @param {*} value + */ +function print (value) { + const precision = 14 + console.log(format(value, precision)) +} diff --git a/node_modules/mathjs/examples/expressions.js b/node_modules/mathjs/examples/expressions.js new file mode 100644 index 0000000..2f8500b --- /dev/null +++ b/node_modules/mathjs/examples/expressions.js @@ -0,0 +1,188 @@ +/** + * Expressions can be evaluated in various ways: + * + * 1. using the function math.evaluate + * 2. using the function math.parse + * 3. using a parser. A parser contains functions evaluate and parse, + * and keeps a scope with assigned variables in memory + */ + +// load math.js (using node.js) +const math = require('..') + +// 1. using the function math.evaluate +// +// Function `evaluate` accepts a single expression or an array with +// expressions as first argument, and has an optional second argument +// containing a scope with variables and functions. The scope is a regular +// JavaScript Object. The scope will be used to resolve symbols, and to write +// assigned variables or function. +console.log('1. USING FUNCTION MATH.EVAL') + +// evaluate expressions +console.log('\nevaluate expressions') +print(math.evaluate('sqrt(3^2 + 4^2)')) // 5 +print(math.evaluate('sqrt(-4)')) // 2i +print(math.evaluate('2 inch to cm')) // 5.08 cm +print(math.evaluate('cos(45 deg)')) // 0.70711 + +// evaluate multiple expressions at once +console.log('\nevaluate multiple expressions at once') +print(math.evaluate([ + 'f = 3', + 'g = 4', + 'f * g' +])) // [3, 4, 12] + +// provide a scope (just a regular JavaScript Object) +console.log('\nevaluate expressions providing a scope with variables and functions') +const scope = { + a: 3, + b: 4 +} + +// variables can be read from the scope +print(math.evaluate('a * b', scope)) // 12 + +// variable assignments are written to the scope +print(math.evaluate('c = 2.3 + 4.5', scope)) // 6.8 +print(scope.c) // 6.8 + +// scope can contain both variables and functions +scope.hello = function (name) { + return 'hello, ' + name + '!' +} +print(math.evaluate('hello("hero")', scope)) // "hello, hero!" + +// define a function as an expression +const f = math.evaluate('f(x) = x ^ a', scope) +print(f(2)) // 8 +print(scope.f(2)) // 8 + +// 2. using function math.parse +// +// Function `math.parse` parses expressions into a node tree. The syntax is +// similar to function `math.evaluate`. +// Function `parse` accepts a single expression or an array with +// expressions as first argument. The function returns a node tree, which +// then can be compiled against math, and then evaluated against an (optional +// scope. This scope is a regular JavaScript Object. The scope will be used +// to resolve symbols, and to write assigned variables or function. +console.log('\n2. USING FUNCTION MATH.PARSE') + +// parse an expression +console.log('\nparse an expression into a node tree') +const node1 = math.parse('sqrt(3^2 + 4^2)') +print(node1.toString()) // "sqrt((3 ^ 2) + (4 ^ 2))" + +// compile and evaluate the compiled code +// you could also do this in two steps: node1.compile().evaluate() +print(node1.evaluate()) // 5 + +// provide a scope +console.log('\nprovide a scope') +const node2 = math.parse('x^a') +const code2 = node2.compile() +print(node2.toString()) // "x ^ a" +const scope2 = { + x: 3, + a: 2 +} +print(code2.evaluate(scope2)) // 9 + +// change a value in the scope and re-evaluate the node +scope2.a = 3 +print(code2.evaluate(scope2)) // 27 + +// 3. using function math.compile +// +// Function `math.compile` compiles expressions into a node tree. The syntax is +// similar to function `math.evaluate`. +// Function `compile` accepts a single expression or an array with +// expressions as first argument, and returns an object with a function evaluate +// to evaluate the compiled expression. On evaluation, an optional scope can +// be provided. This scope will be used to resolve symbols, and to write +// assigned variables or function. +console.log('\n3. USING FUNCTION MATH.COMPILE') + +// parse an expression +console.log('\ncompile an expression') +const code3 = math.compile('sqrt(3^2 + 4^2)') + +// evaluate the compiled code +print(code3.evaluate()) // 5 + +// provide a scope for the variable assignment +console.log('\nprovide a scope') +const code4 = math.compile('a = a + 3') +const scope3 = { + a: 7 +} +code4.evaluate(scope3) +print(scope3.a) // 10 + +// 4. using a parser +// +// In addition to the static functions `math.evaluate` and `math.parse`, math.js +// contains a parser with functions `evaluate` and `parse`, which automatically +// keeps a scope with assigned variables in memory. The parser also contains +// some convenience methods to get, set, and remove variables from memory. +console.log('\n4. USING A PARSER') +const parser = math.parser() + +// evaluate with parser +console.log('\nevaluate expressions') +print(parser.evaluate('sqrt(3^2 + 4^2)')) // 5 +print(parser.evaluate('sqrt(-4)')) // 2i +print(parser.evaluate('2 inch to cm')) // 5.08 cm +print(parser.evaluate('cos(45 deg)')) // 0.70710678118655 + +// define variables and functions +console.log('\ndefine variables and functions') +print(parser.evaluate('x = 7 / 2')) // 3.5 +print(parser.evaluate('x + 3')) // 6.5 +print(parser.evaluate('f2(x, y) = x^y')) // f2(x, y) +print(parser.evaluate('f2(2, 3)')) // 8 + +// manipulate matrices +// Note that matrix indexes in the expression parser are one-based with the +// upper-bound included. On a JavaScript level however, math.js uses zero-based +// indexes with an excluded upper-bound. +console.log('\nmanipulate matrices') +print(parser.evaluate('k = [1, 2; 3, 4]')) // [[1, 2], [3, 4]] +print(parser.evaluate('l = zeros(2, 2)')) // [[0, 0], [0, 0]] +print(parser.evaluate('l[1, 1:2] = [5, 6]')) // [5, 6] +print(parser.evaluate('l')) // [[5, 6], [0, 0]] +print(parser.evaluate('l[2, :] = [7, 8]')) // [7, 8] +print(parser.evaluate('l')) // [[5, 6], [7, 8]] +print(parser.evaluate('m = k * l')) // [[19, 22], [43, 50]] +print(parser.evaluate('n = m[2, 1]')) // 43 +print(parser.evaluate('n = m[:, 1]')) // [[19], [43]] + +// get and set variables and functions +console.log('\nget and set variables and function in the scope of the parser') +const x = parser.get('x') +console.log('x =', x) // x = 3.5 +const f2 = parser.get('f2') +console.log('f2 =', math.format(f2)) // f2 = f2(x, y) +const h = f2(3, 3) +console.log('h =', h) // h = 27 + +parser.set('i', 500) +print(parser.evaluate('i / 2')) // 250 +parser.set('hello', function (name) { + return 'hello, ' + name + '!' +}) +print(parser.evaluate('hello("hero")')) // "hello, hero!" + +// clear defined functions and variables +parser.clear() + +/** + * Helper function to output a value in the console. Value will be formatted. + * @param {*} value + */ +function print (value) { + const precision = 14 + console.log(math.format(value, precision)) +} diff --git a/node_modules/mathjs/examples/fractions.js b/node_modules/mathjs/examples/fractions.js new file mode 100644 index 0000000..73aed71 --- /dev/null +++ b/node_modules/mathjs/examples/fractions.js @@ -0,0 +1,74 @@ +// Fractions + +// load math.js (using node.js) +const { create, all } = require('..') + +// configure the default type of numbers as Fractions +const config = { + // Default type of number + // Available options: 'number' (default), 'BigNumber', or 'Fraction' + number: 'Fraction' +} + +// create a mathjs instance with everything included +const math = create(all, config) + +console.log('basic usage') +printRatio(math.fraction(0.125)) // Fraction, 1/8 +printRatio(math.fraction(0.32)) // Fraction, 8/25 +printRatio(math.fraction('1/3')) // Fraction, 1/3 +printRatio(math.fraction('0.(3)')) // Fraction, 1/3 +printRatio(math.fraction(2, 3)) // Fraction, 2/3 +printRatio(math.fraction('0.(285714)')) // Fraction, 2/7 +console.log() + +console.log('round-off errors with numbers') +print(math.add(0.1, 0.2)) // number, 0.30000000000000004 +print(math.divide(0.3, 0.2)) // number, 1.4999999999999998 +console.log() + +console.log('no round-off errors with fractions :)') +print(math.add(math.fraction(0.1), math.fraction(0.2))) // Fraction, 0.3 +print(math.divide(math.fraction(0.3), math.fraction(0.2))) // Fraction, 1.5 +console.log() + +console.log('represent an infinite number of repeating digits') +print(math.fraction('1/3')) // Fraction, 0.(3) +print(math.fraction('2/7')) // Fraction, 0.(285714) +print(math.fraction('23/11')) // Fraction, 2.(09) +console.log() + +// one can work conveniently with fractions using the expression parser. +// note though that Fractions are only supported by basic arithmetic functions +console.log('use fractions in the expression parser') +printRatio(math.evaluate('0.1 + 0.2')) // Fraction, 3/10 +printRatio(math.evaluate('0.3 / 0.2')) // Fraction, 3/2 +printRatio(math.evaluate('23 / 11')) // Fraction, 23/11 +console.log() + +// output formatting +console.log('output formatting of fractions') +const a = math.fraction('2/3') +console.log(math.format(a)) // Fraction, 2/3 +console.log(math.format(a, { fraction: 'ratio' })) // Fraction, 2/3 +console.log(math.format(a, { fraction: 'decimal' })) // Fraction, 0.(6) +console.log(a.toString()) // Fraction, 0.(6) +console.log() + +/** + * Helper function to output a value in the console. + * Fractions will be formatted as ratio, like '1/3'. + * @param {*} value + */ +function printRatio (value) { + console.log(math.format(value, { fraction: 'ratio' })) +} + +/** + * Helper function to output a value in the console. + * Fractions will be formatted as decimal, like '0.(3)'. + * @param {*} value + */ +function print (value) { + console.log(math.format(value, { fraction: 'decimal' })) +} diff --git a/node_modules/mathjs/examples/import.js b/node_modules/mathjs/examples/import.js new file mode 100644 index 0000000..351cc09 --- /dev/null +++ b/node_modules/mathjs/examples/import.js @@ -0,0 +1,95 @@ +/** + * Math.js can easily be extended with functions and variables using the + * `import` function. The function `import` accepts a module name or an object + * containing functions and variables. + */ + +// load math.js (using node.js) +const { create, all } = require('..') +const math = create(all) + +/** + * Define new functions and variables + */ +math.import({ + myConstant: 42, + hello: function (name) { + return 'hello, ' + name + '!' + } +}) + +// defined methods can be used in both JavaScript as well as the parser +print(math.myConstant * 2) // 84 +print(math.hello('user')) // 'hello, user!' + +print(math.evaluate('myConstant + 10')) // 52 +print(math.evaluate('hello("user")')) // 'hello, user!' + +/** + * Import the math library numbers.js, https://github.com/sjkaliski/numbers.js + * The library must be installed first using npm: + * npm install numbers + */ +try { + // load the numbers.js library + const numbers = require('numbers') + + // import the numbers.js library into math.js + math.import(numbers, { wrap: true, silent: true }) + + if (math.fibonacci) { + // calculate fibonacci + print(math.fibonacci(7)) // 13 + print(math.evaluate('fibonacci(7)')) // 13 + } +} catch (err) { + console.log('Warning: To use numbers.js, the library must ' + + 'be installed first via `npm install numbers`.') +} + +/** + * Import the math library numeric.js, https://github.com/sloisel/numeric + * The library must be installed first using npm: + * npm install numeric + */ +try { + // load the numeric.js library + const numeric = require('numeric') + + // import the numeric.js library into math.js + math.import(numeric, { wrap: true, silent: true }) + + if (math.eig) { + // calculate eigenvalues of a matrix + print(math.evaluate('eig([1, 2; 4, 3])').lambda.x) // [5, -1] + + // solve AX = b + const A = math.evaluate('[1, 2, 3; 2, -1, 1; 3, 0, -1]') + const b = [9, 8, 3] + print(math.solve(A, b)) // [2, -1, 3] + } +} catch (err) { + console.log('Warning: To use numeric.js, the library must ' + + 'be installed first via `npm install numeric`.') +} + +/** + * By default, the function import does not allow overriding existing functions. + * Existing functions can be overridden by specifying option `override: true` + */ +math.import({ + pi: 3.14 +}, { + override: true +}) + +print(math.pi) // returns 3.14 instead of 3.141592653589793 + +/** + * Helper function to output a value in the console. Value will be formatted. + * @param {*} value + */ +function print (value) { + const precision = 14 + console.log(math.format(value, precision)) +} diff --git a/node_modules/mathjs/examples/matrices.js b/node_modules/mathjs/examples/matrices.js new file mode 100644 index 0000000..0e69021 --- /dev/null +++ b/node_modules/mathjs/examples/matrices.js @@ -0,0 +1,101 @@ +// matrices + +// load math.js (using node.js) +const math = require('..') + +// create matrices and arrays. a matrix is just a wrapper around an Array, +// providing some handy utilities. +console.log('create a matrix') +const a = math.matrix([1, 4, 9, 16, 25]) +print(a) // [1, 4, 9, 16, 25] +const b = math.matrix(math.ones([2, 3])) +print(b) // [[1, 1, 1], [1, 1, 1]] +print(b.size()) // [2, 3] + +// the Array data of a Matrix can be retrieved using valueOf() +const array = a.valueOf() +print(array) // [1, 4, 9, 16, 25] + +// Matrices can be cloned +const clone = a.clone() +print(clone) // [1, 4, 9, 16, 25] +console.log() + +// perform operations with matrices +console.log('perform operations') +print(math.sqrt(a)) // [1, 2, 3, 4, 5] +const c = [1, 2, 3, 4, 5] +print(math.factorial(c)) // [1, 2, 6, 24, 120] +console.log() + +// create and manipulate matrices. Arrays and Matrices can be used mixed. +console.log('manipulate matrices') +const d = [[1, 2], [3, 4]] +print(d) // [[1, 2], [3, 4]] +const e = math.matrix([[5, 6], [1, 1]]) +print(e) // [[5, 6], [1, 1]] + +// set a submatrix. +// Matrix indexes are zero-based. +e.subset(math.index(1, [0, 1]), [[7, 8]]) +print(e) // [[5, 6], [7, 8]] +const f = math.multiply(d, e) +print(f) // [[19, 22], [43, 50]] +const g = f.subset(math.index(1, 0)) +print(g) // 43 +console.log() + +// get a sub matrix +// Matrix indexes are zero-based. +console.log('get a sub matrix') +const h = math.diag(math.range(1, 4)) +print(h) // [[1, 0, 0], [0, 2, 0], [0, 0, 3]] +print(h.subset(math.index([1, 2], [1, 2]))) // [[2, 0], [0, 3]] +const i = math.range(1, 6) +print(i) // [1, 2, 3, 4, 5] +print(i.subset(math.index(math.range(1, 4)))) // [2, 3, 4] +console.log() + +// resize a multi dimensional matrix +console.log('resizing a matrix') +const j = math.matrix() +let defaultValue = 0 +j.resize([2, 2, 2], defaultValue) +print(j) // [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] +print(j.size()) // [2, 2, 2] +j.resize([2, 2]) +print(j) // [[0, 0], [0, 0]] +print(j.size()) // [2, 2] +console.log() + +// setting a value outside the matrices range will resize the matrix. +// new elements will be initialized with zero. +console.log('set a value outside a matrices range') +const k = math.matrix() +k.subset(math.index(2), 6) +print(k) // [0, 0, 6] +console.log() + +console.log('set a value outside a matrices range, setting other new entries to null') +const m = math.matrix() +defaultValue = null +m.subset(math.index(2), 6, defaultValue) +print(m) // [null, null, 6] +console.log() + +// create ranges +console.log('create ranges') +print(math.range(1, 6)) // [1, 2, 3, 4, 5] +print(math.range(0, 18, 3)) // [0, 3, 6, 9, 12, 15] +print(math.range('2:-1:-3')) // [2, 1, 0, -1, -2] +print(math.factorial(math.range('1:6'))) // [1, 2, 6, 24, 120] +console.log() + +/** + * Helper function to output a value in the console. Value will be formatted. + * @param {*} value + */ +function print (value) { + const precision = 14 + console.log(math.format(value, precision)) +} diff --git a/node_modules/mathjs/examples/node_modules/.bin/acorn b/node_modules/mathjs/examples/node_modules/.bin/acorn new file mode 100644 index 0000000..46a3e61 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/acorn @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../acorn/bin/acorn" "$@" +else + exec node "$basedir/../acorn/bin/acorn" "$@" +fi diff --git a/node_modules/mathjs/examples/node_modules/.bin/acorn.cmd b/node_modules/mathjs/examples/node_modules/.bin/acorn.cmd new file mode 100644 index 0000000..f38017c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/acorn.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\acorn\bin\acorn" %* diff --git a/node_modules/mathjs/examples/node_modules/.bin/acorn.ps1 b/node_modules/mathjs/examples/node_modules/.bin/acorn.ps1 new file mode 100644 index 0000000..6f6dcdd --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/acorn.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args + } else { + & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../acorn/bin/acorn" $args + } else { + & "node$exe" "$basedir/../acorn/bin/acorn" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/mathjs/examples/node_modules/.bin/browserslist b/node_modules/mathjs/examples/node_modules/.bin/browserslist new file mode 100644 index 0000000..68dd69d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/browserslist @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../browserslist/cli.js" "$@" +else + exec node "$basedir/../browserslist/cli.js" "$@" +fi diff --git a/node_modules/mathjs/examples/node_modules/.bin/browserslist.cmd b/node_modules/mathjs/examples/node_modules/.bin/browserslist.cmd new file mode 100644 index 0000000..e2a0d3f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/browserslist.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\browserslist\cli.js" %* diff --git a/node_modules/mathjs/examples/node_modules/.bin/browserslist.ps1 b/node_modules/mathjs/examples/node_modules/.bin/browserslist.ps1 new file mode 100644 index 0000000..01e10a0 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/browserslist.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../browserslist/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../browserslist/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../browserslist/cli.js" $args + } else { + & "node$exe" "$basedir/../browserslist/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/mathjs/examples/node_modules/.bin/envinfo b/node_modules/mathjs/examples/node_modules/.bin/envinfo new file mode 100644 index 0000000..239315f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/envinfo @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../envinfo/dist/cli.js" "$@" +else + exec node "$basedir/../envinfo/dist/cli.js" "$@" +fi diff --git a/node_modules/mathjs/examples/node_modules/.bin/envinfo.cmd b/node_modules/mathjs/examples/node_modules/.bin/envinfo.cmd new file mode 100644 index 0000000..6b7a5b5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/envinfo.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\envinfo\dist\cli.js" %* diff --git a/node_modules/mathjs/examples/node_modules/.bin/envinfo.ps1 b/node_modules/mathjs/examples/node_modules/.bin/envinfo.ps1 new file mode 100644 index 0000000..f9e36e5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/envinfo.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../envinfo/dist/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../envinfo/dist/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../envinfo/dist/cli.js" $args + } else { + & "node$exe" "$basedir/../envinfo/dist/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/mathjs/examples/node_modules/.bin/import-local-fixture b/node_modules/mathjs/examples/node_modules/.bin/import-local-fixture new file mode 100644 index 0000000..79e3180 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/import-local-fixture @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../import-local/fixtures/cli.js" "$@" +else + exec node "$basedir/../import-local/fixtures/cli.js" "$@" +fi diff --git a/node_modules/mathjs/examples/node_modules/.bin/import-local-fixture.cmd b/node_modules/mathjs/examples/node_modules/.bin/import-local-fixture.cmd new file mode 100644 index 0000000..53ee97f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/import-local-fixture.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\import-local\fixtures\cli.js" %* diff --git a/node_modules/mathjs/examples/node_modules/.bin/import-local-fixture.ps1 b/node_modules/mathjs/examples/node_modules/.bin/import-local-fixture.ps1 new file mode 100644 index 0000000..01ef784 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/import-local-fixture.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../import-local/fixtures/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../import-local/fixtures/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../import-local/fixtures/cli.js" $args + } else { + & "node$exe" "$basedir/../import-local/fixtures/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/mathjs/examples/node_modules/.bin/node-which b/node_modules/mathjs/examples/node_modules/.bin/node-which new file mode 100644 index 0000000..aece735 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/node-which @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../which/bin/node-which" "$@" +else + exec node "$basedir/../which/bin/node-which" "$@" +fi diff --git a/node_modules/mathjs/examples/node_modules/.bin/node-which.cmd b/node_modules/mathjs/examples/node_modules/.bin/node-which.cmd new file mode 100644 index 0000000..7eeb316 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/node-which.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %* diff --git a/node_modules/mathjs/examples/node_modules/.bin/node-which.ps1 b/node_modules/mathjs/examples/node_modules/.bin/node-which.ps1 new file mode 100644 index 0000000..cfb09e8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/node-which.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args + } else { + & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../which/bin/node-which" $args + } else { + & "node$exe" "$basedir/../which/bin/node-which" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/mathjs/examples/node_modules/.bin/resolve b/node_modules/mathjs/examples/node_modules/.bin/resolve new file mode 100644 index 0000000..757d454 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/resolve @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../resolve/bin/resolve" "$@" +else + exec node "$basedir/../resolve/bin/resolve" "$@" +fi diff --git a/node_modules/mathjs/examples/node_modules/.bin/resolve.cmd b/node_modules/mathjs/examples/node_modules/.bin/resolve.cmd new file mode 100644 index 0000000..6358238 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/resolve.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\resolve\bin\resolve" %* diff --git a/node_modules/mathjs/examples/node_modules/.bin/resolve.ps1 b/node_modules/mathjs/examples/node_modules/.bin/resolve.ps1 new file mode 100644 index 0000000..f22b2d3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/resolve.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../resolve/bin/resolve" $args + } else { + & "$basedir/node$exe" "$basedir/../resolve/bin/resolve" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../resolve/bin/resolve" $args + } else { + & "node$exe" "$basedir/../resolve/bin/resolve" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/mathjs/examples/node_modules/.bin/terser b/node_modules/mathjs/examples/node_modules/.bin/terser new file mode 100644 index 0000000..2d3fa89 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/terser @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../terser/bin/terser" "$@" +else + exec node "$basedir/../terser/bin/terser" "$@" +fi diff --git a/node_modules/mathjs/examples/node_modules/.bin/terser.cmd b/node_modules/mathjs/examples/node_modules/.bin/terser.cmd new file mode 100644 index 0000000..5186ade --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/terser.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\terser\bin\terser" %* diff --git a/node_modules/mathjs/examples/node_modules/.bin/terser.ps1 b/node_modules/mathjs/examples/node_modules/.bin/terser.ps1 new file mode 100644 index 0000000..0bbfff6 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/terser.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../terser/bin/terser" $args + } else { + & "$basedir/node$exe" "$basedir/../terser/bin/terser" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../terser/bin/terser" $args + } else { + & "node$exe" "$basedir/../terser/bin/terser" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/mathjs/examples/node_modules/.bin/webpack b/node_modules/mathjs/examples/node_modules/.bin/webpack new file mode 100644 index 0000000..e674801 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/webpack @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../webpack/bin/webpack.js" "$@" +else + exec node "$basedir/../webpack/bin/webpack.js" "$@" +fi diff --git a/node_modules/mathjs/examples/node_modules/.bin/webpack-cli b/node_modules/mathjs/examples/node_modules/.bin/webpack-cli new file mode 100644 index 0000000..d04406f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/webpack-cli @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../webpack-cli/bin/cli.js" "$@" +else + exec node "$basedir/../webpack-cli/bin/cli.js" "$@" +fi diff --git a/node_modules/mathjs/examples/node_modules/.bin/webpack-cli.cmd b/node_modules/mathjs/examples/node_modules/.bin/webpack-cli.cmd new file mode 100644 index 0000000..c469b5d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/webpack-cli.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\webpack-cli\bin\cli.js" %* diff --git a/node_modules/mathjs/examples/node_modules/.bin/webpack-cli.ps1 b/node_modules/mathjs/examples/node_modules/.bin/webpack-cli.ps1 new file mode 100644 index 0000000..9400edb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/webpack-cli.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../webpack-cli/bin/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../webpack-cli/bin/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../webpack-cli/bin/cli.js" $args + } else { + & "node$exe" "$basedir/../webpack-cli/bin/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/mathjs/examples/node_modules/.bin/webpack.cmd b/node_modules/mathjs/examples/node_modules/.bin/webpack.cmd new file mode 100644 index 0000000..6fbf5ec --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/webpack.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\webpack\bin\webpack.js" %* diff --git a/node_modules/mathjs/examples/node_modules/.bin/webpack.ps1 b/node_modules/mathjs/examples/node_modules/.bin/webpack.ps1 new file mode 100644 index 0000000..57bb525 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.bin/webpack.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../webpack/bin/webpack.js" $args + } else { + & "$basedir/node$exe" "$basedir/../webpack/bin/webpack.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../webpack/bin/webpack.js" $args + } else { + & "node$exe" "$basedir/../webpack/bin/webpack.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/mathjs/examples/node_modules/.package-lock.json b/node_modules/mathjs/examples/node_modules/.package-lock.json new file mode 100644 index 0000000..a430373 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/.package-lock.json @@ -0,0 +1,1407 @@ +{ + "name": "examples", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@discoveryjs/json-ext": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz", + "integrity": "sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==", + "dev": true, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/@types/eslint": { + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.4.1.tgz", + "integrity": "sha512-GE44+DNEyxxh2Kc6ro/VkIj+9ma0pO0bwv9+uHSyBrikYOHr8zYcdPvnBOp1aw8s+CjRvuSx7CyWqRrNFQ59mA==", + "dev": true, + "peer": true, + "dependencies": { + "@types/estree": "*", + "@types/json-schema": "*" + } + }, + "node_modules/@types/eslint-scope": { + "version": "3.7.3", + "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.3.tgz", + "integrity": "sha512-PB3ldyrcnAicT35TWPs5IcwKD8S333HMaa2VVv4+wdvebJkjWuW/xESoB8IwRcog8HYVYamb1g/R31Qv5Bx03g==", + "dev": true, + "peer": true, + "dependencies": { + "@types/eslint": "*", + "@types/estree": "*" + } + }, + "node_modules/@types/estree": { + "version": "0.0.51", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.51.tgz", + "integrity": "sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ==", + "dev": true, + "peer": true + }, + "node_modules/@types/json-schema": { + "version": "7.0.11", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.11.tgz", + "integrity": "sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==", + "dev": true, + "peer": true + }, + "node_modules/@types/node": { + "version": "17.0.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.23.tgz", + "integrity": "sha512-UxDxWn7dl97rKVeVS61vErvw086aCYhDLyvRQZ5Rk65rZKepaFdm53GeqXaKBuOhED4e9uWq34IC3TdSdJJ2Gw==", + "dev": true, + "peer": true + }, + "node_modules/@webassemblyjs/ast": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.1.tgz", + "integrity": "sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/helper-numbers": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1" + } + }, + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.1.tgz", + "integrity": "sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ==", + "dev": true, + "peer": true + }, + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.1.tgz", + "integrity": "sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg==", + "dev": true, + "peer": true + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.1.tgz", + "integrity": "sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA==", + "dev": true, + "peer": true + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.1.tgz", + "integrity": "sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.11.1", + "@webassemblyjs/helper-api-error": "1.11.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.1.tgz", + "integrity": "sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q==", + "dev": true, + "peer": true + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.1.tgz", + "integrity": "sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1" + } + }, + "node_modules/@webassemblyjs/ieee754": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.1.tgz", + "integrity": "sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ==", + "dev": true, + "peer": true, + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/@webassemblyjs/leb128": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.1.tgz", + "integrity": "sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw==", + "dev": true, + "peer": true, + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/utf8": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.1.tgz", + "integrity": "sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ==", + "dev": true, + "peer": true + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.1.tgz", + "integrity": "sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/helper-wasm-section": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1", + "@webassemblyjs/wasm-opt": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1", + "@webassemblyjs/wast-printer": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.1.tgz", + "integrity": "sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/ieee754": "1.11.1", + "@webassemblyjs/leb128": "1.11.1", + "@webassemblyjs/utf8": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.1.tgz", + "integrity": "sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.1.tgz", + "integrity": "sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-api-error": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/ieee754": "1.11.1", + "@webassemblyjs/leb128": "1.11.1", + "@webassemblyjs/utf8": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.11.1.tgz", + "integrity": "sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webpack-cli/configtest": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-1.1.1.tgz", + "integrity": "sha512-1FBc1f9G4P/AxMqIgfZgeOTuRnwZMten8E7zap5zgpPInnCrP8D4Q81+4CWIch8i/Nf7nXjP0v6CjjbHOrXhKg==", + "dev": true, + "peerDependencies": { + "webpack": "4.x.x || 5.x.x", + "webpack-cli": "4.x.x" + } + }, + "node_modules/@webpack-cli/info": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-1.4.1.tgz", + "integrity": "sha512-PKVGmazEq3oAo46Q63tpMr4HipI3OPfP7LiNOEJg963RMgT0rqheag28NCML0o3GIzA3DmxP1ZIAv9oTX1CUIA==", + "dev": true, + "dependencies": { + "envinfo": "^7.7.3" + }, + "peerDependencies": { + "webpack-cli": "4.x.x" + } + }, + "node_modules/@webpack-cli/serve": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-1.6.1.tgz", + "integrity": "sha512-gNGTiTrjEVQ0OcVnzsRSqTxaBSr+dmTfm+qJsCDluky8uhdLWep7Gcr62QsAKHTMxjCS/8nEITsmFAhfIx+QSw==", + "dev": true, + "peerDependencies": { + "webpack-cli": "4.x.x" + }, + "peerDependenciesMeta": { + "webpack-dev-server": { + "optional": true + } + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true, + "peer": true + }, + "node_modules/@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true, + "peer": true + }, + "node_modules/acorn": { + "version": "8.7.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.0.tgz", + "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==", + "dev": true, + "peer": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-import-assertions": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.8.0.tgz", + "integrity": "sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw==", + "dev": true, + "peer": true, + "peerDependencies": { + "acorn": "^8" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "peer": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "dev": true, + "peer": true, + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/browserslist": { + "version": "4.20.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.20.2.tgz", + "integrity": "sha512-CQOBCqp/9pDvDbx3xfMi+86pr4KXIf2FDkTTdeuYw8OxS9t898LA1Khq57gtufFILXpfgsSx5woNgsBgvGjpsA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + } + ], + "peer": true, + "dependencies": { + "caniuse-lite": "^1.0.30001317", + "electron-to-chromium": "^1.4.84", + "escalade": "^3.1.1", + "node-releases": "^2.0.2", + "picocolors": "^1.0.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "peer": true + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001320", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001320.tgz", + "integrity": "sha512-MWPzG54AGdo3nWx7zHZTefseM5Y1ccM7hlQKHRqJkPozUaw3hNbBTMmLn16GG2FUzjR13Cr3NPfhIieX5PzXDA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + } + ], + "peer": true + }, + "node_modules/chrome-trace-event": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz", + "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/clone-deep": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz", + "integrity": "sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==", + "dev": true, + "dependencies": { + "is-plain-object": "^2.0.4", + "kind-of": "^6.0.2", + "shallow-clone": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/colorette": { + "version": "2.0.16", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.16.tgz", + "integrity": "sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==", + "dev": true + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true, + "peer": true + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.4.96", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.96.tgz", + "integrity": "sha512-DPNjvNGPabv6FcyjzLAN4C0psN/GgD9rSGvMTuv81SeXG/EX3mCz0wiw9N1tUEnfQXYCJi3H8M0oFPRziZh7rw==", + "dev": true, + "peer": true + }, + "node_modules/enhanced-resolve": { + "version": "5.9.2", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.9.2.tgz", + "integrity": "sha512-GIm3fQfwLJ8YZx2smuHpBKkXC1yOk+OBEmKckVyL0i/ea8mqDEykK3ld5dgH1QYPNyT/lIllxV2LULnxCHaHkA==", + "dev": true, + "peer": true, + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/envinfo": { + "version": "7.8.1", + "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.8.1.tgz", + "integrity": "sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw==", + "dev": true, + "bin": { + "envinfo": "dist/cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/es-module-lexer": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-0.9.3.tgz", + "integrity": "sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ==", + "dev": true, + "peer": true + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "peer": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "peer": true, + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "peer": true + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "peer": true + }, + "node_modules/fastest-levenshtein": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.12.tgz", + "integrity": "sha512-On2N+BpYJ15xIC974QNVuYGMOlEVt4s0EOI3wwMqOmK1fdDY+FN/zltPV8vosq4ad4c/gJ1KHScUn/6AWIgiow==", + "dev": true + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true, + "peer": true + }, + "node_modules/graceful-fs": { + "version": "4.2.9", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", + "integrity": "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==", + "dev": true, + "peer": true + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true, + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/import-local": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", + "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", + "dev": true, + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/interpret": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-2.2.0.tgz", + "integrity": "sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw==", + "dev": true, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-core-module": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.1.tgz", + "integrity": "sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "node_modules/isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/jest-worker": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "dev": true, + "peer": true, + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true, + "peer": true + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "peer": true + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/loader-runner": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.2.0.tgz", + "integrity": "sha512-92+huvxMvYlMzMt0iIOukcwYBFpkYJdpl2xsZ7LrlayO7E8SOv+JJUEK17B/dJIHAOLMfh2dZZ/Y18WgmGtYNw==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.11.5" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "peer": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "dev": true, + "peer": true + }, + "node_modules/node-releases": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.2.tgz", + "integrity": "sha512-XxYDdcQ6eKqp/YjI+tb2C5WM2LgjnZrfYg4vgQt49EK268b6gYCHsBLrK2qvJo4FmCtqmKezb0WZFK4fkrZNsg==", + "dev": true, + "peer": true + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true, + "peer": true + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "peer": true, + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/rechoir": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.7.1.tgz", + "integrity": "sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg==", + "dev": true, + "dependencies": { + "resolve": "^1.9.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/resolve": { + "version": "1.22.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.0.tgz", + "integrity": "sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==", + "dev": true, + "dependencies": { + "is-core-module": "^2.8.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "peer": true + }, + "node_modules/schema-utils": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.1.1.tgz", + "integrity": "sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw==", + "dev": true, + "peer": true, + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/serialize-javascript": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz", + "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==", + "dev": true, + "peer": true, + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/shallow-clone": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", + "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", + "dev": true, + "dependencies": { + "kind-of": "^6.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "peer": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "peer": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tapable": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", + "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/terser": { + "version": "5.12.1", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.12.1.tgz", + "integrity": "sha512-NXbs+7nisos5E+yXwAD+y7zrcTkMqb0dEJxIGtSKPdCBzopf7ni4odPul2aechpV7EXNvOudYOX2bb5tln1jbQ==", + "dev": true, + "peer": true, + "dependencies": { + "acorn": "^8.5.0", + "commander": "^2.20.0", + "source-map": "~0.7.2", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser-webpack-plugin": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.1.tgz", + "integrity": "sha512-GvlZdT6wPQKbDNW/GDQzZFg/j4vKU96yl2q6mcUkzKOgW4gwf1Z8cZToUCrz31XHlPWH8MVb1r2tFtdDtTGJ7g==", + "dev": true, + "peer": true, + "dependencies": { + "jest-worker": "^27.4.5", + "schema-utils": "^3.1.1", + "serialize-javascript": "^6.0.0", + "source-map": "^0.6.1", + "terser": "^5.7.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "uglify-js": { + "optional": true + } + } + }, + "node_modules/terser/node_modules/source-map": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", + "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "peer": true, + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/watchpack": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.3.1.tgz", + "integrity": "sha512-x0t0JuydIo8qCNctdDrn1OzH/qDzk2+rdCOC3YzumZ42fiMqmQ7T3xQurykYMhYfHaPHTp4ZxAx2NfUo1K6QaA==", + "dev": true, + "peer": true, + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack": { + "version": "5.70.0", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.70.0.tgz", + "integrity": "sha512-ZMWWy8CeuTTjCxbeaQI21xSswseF2oNOwc70QSKNePvmxE7XW36i7vpBMYZFAUHPwQiEbNGCEYIOOlyRbdGmxw==", + "dev": true, + "peer": true, + "dependencies": { + "@types/eslint-scope": "^3.7.3", + "@types/estree": "^0.0.51", + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/wasm-edit": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1", + "acorn": "^8.4.1", + "acorn-import-assertions": "^1.7.6", + "browserslist": "^4.14.5", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.9.2", + "es-module-lexer": "^0.9.0", + "eslint-scope": "5.1.1", + "events": "^3.2.0", + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.2.9", + "json-parse-better-errors": "^1.0.2", + "loader-runner": "^4.2.0", + "mime-types": "^2.1.27", + "neo-async": "^2.6.2", + "schema-utils": "^3.1.0", + "tapable": "^2.1.1", + "terser-webpack-plugin": "^5.1.3", + "watchpack": "^2.3.1", + "webpack-sources": "^3.2.3" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-cli": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-4.9.2.tgz", + "integrity": "sha512-m3/AACnBBzK/kMTcxWHcZFPrw/eQuY4Df1TxvIWfWM2x7mRqBQCqKEd96oCUa9jkapLBaFfRce33eGDb4Pr7YQ==", + "dev": true, + "dependencies": { + "@discoveryjs/json-ext": "^0.5.0", + "@webpack-cli/configtest": "^1.1.1", + "@webpack-cli/info": "^1.4.1", + "@webpack-cli/serve": "^1.6.1", + "colorette": "^2.0.14", + "commander": "^7.0.0", + "execa": "^5.0.0", + "fastest-levenshtein": "^1.0.12", + "import-local": "^3.0.2", + "interpret": "^2.2.0", + "rechoir": "^0.7.0", + "webpack-merge": "^5.7.3" + }, + "bin": { + "webpack-cli": "bin/cli.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "peerDependencies": { + "webpack": "4.x.x || 5.x.x" + }, + "peerDependenciesMeta": { + "@webpack-cli/generators": { + "optional": true + }, + "@webpack-cli/migrate": { + "optional": true + }, + "webpack-bundle-analyzer": { + "optional": true + }, + "webpack-dev-server": { + "optional": true + } + } + }, + "node_modules/webpack-cli/node_modules/commander": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", + "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", + "dev": true, + "engines": { + "node": ">= 10" + } + }, + "node_modules/webpack-merge": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-5.8.0.tgz", + "integrity": "sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q==", + "dev": true, + "dependencies": { + "clone-deep": "^4.0.1", + "wildcard": "^2.0.0" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/webpack-sources": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.3.tgz", + "integrity": "sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wildcard": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.0.tgz", + "integrity": "sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw==", + "dev": true + } + } +} diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/LICENSE b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/LICENSE new file mode 100644 index 0000000..44f551a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Roman Dvornov + +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. diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/README.md b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/README.md new file mode 100644 index 0000000..f155a9d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/README.md @@ -0,0 +1,256 @@ +# json-ext + +[![NPM version](https://img.shields.io/npm/v/@discoveryjs/json-ext.svg)](https://www.npmjs.com/package/@discoveryjs/json-ext) +[![Build Status](https://github.com/discoveryjs/json-ext/actions/workflows/ci.yml/badge.svg)](https://github.com/discoveryjs/json-ext/actions/workflows/ci.yml) +[![Coverage Status](https://coveralls.io/repos/github/discoveryjs/json-ext/badge.svg?branch=master)](https://coveralls.io/github/discoveryjs/json-ext?) +[![NPM Downloads](https://img.shields.io/npm/dm/@discoveryjs/json-ext.svg)](https://www.npmjs.com/package/@discoveryjs/json-ext) + +A set of utilities that extend the use of JSON. Designed to be fast and memory efficient + +Features: + +- [x] `parseChunked()` – Parse JSON that comes by chunks (e.g. FS readable stream or fetch response stream) +- [x] `stringifyStream()` – Stringify stream (Node.js) +- [x] `stringifyInfo()` – Get estimated size and other facts of JSON.stringify() without converting a value to string +- [ ] **TBD** Support for circular references +- [ ] **TBD** Binary representation [branch](https://github.com/discoveryjs/json-ext/tree/binary) +- [ ] **TBD** WHATWG [Streams](https://streams.spec.whatwg.org/) support + +## Install + +```bash +npm install @discoveryjs/json-ext +``` + +## API + +- [parseChunked(chunkEmitter)](#parsechunkedchunkemitter) +- [stringifyStream(value[, replacer[, space]])](#stringifystreamvalue-replacer-space) +- [stringifyInfo(value[, replacer[, space[, options]]])](#stringifyinfovalue-replacer-space-options) + - [Options](#options) + - [async](#async) + - [continueOnCircular](#continueoncircular) +- [version](#version) + +### parseChunked(chunkEmitter) + +Works the same as [`JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) but takes `chunkEmitter` instead of string and returns [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + +> NOTE: `reviver` parameter is not supported yet, but will be added in next releases. +> NOTE: WHATWG streams aren't supported yet + +When to use: +- It's required to avoid freezing the main thread during big JSON parsing, since this process can be distributed in time +- Huge JSON needs to be parsed (e.g. >500MB on Node.js) +- Needed to reduce memory pressure. `JSON.parse()` needs to receive the entire JSON before parsing it. With `parseChunked()` you may parse JSON as first bytes of it comes. This approach helps to avoid storing a huge string in the memory at a single time point and following GC. + +[Benchmark](https://github.com/discoveryjs/json-ext/tree/master/benchmarks#parse-chunked) + +Usage: + +```js +const { parseChunked } = require('@discoveryjs/json-ext'); + +// as a regular Promise +parseChunked(chunkEmitter) + .then(data => { + /* data is parsed JSON */ + }); + +// using await (keep in mind that not every runtime has a support for top level await) +const data = await parseChunked(chunkEmitter); +``` + +Parameter `chunkEmitter` can be: +- [`ReadableStream`](https://nodejs.org/dist/latest-v14.x/docs/api/stream.html#stream_readable_streams) (Node.js only) +```js +const fs = require('fs'); +const { parseChunked } = require('@discoveryjs/json-ext'); + +parseChunked(fs.createReadStream('path/to/file.json')) +``` +- Generator, async generator or function that returns iterable (chunks). Chunk might be a `string`, `Uint8Array` or `Buffer` (Node.js only): +```js +const { parseChunked } = require('@discoveryjs/json-ext'); +const encoder = new TextEncoder(); + +// generator +parseChunked(function*() { + yield '{ "hello":'; + yield Buffer.from(' "wor'); // Node.js only + yield encoder.encode('ld" }'); // returns Uint8Array(5) [ 108, 100, 34, 32, 125 ] +}); + +// async generator +parseChunked(async function*() { + for await (const chunk of someAsyncSource) { + yield chunk; + } +}); + +// function that returns iterable +parseChunked(() => ['{ "hello":', ' "world"}']) +``` + +Using with [fetch()](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API): + +```js +async function loadData(url) { + const response = await fetch(url); + const reader = response.body.getReader(); + + return parseChunked(async function*() { + while (true) { + const { done, value } = await reader.read(); + + if (done) { + break; + } + + yield value; + } + }); +} + +loadData('https://example.com/data.json') + .then(data => { + /* data is parsed JSON */ + }) +``` + +### stringifyStream(value[, replacer[, space]]) + +Works the same as [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify), but returns an instance of [`ReadableStream`](https://nodejs.org/dist/latest-v14.x/docs/api/stream.html#stream_readable_streams) instead of string. + +> NOTE: WHATWG Streams aren't supported yet, so function available for Node.js only for now + +Departs from JSON.stringify(): +- Outputs `null` when `JSON.stringify()` returns `undefined` (since streams may not emit `undefined`) +- A promise is resolving and the resulting value is stringifying as a regular one +- A stream in non-object mode is piping to output as is +- A stream in object mode is piping to output as an array of objects + +When to use: +- Huge JSON needs to be generated (e.g. >500MB on Node.js) +- Needed to reduce memory pressure. `JSON.stringify()` needs to generate the entire JSON before send or write it to somewhere. With `stringifyStream()` you may send a result to somewhere as first bytes of the result appears. This approach helps to avoid storing a huge string in the memory at a single time point. +- The object being serialized contains Promises or Streams (see Usage for examples) + +[Benchmark](https://github.com/discoveryjs/json-ext/tree/master/benchmarks#stream-stringifying) + +Usage: + +```js +const { stringifyStream } = require('@discoveryjs/json-ext'); + +// handle events +stringifyStream(data) + .on('data', chunk => console.log(chunk)) + .on('error', error => consold.error(error)) + .on('finish', () => console.log('DONE!')); + +// pipe into a stream +stringifyStream(data) + .pipe(writableStream); +``` + +Using Promise or ReadableStream in serializing object: + +```js +const fs = require('fs'); +const { stringifyStream } = require('@discoveryjs/json-ext'); + +// output will be +// {"name":"example","willSerializeResolvedValue":42,"fromFile":[1, 2, 3],"at":{"any":{"level":"promise!"}}} +stringifyStream({ + name: 'example', + willSerializeResolvedValue: Promise.resolve(42), + fromFile: fs.createReadStream('path/to/file.json'), // support file content is "[1, 2, 3]", it'll be inserted as it + at: { + any: { + level: new Promise(resolve => setTimeout(() => resolve('promise!'), 100)) + } + } +}) + +// in case several async requests are used in object, it's prefered +// to put fastest requests first, because in this case +stringifyStream({ + foo: fetch('http://example.com/request_takes_2s').then(req => req.json()), + bar: fetch('http://example.com/request_takes_5s').then(req => req.json()) +}); +``` + +Using with [`WritableStream`](https://nodejs.org/dist/latest-v14.x/docs/api/stream.html#stream_writable_streams) (Node.js only): + +```js +const fs = require('fs'); +const { stringifyStream } = require('@discoveryjs/json-ext'); + +// pipe into a console +stringifyStream(data) + .pipe(process.stdout); + +// pipe into a file +stringifyStream(data) + .pipe(fs.createWriteStream('path/to/file.json')); + +// wrapping into a Promise +new Promise((resolve, reject) => { + stringifyStream(data) + .on('error', reject) + .pipe(stream) + .on('error', reject) + .on('finish', resolve); +}); +``` + +### stringifyInfo(value[, replacer[, space[, options]]]) + +`value`, `replacer` and `space` arguments are the same as for `JSON.stringify()`. + +Result is an object: + +```js +{ + minLength: Number, // minimal bytes when values is stringified + circular: [...], // list of circular references + duplicate: [...], // list of objects that occur more than once + async: [...] // list of async values, i.e. promises and streams +} +``` + +Example: + +```js +const { stringifyInfo } = require('@discoveryjs/json-ext'); + +console.log( + stringifyInfo({ test: true }).minLength +); +// > 13 +// that equals '{"test":true}'.length +``` + +#### Options + +##### async + +Type: `Boolean` +Default: `false` + +Collect async values (promises and streams) or not. + +##### continueOnCircular + +Type: `Boolean` +Default: `false` + +Stop collecting info for a value or not whenever circular reference is found. Setting option to `true` allows to find all circular references. + +### version + +The version of library, e.g. `"0.3.1"`. + +## License + +MIT diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/dist/json-ext.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/dist/json-ext.js new file mode 100644 index 0000000..298fbd4 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/dist/json-ext.js @@ -0,0 +1,791 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.jsonExt = factory()); +})(this, (function () { 'use strict'; + + var version = "0.5.7"; + + const PrimitiveType = 1; + const ObjectType = 2; + const ArrayType = 3; + const PromiseType = 4; + const ReadableStringType = 5; + const ReadableObjectType = 6; + // https://tc39.es/ecma262/#table-json-single-character-escapes + const escapableCharCodeSubstitution$1 = { // JSON Single Character Escape Sequences + 0x08: '\\b', + 0x09: '\\t', + 0x0a: '\\n', + 0x0c: '\\f', + 0x0d: '\\r', + 0x22: '\\\"', + 0x5c: '\\\\' + }; + + function isLeadingSurrogate$1(code) { + return code >= 0xD800 && code <= 0xDBFF; + } + + function isTrailingSurrogate$1(code) { + return code >= 0xDC00 && code <= 0xDFFF; + } + + function isReadableStream$1(value) { + return ( + typeof value.pipe === 'function' && + typeof value._read === 'function' && + typeof value._readableState === 'object' && value._readableState !== null + ); + } + + function replaceValue$1(holder, key, value, replacer) { + if (value && typeof value.toJSON === 'function') { + value = value.toJSON(); + } + + if (replacer !== null) { + value = replacer.call(holder, String(key), value); + } + + switch (typeof value) { + case 'function': + case 'symbol': + value = undefined; + break; + + case 'object': + if (value !== null) { + const cls = value.constructor; + if (cls === String || cls === Number || cls === Boolean) { + value = value.valueOf(); + } + } + break; + } + + return value; + } + + function getTypeNative$1(value) { + if (value === null || typeof value !== 'object') { + return PrimitiveType; + } + + if (Array.isArray(value)) { + return ArrayType; + } + + return ObjectType; + } + + function getTypeAsync$1(value) { + if (value === null || typeof value !== 'object') { + return PrimitiveType; + } + + if (typeof value.then === 'function') { + return PromiseType; + } + + if (isReadableStream$1(value)) { + return value._readableState.objectMode ? ReadableObjectType : ReadableStringType; + } + + if (Array.isArray(value)) { + return ArrayType; + } + + return ObjectType; + } + + function normalizeReplacer$1(replacer) { + if (typeof replacer === 'function') { + return replacer; + } + + if (Array.isArray(replacer)) { + const allowlist = new Set(replacer + .map(item => { + const cls = item && item.constructor; + return cls === String || cls === Number ? String(item) : null; + }) + .filter(item => typeof item === 'string') + ); + + return [...allowlist]; + } + + return null; + } + + function normalizeSpace$1(space) { + if (typeof space === 'number') { + if (!Number.isFinite(space) || space < 1) { + return false; + } + + return ' '.repeat(Math.min(space, 10)); + } + + if (typeof space === 'string') { + return space.slice(0, 10) || false; + } + + return false; + } + + var utils = { + escapableCharCodeSubstitution: escapableCharCodeSubstitution$1, + isLeadingSurrogate: isLeadingSurrogate$1, + isTrailingSurrogate: isTrailingSurrogate$1, + type: { + PRIMITIVE: PrimitiveType, + PROMISE: PromiseType, + ARRAY: ArrayType, + OBJECT: ObjectType, + STRING_STREAM: ReadableStringType, + OBJECT_STREAM: ReadableObjectType + }, + + isReadableStream: isReadableStream$1, + replaceValue: replaceValue$1, + getTypeNative: getTypeNative$1, + getTypeAsync: getTypeAsync$1, + normalizeReplacer: normalizeReplacer$1, + normalizeSpace: normalizeSpace$1 + }; + + const { + normalizeReplacer, + normalizeSpace, + replaceValue, + getTypeNative, + getTypeAsync, + isLeadingSurrogate, + isTrailingSurrogate, + escapableCharCodeSubstitution, + type: { + PRIMITIVE, + OBJECT, + ARRAY, + PROMISE, + STRING_STREAM, + OBJECT_STREAM + } + } = utils; + const charLength2048 = Array.from({ length: 2048 }).map((_, code) => { + if (escapableCharCodeSubstitution.hasOwnProperty(code)) { + return 2; // \X + } + + if (code < 0x20) { + return 6; // \uXXXX + } + + return code < 128 ? 1 : 2; // UTF8 bytes + }); + + function stringLength(str) { + let len = 0; + let prevLeadingSurrogate = false; + + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i); + + if (code < 2048) { + len += charLength2048[code]; + } else if (isLeadingSurrogate(code)) { + len += 6; // \uXXXX since no pair with trailing surrogate yet + prevLeadingSurrogate = true; + continue; + } else if (isTrailingSurrogate(code)) { + len = prevLeadingSurrogate + ? len - 2 // surrogate pair (4 bytes), since we calculate prev leading surrogate as 6 bytes, substruct 2 bytes + : len + 6; // \uXXXX + } else { + len += 3; // code >= 2048 is 3 bytes length for UTF8 + } + + prevLeadingSurrogate = false; + } + + return len + 2; // +2 for quotes + } + + function primitiveLength(value) { + switch (typeof value) { + case 'string': + return stringLength(value); + + case 'number': + return Number.isFinite(value) ? String(value).length : 4 /* null */; + + case 'boolean': + return value ? 4 /* true */ : 5 /* false */; + + case 'undefined': + case 'object': + return 4; /* null */ + + default: + return 0; + } + } + + function spaceLength(space) { + space = normalizeSpace(space); + return typeof space === 'string' ? space.length : 0; + } + + var stringifyInfo = function jsonStringifyInfo(value, replacer, space, options) { + function walk(holder, key, value) { + if (stop) { + return; + } + + value = replaceValue(holder, key, value, replacer); + + let type = getType(value); + + // check for circular structure + if (type !== PRIMITIVE && stack.has(value)) { + circular.add(value); + length += 4; // treat as null + + if (!options.continueOnCircular) { + stop = true; + } + + return; + } + + switch (type) { + case PRIMITIVE: + if (value !== undefined || Array.isArray(holder)) { + length += primitiveLength(value); + } else if (holder === root) { + length += 9; // FIXME: that's the length of undefined, should we normalize behaviour to convert it to null? + } + break; + + case OBJECT: { + if (visited.has(value)) { + duplicate.add(value); + length += visited.get(value); + break; + } + + const valueLength = length; + let entries = 0; + + length += 2; // {} + + stack.add(value); + + for (const key in value) { + if (hasOwnProperty.call(value, key) && (allowlist === null || allowlist.has(key))) { + const prevLength = length; + walk(value, key, value[key]); + + if (prevLength !== length) { + // value is printed + length += stringLength(key) + 1; // "key": + entries++; + } + } + } + + if (entries > 1) { + length += entries - 1; // commas + } + + stack.delete(value); + + if (space > 0 && entries > 0) { + length += (1 + (stack.size + 1) * space + 1) * entries; // for each key-value: \n{space} + length += 1 + stack.size * space; // for } + } + + visited.set(value, length - valueLength); + + break; + } + + case ARRAY: { + if (visited.has(value)) { + duplicate.add(value); + length += visited.get(value); + break; + } + + const valueLength = length; + + length += 2; // [] + + stack.add(value); + + for (let i = 0; i < value.length; i++) { + walk(value, i, value[i]); + } + + if (value.length > 1) { + length += value.length - 1; // commas + } + + stack.delete(value); + + if (space > 0 && value.length > 0) { + length += (1 + (stack.size + 1) * space) * value.length; // for each element: \n{space} + length += 1 + stack.size * space; // for ] + } + + visited.set(value, length - valueLength); + + break; + } + + case PROMISE: + case STRING_STREAM: + async.add(value); + break; + + case OBJECT_STREAM: + length += 2; // [] + async.add(value); + break; + } + } + + let allowlist = null; + replacer = normalizeReplacer(replacer); + + if (Array.isArray(replacer)) { + allowlist = new Set(replacer); + replacer = null; + } + + space = spaceLength(space); + options = options || {}; + + const visited = new Map(); + const stack = new Set(); + const duplicate = new Set(); + const circular = new Set(); + const async = new Set(); + const getType = options.async ? getTypeAsync : getTypeNative; + const root = { '': value }; + let stop = false; + let length = 0; + + walk(root, '', value); + + return { + minLength: isNaN(length) ? Infinity : length, + circular: [...circular], + duplicate: [...duplicate], + async: [...async] + }; + }; + + var stringifyStreamBrowser = () => { + throw new Error('Method is not supported'); + }; + + var textDecoderBrowser = TextDecoder; + + const { isReadableStream } = utils; + + + const STACK_OBJECT = 1; + const STACK_ARRAY = 2; + const decoder = new textDecoderBrowser(); + + function isObject(value) { + return value !== null && typeof value === 'object'; + } + + function adjustPosition(error, parser) { + if (error.name === 'SyntaxError' && parser.jsonParseOffset) { + error.message = error.message.replace(/at position (\d+)/, (_, pos) => + 'at position ' + (Number(pos) + parser.jsonParseOffset) + ); + } + + return error; + } + + function append(array, elements) { + // Note: Avoid to use array.push(...elements) since it may lead to + // "RangeError: Maximum call stack size exceeded" for a long arrays + const initialLength = array.length; + array.length += elements.length; + + for (let i = 0; i < elements.length; i++) { + array[initialLength + i] = elements[i]; + } + } + + var parseChunked = function(chunkEmitter) { + let parser = new ChunkParser(); + + if (isObject(chunkEmitter) && isReadableStream(chunkEmitter)) { + return new Promise((resolve, reject) => { + chunkEmitter + .on('data', chunk => { + try { + parser.push(chunk); + } catch (e) { + reject(adjustPosition(e, parser)); + parser = null; + } + }) + .on('error', (e) => { + parser = null; + reject(e); + }) + .on('end', () => { + try { + resolve(parser.finish()); + } catch (e) { + reject(adjustPosition(e, parser)); + } finally { + parser = null; + } + }); + }); + } + + if (typeof chunkEmitter === 'function') { + const iterator = chunkEmitter(); + + if (isObject(iterator) && (Symbol.iterator in iterator || Symbol.asyncIterator in iterator)) { + return new Promise(async (resolve, reject) => { + try { + for await (const chunk of iterator) { + parser.push(chunk); + } + + resolve(parser.finish()); + } catch (e) { + reject(adjustPosition(e, parser)); + } finally { + parser = null; + } + }); + } + } + + throw new Error( + 'Chunk emitter should be readable stream, generator, ' + + 'async generator or function returning an iterable object' + ); + }; + + class ChunkParser { + constructor() { + this.value = undefined; + this.valueStack = null; + + this.stack = new Array(100); + this.lastFlushDepth = 0; + this.flushDepth = 0; + this.stateString = false; + this.stateStringEscape = false; + this.pendingByteSeq = null; + this.pendingChunk = null; + this.chunkOffset = 0; + this.jsonParseOffset = 0; + } + + parseAndAppend(fragment, wrap) { + // Append new entries or elements + if (this.stack[this.lastFlushDepth - 1] === STACK_OBJECT) { + if (wrap) { + this.jsonParseOffset--; + fragment = '{' + fragment + '}'; + } + + Object.assign(this.valueStack.value, JSON.parse(fragment)); + } else { + if (wrap) { + this.jsonParseOffset--; + fragment = '[' + fragment + ']'; + } + + append(this.valueStack.value, JSON.parse(fragment)); + } + } + + prepareAddition(fragment) { + const { value } = this.valueStack; + const expectComma = Array.isArray(value) + ? value.length !== 0 + : Object.keys(value).length !== 0; + + if (expectComma) { + // Skip a comma at the beginning of fragment, otherwise it would + // fail to parse + if (fragment[0] === ',') { + this.jsonParseOffset++; + return fragment.slice(1); + } + + // When value (an object or array) is not empty and a fragment + // doesn't start with a comma, a single valid fragment starting + // is a closing bracket. If it's not, a prefix is adding to fail + // parsing. Otherwise, the sequence of chunks can be successfully + // parsed, although it should not, e.g. ["[{}", "{}]"] + if (fragment[0] !== '}' && fragment[0] !== ']') { + this.jsonParseOffset -= 3; + return '[[]' + fragment; + } + } + + return fragment; + } + + flush(chunk, start, end) { + let fragment = chunk.slice(start, end); + + // Save position correction an error in JSON.parse() if any + this.jsonParseOffset = this.chunkOffset + start; + + // Prepend pending chunk if any + if (this.pendingChunk !== null) { + fragment = this.pendingChunk + fragment; + this.jsonParseOffset -= this.pendingChunk.length; + this.pendingChunk = null; + } + + if (this.flushDepth === this.lastFlushDepth) { + // Depth didn't changed, so it's a root value or entry/element set + if (this.flushDepth > 0) { + this.parseAndAppend(this.prepareAddition(fragment), true); + } else { + // That's an entire value on a top level + this.value = JSON.parse(fragment); + this.valueStack = { + value: this.value, + prev: null + }; + } + } else if (this.flushDepth > this.lastFlushDepth) { + // Add missed closing brackets/parentheses + for (let i = this.flushDepth - 1; i >= this.lastFlushDepth; i--) { + fragment += this.stack[i] === STACK_OBJECT ? '}' : ']'; + } + + if (this.lastFlushDepth === 0) { + // That's a root value + this.value = JSON.parse(fragment); + this.valueStack = { + value: this.value, + prev: null + }; + } else { + this.parseAndAppend(this.prepareAddition(fragment), true); + } + + // Move down to the depths to the last object/array, which is current now + for (let i = this.lastFlushDepth || 1; i < this.flushDepth; i++) { + let value = this.valueStack.value; + + if (this.stack[i - 1] === STACK_OBJECT) { + // find last entry + let key; + // eslint-disable-next-line curly + for (key in value); + value = value[key]; + } else { + // last element + value = value[value.length - 1]; + } + + this.valueStack = { + value, + prev: this.valueStack + }; + } + } else /* this.flushDepth < this.lastFlushDepth */ { + fragment = this.prepareAddition(fragment); + + // Add missed opening brackets/parentheses + for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) { + this.jsonParseOffset--; + fragment = (this.stack[i] === STACK_OBJECT ? '{' : '[') + fragment; + } + + this.parseAndAppend(fragment, false); + + for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) { + this.valueStack = this.valueStack.prev; + } + } + + this.lastFlushDepth = this.flushDepth; + } + + push(chunk) { + if (typeof chunk !== 'string') { + // Suppose chunk is Buffer or Uint8Array + + // Prepend uncompleted byte sequence if any + if (this.pendingByteSeq !== null) { + const origRawChunk = chunk; + chunk = new Uint8Array(this.pendingByteSeq.length + origRawChunk.length); + chunk.set(this.pendingByteSeq); + chunk.set(origRawChunk, this.pendingByteSeq.length); + this.pendingByteSeq = null; + } + + // In case Buffer/Uint8Array, an input is encoded in UTF8 + // Seek for parts of uncompleted UTF8 symbol on the ending + // This makes sense only if we expect more chunks and last char is not multi-bytes + if (chunk[chunk.length - 1] > 127) { + for (let seqLength = 0; seqLength < chunk.length; seqLength++) { + const byte = chunk[chunk.length - 1 - seqLength]; + + // 10xxxxxx - 2nd, 3rd or 4th byte + // 110xxxxx – first byte of 2-byte sequence + // 1110xxxx - first byte of 3-byte sequence + // 11110xxx - first byte of 4-byte sequence + if (byte >> 6 === 3) { + seqLength++; + + // If the sequence is really incomplete, then preserve it + // for the future chunk and cut off it from the current chunk + if ((seqLength !== 4 && byte >> 3 === 0b11110) || + (seqLength !== 3 && byte >> 4 === 0b1110) || + (seqLength !== 2 && byte >> 5 === 0b110)) { + this.pendingByteSeq = chunk.slice(chunk.length - seqLength); + chunk = chunk.slice(0, -seqLength); + } + + break; + } + } + } + + // Convert chunk to a string, since single decode per chunk + // is much effective than decode multiple small substrings + chunk = decoder.decode(chunk); + } + + const chunkLength = chunk.length; + let lastFlushPoint = 0; + let flushPoint = 0; + + // Main scan loop + scan: for (let i = 0; i < chunkLength; i++) { + if (this.stateString) { + for (; i < chunkLength; i++) { + if (this.stateStringEscape) { + this.stateStringEscape = false; + } else { + switch (chunk.charCodeAt(i)) { + case 0x22: /* " */ + this.stateString = false; + continue scan; + + case 0x5C: /* \ */ + this.stateStringEscape = true; + } + } + } + + break; + } + + switch (chunk.charCodeAt(i)) { + case 0x22: /* " */ + this.stateString = true; + this.stateStringEscape = false; + break; + + case 0x2C: /* , */ + flushPoint = i; + break; + + case 0x7B: /* { */ + // Open an object + flushPoint = i + 1; + this.stack[this.flushDepth++] = STACK_OBJECT; + break; + + case 0x5B: /* [ */ + // Open an array + flushPoint = i + 1; + this.stack[this.flushDepth++] = STACK_ARRAY; + break; + + case 0x5D: /* ] */ + case 0x7D: /* } */ + // Close an object or array + flushPoint = i + 1; + this.flushDepth--; + + if (this.flushDepth < this.lastFlushDepth) { + this.flush(chunk, lastFlushPoint, flushPoint); + lastFlushPoint = flushPoint; + } + + break; + + case 0x09: /* \t */ + case 0x0A: /* \n */ + case 0x0D: /* \r */ + case 0x20: /* space */ + // Move points forward when they points on current position and it's a whitespace + if (lastFlushPoint === i) { + lastFlushPoint++; + } + + if (flushPoint === i) { + flushPoint++; + } + + break; + } + } + + if (flushPoint > lastFlushPoint) { + this.flush(chunk, lastFlushPoint, flushPoint); + } + + // Produce pendingChunk if something left + if (flushPoint < chunkLength) { + if (this.pendingChunk !== null) { + // When there is already a pending chunk then no flush happened, + // appending entire chunk to pending one + this.pendingChunk += chunk; + } else { + // Create a pending chunk, it will start with non-whitespace since + // flushPoint was moved forward away from whitespaces on scan + this.pendingChunk = chunk.slice(flushPoint, chunkLength); + } + } + + this.chunkOffset += chunkLength; + } + + finish() { + if (this.pendingChunk !== null) { + this.flush('', 0, 0); + this.pendingChunk = null; + } + + return this.value; + } + } + + var src = { + version: version, + stringifyInfo: stringifyInfo, + stringifyStream: stringifyStreamBrowser, + parseChunked: parseChunked + }; + + return src; + +})); diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/dist/json-ext.min.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/dist/json-ext.min.js new file mode 100644 index 0000000..e7e66b7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/dist/json-ext.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).jsonExt=t()}(this,(function(){"use strict";function e(e){return"function"==typeof e.pipe&&"function"==typeof e._read&&"object"==typeof e._readableState&&null!==e._readableState}var t={escapableCharCodeSubstitution:{8:"\\b",9:"\\t",10:"\\n",12:"\\f",13:"\\r",34:'\\"',92:"\\\\"},isLeadingSurrogate:function(e){return e>=55296&&e<=56319},isTrailingSurrogate:function(e){return e>=56320&&e<=57343},type:{PRIMITIVE:1,PROMISE:4,ARRAY:3,OBJECT:2,STRING_STREAM:5,OBJECT_STREAM:6},isReadableStream:e,replaceValue:function(e,t,s,n){switch(s&&"function"==typeof s.toJSON&&(s=s.toJSON()),null!==n&&(s=n.call(e,String(t),s)),typeof s){case"function":case"symbol":s=void 0;break;case"object":if(null!==s){const e=s.constructor;e!==String&&e!==Number&&e!==Boolean||(s=s.valueOf())}}return s},getTypeNative:function(e){return null===e||"object"!=typeof e?1:Array.isArray(e)?3:2},getTypeAsync:function(t){return null===t||"object"!=typeof t?1:"function"==typeof t.then?4:e(t)?t._readableState.objectMode?6:5:Array.isArray(t)?3:2},normalizeReplacer:function(e){return"function"==typeof e?e:Array.isArray(e)?[...new Set(e.map((e=>{const t=e&&e.constructor;return t===String||t===Number?String(e):null})).filter((e=>"string"==typeof e)))]:null},normalizeSpace:function(e){return"number"==typeof e?!(!Number.isFinite(e)||e<1)&&" ".repeat(Math.min(e,10)):"string"==typeof e&&e.slice(0,10)||!1}};const{normalizeReplacer:s,normalizeSpace:n,replaceValue:i,getTypeNative:r,getTypeAsync:a,isLeadingSurrogate:l,isTrailingSurrogate:h,escapableCharCodeSubstitution:u,type:{PRIMITIVE:o,OBJECT:c,ARRAY:f,PROMISE:p,STRING_STREAM:d,OBJECT_STREAM:g}}=t,y=Array.from({length:2048}).map(((e,t)=>u.hasOwnProperty(t)?2:t<32?6:t<128?1:2));function S(e){let t=0,s=!1;for(let n=0;n"at position "+(Number(s)+t.jsonParseOffset)))),e}class O{constructor(){this.value=void 0,this.valueStack=null,this.stack=new Array(100),this.lastFlushDepth=0,this.flushDepth=0,this.stateString=!1,this.stateStringEscape=!1,this.pendingByteSeq=null,this.pendingChunk=null,this.chunkOffset=0,this.jsonParseOffset=0}parseAndAppend(e,t){1===this.stack[this.lastFlushDepth-1]?(t&&(this.jsonParseOffset--,e="{"+e+"}"),Object.assign(this.valueStack.value,JSON.parse(e))):(t&&(this.jsonParseOffset--,e="["+e+"]"),function(e,t){const s=e.length;e.length+=t.length;for(let n=0;n0?this.parseAndAppend(this.prepareAddition(n),!0):(this.value=JSON.parse(n),this.valueStack={value:this.value,prev:null});else if(this.flushDepth>this.lastFlushDepth){for(let e=this.flushDepth-1;e>=this.lastFlushDepth;e--)n+=1===this.stack[e]?"}":"]";0===this.lastFlushDepth?(this.value=JSON.parse(n),this.valueStack={value:this.value,prev:null}):this.parseAndAppend(this.prepareAddition(n),!0);for(let e=this.lastFlushDepth||1;e=this.flushDepth;e--)this.jsonParseOffset--,n=(1===this.stack[e]?"{":"[")+n;this.parseAndAppend(n,!1);for(let e=this.lastFlushDepth-1;e>=this.flushDepth;e--)this.valueStack=this.valueStack.prev}this.lastFlushDepth=this.flushDepth}push(e){if("string"!=typeof e){if(null!==this.pendingByteSeq){const t=e;(e=new Uint8Array(this.pendingByteSeq.length+t.length)).set(this.pendingByteSeq),e.set(t,this.pendingByteSeq.length),this.pendingByteSeq=null}if(e[e.length-1]>127)for(let t=0;t>6==3){t++,(4!==t&&s>>3==30||3!==t&&s>>4==14||2!==t&&s>>5==6)&&(this.pendingByteSeq=e.slice(e.length-t),e=e.slice(0,-t));break}}e=A.decode(e)}const t=e.length;let s=0,n=0;e:for(let i=0;is&&this.flush(e,s,n),n1&&(D+=s-1),b.delete(r),l>0&&s>0&&(D+=(1+(b.size+1)*l+1)*s,D+=1+b.size*l),y.set(r,D-t);break}case f:{if(y.has(r)){k.add(r),D+=y.get(r);break}const t=D;D+=2,b.add(r);for(let t=0;t1&&(D+=r.length-1),b.delete(r),l>0&&r.length>0&&(D+=(1+(b.size+1)*l)*r.length,D+=1+b.size*l),y.set(r,D-t);break}case p:case d:v.add(r);break;case g:D+=2,v.add(r)}}(O,"",e),{minLength:isNaN(D)?1/0:D,circular:[...A],duplicate:[...k],async:[...v]}},stringifyStream:()=>{throw new Error("Method is not supported")},parseChunked:function(e){let t=new O;if(v(e)&&k(e))return new Promise(((s,n)=>{e.on("data",(e=>{try{t.push(e)}catch(e){n(m(e,t)),t=null}})).on("error",(e=>{t=null,n(e)})).on("end",(()=>{try{s(t.finish())}catch(e){n(m(e,t))}finally{t=null}}))}));if("function"==typeof e){const s=e();if(v(s)&&(Symbol.iterator in s||Symbol.asyncIterator in s))return new Promise((async(e,n)=>{try{for await(const e of s)t.push(e);e(t.finish())}catch(e){n(m(e,t))}finally{t=null}}))}throw new Error("Chunk emitter should be readable stream, generator, async generator or function returning an iterable object")}}})); diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/dist/version.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/dist/version.js new file mode 100644 index 0000000..3d0dce2 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/dist/version.js @@ -0,0 +1 @@ +module.exports = "0.5.7"; \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/index.d.ts b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/index.d.ts new file mode 100644 index 0000000..8b1d7c9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/index.d.ts @@ -0,0 +1,31 @@ +declare module '@discoveryjs/json-ext' { + import { Readable } from 'stream'; + + type TReplacer = + | ((this: any, key: string, value: any) => any) + | string[] + | number[] + | null; + type TSpace = string | number | null; + type TChunk = string | Buffer | Uint8Array; + + export function parseChunked(input: Readable): Promise; + export function parseChunked(input: () => (Iterable | AsyncIterable)): Promise; + + export function stringifyStream(value: any, replacer?: TReplacer, space?: TSpace): Readable; + + export function stringifyInfo( + value: any, + replacer?: TReplacer, + space?: TSpace, + options?: { + async?: boolean; + continueOnCircular?: boolean; + } + ): { + minLength: number; + circular: any[]; + duplicate: any[]; + async: any[]; + }; +} diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/package.json b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/package.json new file mode 100644 index 0000000..f6ccde5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/package.json @@ -0,0 +1,56 @@ +{ + "name": "@discoveryjs/json-ext", + "version": "0.5.7", + "description": "A set of utilities that extend the use of JSON", + "keywords": [ + "json", + "utils", + "stream", + "async", + "promise", + "stringify", + "info" + ], + "author": "Roman Dvornov (https://github.com/lahmatiy)", + "license": "MIT", + "repository": "discoveryjs/json-ext", + "main": "./src/index", + "browser": { + "./src/stringify-stream.js": "./src/stringify-stream-browser.js", + "./src/text-decoder.js": "./src/text-decoder-browser.js", + "./src/version.js": "./dist/version.js" + }, + "types": "./index.d.ts", + "scripts": { + "test": "mocha --reporter progress", + "lint": "eslint src test", + "lint-and-test": "npm run lint && npm test", + "build": "rollup --config", + "test:all": "npm run test:src && npm run test:dist", + "test:src": "npm test", + "test:dist": "cross-env MODE=dist npm test && cross-env MODE=dist-min npm test", + "build-and-test": "npm run build && npm run test:dist", + "coverage": "c8 --reporter=lcovonly npm test", + "prepublishOnly": "npm run lint && npm test && npm run build-and-test" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^15.1.0", + "@rollup/plugin-json": "^4.1.0", + "@rollup/plugin-node-resolve": "^9.0.0", + "c8": "^7.10.0", + "chalk": "^4.1.0", + "cross-env": "^7.0.3", + "eslint": "^8.10.0", + "mocha": "^8.4.0", + "rollup": "^2.28.2", + "rollup-plugin-terser": "^7.0.2" + }, + "engines": { + "node": ">=10.0.0" + }, + "files": [ + "dist", + "src", + "index.d.ts" + ] +} diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/index.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/index.js new file mode 100644 index 0000000..ae05057 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/index.js @@ -0,0 +1,6 @@ +module.exports = { + version: require('./version'), + stringifyInfo: require('./stringify-info'), + stringifyStream: require('./stringify-stream'), + parseChunked: require('./parse-chunked') +}; diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/parse-chunked.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/parse-chunked.js new file mode 100644 index 0000000..87f7209 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/parse-chunked.js @@ -0,0 +1,384 @@ +const { isReadableStream } = require('./utils'); +const TextDecoder = require('./text-decoder'); + +const STACK_OBJECT = 1; +const STACK_ARRAY = 2; +const decoder = new TextDecoder(); + +function isObject(value) { + return value !== null && typeof value === 'object'; +} + +function adjustPosition(error, parser) { + if (error.name === 'SyntaxError' && parser.jsonParseOffset) { + error.message = error.message.replace(/at position (\d+)/, (_, pos) => + 'at position ' + (Number(pos) + parser.jsonParseOffset) + ); + } + + return error; +} + +function append(array, elements) { + // Note: Avoid to use array.push(...elements) since it may lead to + // "RangeError: Maximum call stack size exceeded" for a long arrays + const initialLength = array.length; + array.length += elements.length; + + for (let i = 0; i < elements.length; i++) { + array[initialLength + i] = elements[i]; + } +} + +module.exports = function(chunkEmitter) { + let parser = new ChunkParser(); + + if (isObject(chunkEmitter) && isReadableStream(chunkEmitter)) { + return new Promise((resolve, reject) => { + chunkEmitter + .on('data', chunk => { + try { + parser.push(chunk); + } catch (e) { + reject(adjustPosition(e, parser)); + parser = null; + } + }) + .on('error', (e) => { + parser = null; + reject(e); + }) + .on('end', () => { + try { + resolve(parser.finish()); + } catch (e) { + reject(adjustPosition(e, parser)); + } finally { + parser = null; + } + }); + }); + } + + if (typeof chunkEmitter === 'function') { + const iterator = chunkEmitter(); + + if (isObject(iterator) && (Symbol.iterator in iterator || Symbol.asyncIterator in iterator)) { + return new Promise(async (resolve, reject) => { + try { + for await (const chunk of iterator) { + parser.push(chunk); + } + + resolve(parser.finish()); + } catch (e) { + reject(adjustPosition(e, parser)); + } finally { + parser = null; + } + }); + } + } + + throw new Error( + 'Chunk emitter should be readable stream, generator, ' + + 'async generator or function returning an iterable object' + ); +}; + +class ChunkParser { + constructor() { + this.value = undefined; + this.valueStack = null; + + this.stack = new Array(100); + this.lastFlushDepth = 0; + this.flushDepth = 0; + this.stateString = false; + this.stateStringEscape = false; + this.pendingByteSeq = null; + this.pendingChunk = null; + this.chunkOffset = 0; + this.jsonParseOffset = 0; + } + + parseAndAppend(fragment, wrap) { + // Append new entries or elements + if (this.stack[this.lastFlushDepth - 1] === STACK_OBJECT) { + if (wrap) { + this.jsonParseOffset--; + fragment = '{' + fragment + '}'; + } + + Object.assign(this.valueStack.value, JSON.parse(fragment)); + } else { + if (wrap) { + this.jsonParseOffset--; + fragment = '[' + fragment + ']'; + } + + append(this.valueStack.value, JSON.parse(fragment)); + } + } + + prepareAddition(fragment) { + const { value } = this.valueStack; + const expectComma = Array.isArray(value) + ? value.length !== 0 + : Object.keys(value).length !== 0; + + if (expectComma) { + // Skip a comma at the beginning of fragment, otherwise it would + // fail to parse + if (fragment[0] === ',') { + this.jsonParseOffset++; + return fragment.slice(1); + } + + // When value (an object or array) is not empty and a fragment + // doesn't start with a comma, a single valid fragment starting + // is a closing bracket. If it's not, a prefix is adding to fail + // parsing. Otherwise, the sequence of chunks can be successfully + // parsed, although it should not, e.g. ["[{}", "{}]"] + if (fragment[0] !== '}' && fragment[0] !== ']') { + this.jsonParseOffset -= 3; + return '[[]' + fragment; + } + } + + return fragment; + } + + flush(chunk, start, end) { + let fragment = chunk.slice(start, end); + + // Save position correction an error in JSON.parse() if any + this.jsonParseOffset = this.chunkOffset + start; + + // Prepend pending chunk if any + if (this.pendingChunk !== null) { + fragment = this.pendingChunk + fragment; + this.jsonParseOffset -= this.pendingChunk.length; + this.pendingChunk = null; + } + + if (this.flushDepth === this.lastFlushDepth) { + // Depth didn't changed, so it's a root value or entry/element set + if (this.flushDepth > 0) { + this.parseAndAppend(this.prepareAddition(fragment), true); + } else { + // That's an entire value on a top level + this.value = JSON.parse(fragment); + this.valueStack = { + value: this.value, + prev: null + }; + } + } else if (this.flushDepth > this.lastFlushDepth) { + // Add missed closing brackets/parentheses + for (let i = this.flushDepth - 1; i >= this.lastFlushDepth; i--) { + fragment += this.stack[i] === STACK_OBJECT ? '}' : ']'; + } + + if (this.lastFlushDepth === 0) { + // That's a root value + this.value = JSON.parse(fragment); + this.valueStack = { + value: this.value, + prev: null + }; + } else { + this.parseAndAppend(this.prepareAddition(fragment), true); + } + + // Move down to the depths to the last object/array, which is current now + for (let i = this.lastFlushDepth || 1; i < this.flushDepth; i++) { + let value = this.valueStack.value; + + if (this.stack[i - 1] === STACK_OBJECT) { + // find last entry + let key; + // eslint-disable-next-line curly + for (key in value); + value = value[key]; + } else { + // last element + value = value[value.length - 1]; + } + + this.valueStack = { + value, + prev: this.valueStack + }; + } + } else /* this.flushDepth < this.lastFlushDepth */ { + fragment = this.prepareAddition(fragment); + + // Add missed opening brackets/parentheses + for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) { + this.jsonParseOffset--; + fragment = (this.stack[i] === STACK_OBJECT ? '{' : '[') + fragment; + } + + this.parseAndAppend(fragment, false); + + for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) { + this.valueStack = this.valueStack.prev; + } + } + + this.lastFlushDepth = this.flushDepth; + } + + push(chunk) { + if (typeof chunk !== 'string') { + // Suppose chunk is Buffer or Uint8Array + + // Prepend uncompleted byte sequence if any + if (this.pendingByteSeq !== null) { + const origRawChunk = chunk; + chunk = new Uint8Array(this.pendingByteSeq.length + origRawChunk.length); + chunk.set(this.pendingByteSeq); + chunk.set(origRawChunk, this.pendingByteSeq.length); + this.pendingByteSeq = null; + } + + // In case Buffer/Uint8Array, an input is encoded in UTF8 + // Seek for parts of uncompleted UTF8 symbol on the ending + // This makes sense only if we expect more chunks and last char is not multi-bytes + if (chunk[chunk.length - 1] > 127) { + for (let seqLength = 0; seqLength < chunk.length; seqLength++) { + const byte = chunk[chunk.length - 1 - seqLength]; + + // 10xxxxxx - 2nd, 3rd or 4th byte + // 110xxxxx – first byte of 2-byte sequence + // 1110xxxx - first byte of 3-byte sequence + // 11110xxx - first byte of 4-byte sequence + if (byte >> 6 === 3) { + seqLength++; + + // If the sequence is really incomplete, then preserve it + // for the future chunk and cut off it from the current chunk + if ((seqLength !== 4 && byte >> 3 === 0b11110) || + (seqLength !== 3 && byte >> 4 === 0b1110) || + (seqLength !== 2 && byte >> 5 === 0b110)) { + this.pendingByteSeq = chunk.slice(chunk.length - seqLength); + chunk = chunk.slice(0, -seqLength); + } + + break; + } + } + } + + // Convert chunk to a string, since single decode per chunk + // is much effective than decode multiple small substrings + chunk = decoder.decode(chunk); + } + + const chunkLength = chunk.length; + let lastFlushPoint = 0; + let flushPoint = 0; + + // Main scan loop + scan: for (let i = 0; i < chunkLength; i++) { + if (this.stateString) { + for (; i < chunkLength; i++) { + if (this.stateStringEscape) { + this.stateStringEscape = false; + } else { + switch (chunk.charCodeAt(i)) { + case 0x22: /* " */ + this.stateString = false; + continue scan; + + case 0x5C: /* \ */ + this.stateStringEscape = true; + } + } + } + + break; + } + + switch (chunk.charCodeAt(i)) { + case 0x22: /* " */ + this.stateString = true; + this.stateStringEscape = false; + break; + + case 0x2C: /* , */ + flushPoint = i; + break; + + case 0x7B: /* { */ + // Open an object + flushPoint = i + 1; + this.stack[this.flushDepth++] = STACK_OBJECT; + break; + + case 0x5B: /* [ */ + // Open an array + flushPoint = i + 1; + this.stack[this.flushDepth++] = STACK_ARRAY; + break; + + case 0x5D: /* ] */ + case 0x7D: /* } */ + // Close an object or array + flushPoint = i + 1; + this.flushDepth--; + + if (this.flushDepth < this.lastFlushDepth) { + this.flush(chunk, lastFlushPoint, flushPoint); + lastFlushPoint = flushPoint; + } + + break; + + case 0x09: /* \t */ + case 0x0A: /* \n */ + case 0x0D: /* \r */ + case 0x20: /* space */ + // Move points forward when they points on current position and it's a whitespace + if (lastFlushPoint === i) { + lastFlushPoint++; + } + + if (flushPoint === i) { + flushPoint++; + } + + break; + } + } + + if (flushPoint > lastFlushPoint) { + this.flush(chunk, lastFlushPoint, flushPoint); + } + + // Produce pendingChunk if something left + if (flushPoint < chunkLength) { + if (this.pendingChunk !== null) { + // When there is already a pending chunk then no flush happened, + // appending entire chunk to pending one + this.pendingChunk += chunk; + } else { + // Create a pending chunk, it will start with non-whitespace since + // flushPoint was moved forward away from whitespaces on scan + this.pendingChunk = chunk.slice(flushPoint, chunkLength); + } + } + + this.chunkOffset += chunkLength; + } + + finish() { + if (this.pendingChunk !== null) { + this.flush('', 0, 0); + this.pendingChunk = null; + } + + return this.value; + } +}; diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/stringify-info.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/stringify-info.js new file mode 100644 index 0000000..2678f11 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/stringify-info.js @@ -0,0 +1,231 @@ +const { + normalizeReplacer, + normalizeSpace, + replaceValue, + getTypeNative, + getTypeAsync, + isLeadingSurrogate, + isTrailingSurrogate, + escapableCharCodeSubstitution, + type: { + PRIMITIVE, + OBJECT, + ARRAY, + PROMISE, + STRING_STREAM, + OBJECT_STREAM + } +} = require('./utils'); +const charLength2048 = Array.from({ length: 2048 }).map((_, code) => { + if (escapableCharCodeSubstitution.hasOwnProperty(code)) { + return 2; // \X + } + + if (code < 0x20) { + return 6; // \uXXXX + } + + return code < 128 ? 1 : 2; // UTF8 bytes +}); + +function stringLength(str) { + let len = 0; + let prevLeadingSurrogate = false; + + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i); + + if (code < 2048) { + len += charLength2048[code]; + } else if (isLeadingSurrogate(code)) { + len += 6; // \uXXXX since no pair with trailing surrogate yet + prevLeadingSurrogate = true; + continue; + } else if (isTrailingSurrogate(code)) { + len = prevLeadingSurrogate + ? len - 2 // surrogate pair (4 bytes), since we calculate prev leading surrogate as 6 bytes, substruct 2 bytes + : len + 6; // \uXXXX + } else { + len += 3; // code >= 2048 is 3 bytes length for UTF8 + } + + prevLeadingSurrogate = false; + } + + return len + 2; // +2 for quotes +} + +function primitiveLength(value) { + switch (typeof value) { + case 'string': + return stringLength(value); + + case 'number': + return Number.isFinite(value) ? String(value).length : 4 /* null */; + + case 'boolean': + return value ? 4 /* true */ : 5 /* false */; + + case 'undefined': + case 'object': + return 4; /* null */ + + default: + return 0; + } +} + +function spaceLength(space) { + space = normalizeSpace(space); + return typeof space === 'string' ? space.length : 0; +} + +module.exports = function jsonStringifyInfo(value, replacer, space, options) { + function walk(holder, key, value) { + if (stop) { + return; + } + + value = replaceValue(holder, key, value, replacer); + + let type = getType(value); + + // check for circular structure + if (type !== PRIMITIVE && stack.has(value)) { + circular.add(value); + length += 4; // treat as null + + if (!options.continueOnCircular) { + stop = true; + } + + return; + } + + switch (type) { + case PRIMITIVE: + if (value !== undefined || Array.isArray(holder)) { + length += primitiveLength(value); + } else if (holder === root) { + length += 9; // FIXME: that's the length of undefined, should we normalize behaviour to convert it to null? + } + break; + + case OBJECT: { + if (visited.has(value)) { + duplicate.add(value); + length += visited.get(value); + break; + } + + const valueLength = length; + let entries = 0; + + length += 2; // {} + + stack.add(value); + + for (const key in value) { + if (hasOwnProperty.call(value, key) && (allowlist === null || allowlist.has(key))) { + const prevLength = length; + walk(value, key, value[key]); + + if (prevLength !== length) { + // value is printed + length += stringLength(key) + 1; // "key": + entries++; + } + } + } + + if (entries > 1) { + length += entries - 1; // commas + } + + stack.delete(value); + + if (space > 0 && entries > 0) { + length += (1 + (stack.size + 1) * space + 1) * entries; // for each key-value: \n{space} + length += 1 + stack.size * space; // for } + } + + visited.set(value, length - valueLength); + + break; + } + + case ARRAY: { + if (visited.has(value)) { + duplicate.add(value); + length += visited.get(value); + break; + } + + const valueLength = length; + + length += 2; // [] + + stack.add(value); + + for (let i = 0; i < value.length; i++) { + walk(value, i, value[i]); + } + + if (value.length > 1) { + length += value.length - 1; // commas + } + + stack.delete(value); + + if (space > 0 && value.length > 0) { + length += (1 + (stack.size + 1) * space) * value.length; // for each element: \n{space} + length += 1 + stack.size * space; // for ] + } + + visited.set(value, length - valueLength); + + break; + } + + case PROMISE: + case STRING_STREAM: + async.add(value); + break; + + case OBJECT_STREAM: + length += 2; // [] + async.add(value); + break; + } + } + + let allowlist = null; + replacer = normalizeReplacer(replacer); + + if (Array.isArray(replacer)) { + allowlist = new Set(replacer); + replacer = null; + } + + space = spaceLength(space); + options = options || {}; + + const visited = new Map(); + const stack = new Set(); + const duplicate = new Set(); + const circular = new Set(); + const async = new Set(); + const getType = options.async ? getTypeAsync : getTypeNative; + const root = { '': value }; + let stop = false; + let length = 0; + + walk(root, '', value); + + return { + minLength: isNaN(length) ? Infinity : length, + circular: [...circular], + duplicate: [...duplicate], + async: [...async] + }; +}; diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/stringify-stream-browser.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/stringify-stream-browser.js new file mode 100644 index 0000000..e11ccb6 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/stringify-stream-browser.js @@ -0,0 +1,3 @@ +module.exports = () => { + throw new Error('Method is not supported'); +}; diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/stringify-stream.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/stringify-stream.js new file mode 100644 index 0000000..4f983a7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/stringify-stream.js @@ -0,0 +1,408 @@ +const { Readable } = require('stream'); +const { + normalizeReplacer, + normalizeSpace, + replaceValue, + getTypeAsync, + type: { + PRIMITIVE, + OBJECT, + ARRAY, + PROMISE, + STRING_STREAM, + OBJECT_STREAM + } +} = require('./utils'); +const noop = () => {}; +const hasOwnProperty = Object.prototype.hasOwnProperty; + +// TODO: Remove when drop support for Node.js 10 +// Node.js 10 has no well-formed JSON.stringify() +// https://github.com/tc39/proposal-well-formed-stringify +// Adopted code from https://bugs.chromium.org/p/v8/issues/detail?id=7782#c12 +const wellformedStringStringify = JSON.stringify('\ud800') === '"\\ud800"' + ? JSON.stringify + : s => JSON.stringify(s).replace( + /\p{Surrogate}/gu, + m => `\\u${m.charCodeAt(0).toString(16)}` + ); + +function push() { + this.push(this._stack.value); + this.popStack(); +} + +function pushPrimitive(value) { + switch (typeof value) { + case 'string': + this.push(this.encodeString(value)); + break; + + case 'number': + this.push(Number.isFinite(value) ? this.encodeNumber(value) : 'null'); + break; + + case 'boolean': + this.push(value ? 'true' : 'false'); + break; + + case 'undefined': + case 'object': // typeof null === 'object' + this.push('null'); + break; + + default: + this.destroy(new TypeError(`Do not know how to serialize a ${value.constructor && value.constructor.name || typeof value}`)); + } +} + +function processObjectEntry(key) { + const current = this._stack; + + if (!current.first) { + current.first = true; + } else { + this.push(','); + } + + if (this.space) { + this.push(`\n${this.space.repeat(this._depth)}${this.encodeString(key)}: `); + } else { + this.push(this.encodeString(key) + ':'); + } +} + +function processObject() { + const current = this._stack; + + // when no keys left, remove obj from stack + if (current.index === current.keys.length) { + if (this.space && current.first) { + this.push(`\n${this.space.repeat(this._depth - 1)}}`); + } else { + this.push('}'); + } + + this.popStack(); + return; + } + + const key = current.keys[current.index]; + + this.processValue(current.value, key, current.value[key], processObjectEntry); + current.index++; +} + +function processArrayItem(index) { + if (index !== 0) { + this.push(','); + } + + if (this.space) { + this.push(`\n${this.space.repeat(this._depth)}`); + } +} + +function processArray() { + const current = this._stack; + + if (current.index === current.value.length) { + if (this.space && current.index > 0) { + this.push(`\n${this.space.repeat(this._depth - 1)}]`); + } else { + this.push(']'); + } + + this.popStack(); + return; + } + + this.processValue(current.value, current.index, current.value[current.index], processArrayItem); + current.index++; +} + +function createStreamReader(fn) { + return function() { + const current = this._stack; + const data = current.value.read(this._readSize); + + if (data !== null) { + current.first = false; + fn.call(this, data, current); + } else { + if ((current.first && !current.value._readableState.reading) || current.ended) { + this.popStack(); + } else { + current.first = true; + current.awaiting = true; + } + } + }; +} + +const processReadableObject = createStreamReader(function(data, current) { + this.processValue(current.value, current.index, data, processArrayItem); + current.index++; +}); + +const processReadableString = createStreamReader(function(data) { + this.push(data); +}); + +class JsonStringifyStream extends Readable { + constructor(value, replacer, space) { + super({ + autoDestroy: true + }); + + this.getKeys = Object.keys; + this.replacer = normalizeReplacer(replacer); + + if (Array.isArray(this.replacer)) { + const allowlist = this.replacer; + + this.getKeys = (value) => allowlist.filter(key => hasOwnProperty.call(value, key)); + this.replacer = null; + } + + this.space = normalizeSpace(space); + this._depth = 0; + + this.error = null; + this._processing = false; + this._ended = false; + + this._readSize = 0; + this._buffer = ''; + + this._stack = null; + this._visited = new WeakSet(); + + this.pushStack({ + handler: () => { + this.popStack(); + this.processValue({ '': value }, '', value, noop); + } + }); + } + + encodeString(value) { + if (/[^\x20-\uD799]|[\x22\x5c]/.test(value)) { + return wellformedStringStringify(value); + } + + return '"' + value + '"'; + } + + encodeNumber(value) { + return value; + } + + processValue(holder, key, value, callback) { + value = replaceValue(holder, key, value, this.replacer); + + let type = getTypeAsync(value); + + switch (type) { + case PRIMITIVE: + if (callback !== processObjectEntry || value !== undefined) { + callback.call(this, key); + pushPrimitive.call(this, value); + } + break; + + case OBJECT: + callback.call(this, key); + + // check for circular structure + if (this._visited.has(value)) { + return this.destroy(new TypeError('Converting circular structure to JSON')); + } + + this._visited.add(value); + this._depth++; + this.push('{'); + this.pushStack({ + handler: processObject, + value, + index: 0, + first: false, + keys: this.getKeys(value) + }); + break; + + case ARRAY: + callback.call(this, key); + + // check for circular structure + if (this._visited.has(value)) { + return this.destroy(new TypeError('Converting circular structure to JSON')); + } + + this._visited.add(value); + + this.push('['); + this.pushStack({ + handler: processArray, + value, + index: 0 + }); + this._depth++; + break; + + case PROMISE: + this.pushStack({ + handler: noop, + awaiting: true + }); + + Promise.resolve(value) + .then(resolved => { + this.popStack(); + this.processValue(holder, key, resolved, callback); + this.processStack(); + }) + .catch(error => { + this.destroy(error); + }); + break; + + case STRING_STREAM: + case OBJECT_STREAM: + callback.call(this, key); + + // TODO: Remove when drop support for Node.js 10 + // Used `_readableState.endEmitted` as fallback, since Node.js 10 has no `readableEnded` getter + if (value.readableEnded || value._readableState.endEmitted) { + return this.destroy(new Error('Readable Stream has ended before it was serialized. All stream data have been lost')); + } + + if (value.readableFlowing) { + return this.destroy(new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.')); + } + + if (type === OBJECT_STREAM) { + this.push('['); + this.pushStack({ + handler: push, + value: this.space ? '\n' + this.space.repeat(this._depth) + ']' : ']' + }); + this._depth++; + } + + const self = this.pushStack({ + handler: type === OBJECT_STREAM ? processReadableObject : processReadableString, + value, + index: 0, + first: false, + ended: false, + awaiting: !value.readable || value.readableLength === 0 + }); + const continueProcessing = () => { + if (self.awaiting) { + self.awaiting = false; + this.processStack(); + } + }; + + value.once('error', error => this.destroy(error)); + value.once('end', () => { + self.ended = true; + continueProcessing(); + }); + value.on('readable', continueProcessing); + break; + } + } + + pushStack(node) { + node.prev = this._stack; + return this._stack = node; + } + + popStack() { + const { handler, value } = this._stack; + + if (handler === processObject || handler === processArray || handler === processReadableObject) { + this._visited.delete(value); + this._depth--; + } + + this._stack = this._stack.prev; + } + + processStack() { + if (this._processing || this._ended) { + return; + } + + try { + this._processing = true; + + while (this._stack !== null && !this._stack.awaiting) { + this._stack.handler.call(this); + + if (!this._processing) { + return; + } + } + + this._processing = false; + } catch (error) { + this.destroy(error); + return; + } + + if (this._stack === null && !this._ended) { + this._finish(); + this.push(null); + } + } + + push(data) { + if (data !== null) { + this._buffer += data; + + // check buffer overflow + if (this._buffer.length < this._readSize) { + return; + } + + // flush buffer + data = this._buffer; + this._buffer = ''; + this._processing = false; + } + + super.push(data); + } + + _read(size) { + // start processing + this._readSize = size || this.readableHighWaterMark; + this.processStack(); + } + + _finish() { + this._ended = true; + this._processing = false; + this._stack = null; + this._visited = null; + + if (this._buffer && this._buffer.length) { + super.push(this._buffer); // flush buffer + } + + this._buffer = ''; + } + + _destroy(error, cb) { + this.error = this.error || error; + this._finish(); + cb(error); + } +} + +module.exports = function createJsonStringifyStream(value, replacer, space) { + return new JsonStringifyStream(value, replacer, space); +}; diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/text-decoder-browser.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/text-decoder-browser.js new file mode 100644 index 0000000..11befa2 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/text-decoder-browser.js @@ -0,0 +1 @@ +module.exports = TextDecoder; diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/text-decoder.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/text-decoder.js new file mode 100644 index 0000000..99fa6d5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/text-decoder.js @@ -0,0 +1 @@ +module.exports = require('util').TextDecoder; diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/utils.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/utils.js new file mode 100644 index 0000000..b79bc72 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/utils.js @@ -0,0 +1,149 @@ +const PrimitiveType = 1; +const ObjectType = 2; +const ArrayType = 3; +const PromiseType = 4; +const ReadableStringType = 5; +const ReadableObjectType = 6; +// https://tc39.es/ecma262/#table-json-single-character-escapes +const escapableCharCodeSubstitution = { // JSON Single Character Escape Sequences + 0x08: '\\b', + 0x09: '\\t', + 0x0a: '\\n', + 0x0c: '\\f', + 0x0d: '\\r', + 0x22: '\\\"', + 0x5c: '\\\\' +}; + +function isLeadingSurrogate(code) { + return code >= 0xD800 && code <= 0xDBFF; +} + +function isTrailingSurrogate(code) { + return code >= 0xDC00 && code <= 0xDFFF; +} + +function isReadableStream(value) { + return ( + typeof value.pipe === 'function' && + typeof value._read === 'function' && + typeof value._readableState === 'object' && value._readableState !== null + ); +} + +function replaceValue(holder, key, value, replacer) { + if (value && typeof value.toJSON === 'function') { + value = value.toJSON(); + } + + if (replacer !== null) { + value = replacer.call(holder, String(key), value); + } + + switch (typeof value) { + case 'function': + case 'symbol': + value = undefined; + break; + + case 'object': + if (value !== null) { + const cls = value.constructor; + if (cls === String || cls === Number || cls === Boolean) { + value = value.valueOf(); + } + } + break; + } + + return value; +} + +function getTypeNative(value) { + if (value === null || typeof value !== 'object') { + return PrimitiveType; + } + + if (Array.isArray(value)) { + return ArrayType; + } + + return ObjectType; +} + +function getTypeAsync(value) { + if (value === null || typeof value !== 'object') { + return PrimitiveType; + } + + if (typeof value.then === 'function') { + return PromiseType; + } + + if (isReadableStream(value)) { + return value._readableState.objectMode ? ReadableObjectType : ReadableStringType; + } + + if (Array.isArray(value)) { + return ArrayType; + } + + return ObjectType; +} + +function normalizeReplacer(replacer) { + if (typeof replacer === 'function') { + return replacer; + } + + if (Array.isArray(replacer)) { + const allowlist = new Set(replacer + .map(item => { + const cls = item && item.constructor; + return cls === String || cls === Number ? String(item) : null; + }) + .filter(item => typeof item === 'string') + ); + + return [...allowlist]; + } + + return null; +} + +function normalizeSpace(space) { + if (typeof space === 'number') { + if (!Number.isFinite(space) || space < 1) { + return false; + } + + return ' '.repeat(Math.min(space, 10)); + } + + if (typeof space === 'string') { + return space.slice(0, 10) || false; + } + + return false; +} + +module.exports = { + escapableCharCodeSubstitution, + isLeadingSurrogate, + isTrailingSurrogate, + type: { + PRIMITIVE: PrimitiveType, + PROMISE: PromiseType, + ARRAY: ArrayType, + OBJECT: ObjectType, + STRING_STREAM: ReadableStringType, + OBJECT_STREAM: ReadableObjectType + }, + + isReadableStream, + replaceValue, + getTypeNative, + getTypeAsync, + normalizeReplacer, + normalizeSpace +}; diff --git a/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/version.js b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/version.js new file mode 100644 index 0000000..81f6e78 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@discoveryjs/json-ext/src/version.js @@ -0,0 +1 @@ +module.exports = require('../package.json').version; diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint-scope/LICENSE b/node_modules/mathjs/examples/node_modules/@types/eslint-scope/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint-scope/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint-scope/README.md b/node_modules/mathjs/examples/node_modules/@types/eslint-scope/README.md new file mode 100644 index 0000000..81f42d5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint-scope/README.md @@ -0,0 +1,84 @@ +# Installation +> `npm install --save @types/eslint-scope` + +# Summary +This package contains type definitions for eslint-scope (https://github.com/eslint/eslint-scope). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/eslint-scope. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/eslint-scope/index.d.ts) +````ts +// Type definitions for eslint-scope 3.7 +// Project: https://github.com/eslint/eslint-scope +// Definitions by: Toru Nagashima +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.8 +import * as eslint from "eslint"; +import * as estree from "estree"; + +export const version: string; + +export class ScopeManager implements eslint.Scope.ScopeManager { + scopes: Scope[]; + globalScope: Scope; + acquire(node: {}, inner?: boolean): Scope | null; + getDeclaredVariables(node: {}): Variable[]; +} + +export class Scope implements eslint.Scope.Scope { + type: "block" | "catch" | "class" | "for" | "function" | "function-expression-name" | "global" | "module" | "switch" | "with" | "TDZ"; + isStrict: boolean; + upper: Scope | null; + childScopes: Scope[]; + variableScope: Scope; + block: estree.Node; + variables: Variable[]; + set: Map; + references: Reference[]; + through: Reference[]; + functionExpressionScope: boolean; +} + +export class Variable implements eslint.Scope.Variable { + name: string; + identifiers: estree.Identifier[]; + references: Reference[]; + defs: eslint.Scope.Definition[]; +} + +export class Reference implements eslint.Scope.Reference { + identifier: estree.Identifier; + from: Scope; + resolved: Variable | null; + writeExpr: estree.Node | null; + init: boolean; + + isWrite(): boolean; + isRead(): boolean; + isWriteOnly(): boolean; + isReadOnly(): boolean; + isReadWrite(): boolean; +} + +export interface AnalysisOptions { + optimistic?: boolean; + directive?: boolean; + ignoreEval?: boolean; + nodejsScope?: boolean; + impliedStrict?: boolean; + fallback?: string | ((node: {}) => string[]); + sourceType?: "script" | "module"; + ecmaVersion?: number; +} + +export function analyze(ast: {}, options?: AnalysisOptions): ScopeManager; + +```` + +### Additional Details + * Last updated: Mon, 10 Jan 2022 21:01:33 GMT + * Dependencies: [@types/eslint](https://npmjs.com/package/@types/eslint), [@types/estree](https://npmjs.com/package/@types/estree) + * Global values: none + +# Credits +These definitions were written by [Toru Nagashima](https://github.com/mysticatea). diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint-scope/index.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint-scope/index.d.ts new file mode 100644 index 0000000..a54941d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint-scope/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for eslint-scope 3.7 +// Project: https://github.com/eslint/eslint-scope +// Definitions by: Toru Nagashima +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.8 +import * as eslint from "eslint"; +import * as estree from "estree"; + +export const version: string; + +export class ScopeManager implements eslint.Scope.ScopeManager { + scopes: Scope[]; + globalScope: Scope; + acquire(node: {}, inner?: boolean): Scope | null; + getDeclaredVariables(node: {}): Variable[]; +} + +export class Scope implements eslint.Scope.Scope { + type: "block" | "catch" | "class" | "for" | "function" | "function-expression-name" | "global" | "module" | "switch" | "with" | "TDZ"; + isStrict: boolean; + upper: Scope | null; + childScopes: Scope[]; + variableScope: Scope; + block: estree.Node; + variables: Variable[]; + set: Map; + references: Reference[]; + through: Reference[]; + functionExpressionScope: boolean; +} + +export class Variable implements eslint.Scope.Variable { + name: string; + identifiers: estree.Identifier[]; + references: Reference[]; + defs: eslint.Scope.Definition[]; +} + +export class Reference implements eslint.Scope.Reference { + identifier: estree.Identifier; + from: Scope; + resolved: Variable | null; + writeExpr: estree.Node | null; + init: boolean; + + isWrite(): boolean; + isRead(): boolean; + isWriteOnly(): boolean; + isReadOnly(): boolean; + isReadWrite(): boolean; +} + +export interface AnalysisOptions { + optimistic?: boolean; + directive?: boolean; + ignoreEval?: boolean; + nodejsScope?: boolean; + impliedStrict?: boolean; + fallback?: string | ((node: {}) => string[]); + sourceType?: "script" | "module"; + ecmaVersion?: number; +} + +export function analyze(ast: {}, options?: AnalysisOptions): ScopeManager; diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint-scope/package.json b/node_modules/mathjs/examples/node_modules/@types/eslint-scope/package.json new file mode 100644 index 0000000..9a67ffb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint-scope/package.json @@ -0,0 +1,28 @@ +{ + "name": "@types/eslint-scope", + "version": "3.7.3", + "description": "TypeScript definitions for eslint-scope", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/eslint-scope", + "license": "MIT", + "contributors": [ + { + "name": "Toru Nagashima", + "url": "https://github.com/mysticatea", + "githubUsername": "mysticatea" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/eslint-scope" + }, + "scripts": {}, + "dependencies": { + "@types/eslint": "*", + "@types/estree": "*" + }, + "typesPublisherContentHash": "8e411ace0ab4265f36d35de1569d64466d2b58696d0afdd65620550a4762f1f4", + "typeScriptVersion": "3.8" +} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/LICENSE b/node_modules/mathjs/examples/node_modules/@types/eslint/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/README.md b/node_modules/mathjs/examples/node_modules/@types/eslint/README.md new file mode 100644 index 0000000..e2923b5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/eslint` + +# Summary +This package contains type definitions for eslint (https://eslint.org). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/eslint. + +### Additional Details + * Last updated: Sat, 22 Jan 2022 19:01:30 GMT + * Dependencies: [@types/json-schema](https://npmjs.com/package/@types/json-schema), [@types/estree](https://npmjs.com/package/@types/estree) + * Global values: none + +# Credits +These definitions were written by [Pierre-Marie Dartus](https://github.com/pmdartus), [Jed Fox](https://github.com/j-f1), [Saad Quadri](https://github.com/saadq), [Jason Kwok](https://github.com/JasonHK), [Brad Zacher](https://github.com/bradzacher), and [JounQin](https://github.com/JounQin). diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/helpers.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/helpers.d.ts new file mode 100644 index 0000000..0cf2141 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/helpers.d.ts @@ -0,0 +1,3 @@ +type Prepend = ((_: Addend, ..._1: Tuple) => any) extends (..._: infer Result) => any + ? Result + : never; diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/index.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/index.d.ts new file mode 100644 index 0000000..1f50fcc --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/index.d.ts @@ -0,0 +1,953 @@ +// Type definitions for eslint 8.4 +// Project: https://eslint.org +// Definitions by: Pierre-Marie Dartus +// Jed Fox +// Saad Quadri +// Jason Kwok +// Brad Zacher +// JounQin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { JSONSchema4 } from "json-schema"; +import * as ESTree from "estree"; + +export namespace AST { + type TokenType = + | "Boolean" + | "Null" + | "Identifier" + | "Keyword" + | "Punctuator" + | "JSXIdentifier" + | "JSXText" + | "Numeric" + | "String" + | "RegularExpression"; + + interface Token { + type: TokenType; + value: string; + range: Range; + loc: SourceLocation; + } + + interface SourceLocation { + start: ESTree.Position; + end: ESTree.Position; + } + + type Range = [number, number]; + + interface Program extends ESTree.Program { + comments: ESTree.Comment[]; + tokens: Token[]; + loc: SourceLocation; + range: Range; + } +} + +export namespace Scope { + interface ScopeManager { + scopes: Scope[]; + globalScope: Scope | null; + + acquire(node: ESTree.Node, inner?: boolean): Scope | null; + + getDeclaredVariables(node: ESTree.Node): Variable[]; + } + + interface Scope { + type: + | "block" + | "catch" + | "class" + | "for" + | "function" + | "function-expression-name" + | "global" + | "module" + | "switch" + | "with" + | "TDZ"; + isStrict: boolean; + upper: Scope | null; + childScopes: Scope[]; + variableScope: Scope; + block: ESTree.Node; + variables: Variable[]; + set: Map; + references: Reference[]; + through: Reference[]; + functionExpressionScope: boolean; + } + + interface Variable { + name: string; + identifiers: ESTree.Identifier[]; + references: Reference[]; + defs: Definition[]; + } + + interface Reference { + identifier: ESTree.Identifier; + from: Scope; + resolved: Variable | null; + writeExpr: ESTree.Node | null; + init: boolean; + + isWrite(): boolean; + + isRead(): boolean; + + isWriteOnly(): boolean; + + isReadOnly(): boolean; + + isReadWrite(): boolean; + } + + type DefinitionType = + | { type: "CatchClause"; node: ESTree.CatchClause; parent: null } + | { type: "ClassName"; node: ESTree.ClassDeclaration | ESTree.ClassExpression; parent: null } + | { type: "FunctionName"; node: ESTree.FunctionDeclaration | ESTree.FunctionExpression; parent: null } + | { type: "ImplicitGlobalVariable"; node: ESTree.Program; parent: null } + | { + type: "ImportBinding"; + node: ESTree.ImportSpecifier | ESTree.ImportDefaultSpecifier | ESTree.ImportNamespaceSpecifier; + parent: ESTree.ImportDeclaration; + } + | { + type: "Parameter"; + node: ESTree.FunctionDeclaration | ESTree.FunctionExpression | ESTree.ArrowFunctionExpression; + parent: null; + } + | { type: "TDZ"; node: any; parent: null } + | { type: "Variable"; node: ESTree.VariableDeclarator; parent: ESTree.VariableDeclaration }; + + type Definition = DefinitionType & { name: ESTree.Identifier }; +} + +//#region SourceCode + +export class SourceCode { + text: string; + ast: AST.Program; + lines: string[]; + hasBOM: boolean; + parserServices: SourceCode.ParserServices; + scopeManager: Scope.ScopeManager; + visitorKeys: SourceCode.VisitorKeys; + + constructor(text: string, ast: AST.Program); + constructor(config: SourceCode.Config); + + static splitLines(text: string): string[]; + + getText(node?: ESTree.Node, beforeCount?: number, afterCount?: number): string; + + getLines(): string[]; + + getAllComments(): ESTree.Comment[]; + + getComments(node: ESTree.Node): { leading: ESTree.Comment[]; trailing: ESTree.Comment[] }; + + getJSDocComment(node: ESTree.Node): ESTree.Comment | null; + + getNodeByRangeIndex(index: number): ESTree.Node | null; + + isSpaceBetweenTokens(first: AST.Token, second: AST.Token): boolean; + + getLocFromIndex(index: number): ESTree.Position; + + getIndexFromLoc(location: ESTree.Position): number; + + // Inherited methods from TokenStore + // --------------------------------- + + getTokenByRangeStart(offset: number, options?: { includeComments: false }): AST.Token | null; + getTokenByRangeStart(offset: number, options: { includeComments: boolean }): AST.Token | ESTree.Comment | null; + + getFirstToken: SourceCode.UnaryNodeCursorWithSkipOptions; + + getFirstTokens: SourceCode.UnaryNodeCursorWithCountOptions; + + getLastToken: SourceCode.UnaryNodeCursorWithSkipOptions; + + getLastTokens: SourceCode.UnaryNodeCursorWithCountOptions; + + getTokenBefore: SourceCode.UnaryCursorWithSkipOptions; + + getTokensBefore: SourceCode.UnaryCursorWithCountOptions; + + getTokenAfter: SourceCode.UnaryCursorWithSkipOptions; + + getTokensAfter: SourceCode.UnaryCursorWithCountOptions; + + getFirstTokenBetween: SourceCode.BinaryCursorWithSkipOptions; + + getFirstTokensBetween: SourceCode.BinaryCursorWithCountOptions; + + getLastTokenBetween: SourceCode.BinaryCursorWithSkipOptions; + + getLastTokensBetween: SourceCode.BinaryCursorWithCountOptions; + + getTokensBetween: SourceCode.BinaryCursorWithCountOptions; + + getTokens: ((node: ESTree.Node, beforeCount?: number, afterCount?: number) => AST.Token[]) & + SourceCode.UnaryNodeCursorWithCountOptions; + + commentsExistBetween( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + ): boolean; + + getCommentsBefore(nodeOrToken: ESTree.Node | AST.Token): ESTree.Comment[]; + + getCommentsAfter(nodeOrToken: ESTree.Node | AST.Token): ESTree.Comment[]; + + getCommentsInside(node: ESTree.Node): ESTree.Comment[]; +} + +export namespace SourceCode { + interface Config { + text: string; + ast: AST.Program; + parserServices?: ParserServices | undefined; + scopeManager?: Scope.ScopeManager | undefined; + visitorKeys?: VisitorKeys | undefined; + } + + type ParserServices = any; + + interface VisitorKeys { + [nodeType: string]: string[]; + } + + interface UnaryNodeCursorWithSkipOptions { + ( + node: ESTree.Node, + options: + | ((token: AST.Token) => token is T) + | { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; skip?: number | undefined }, + ): T | null; + ( + node: ESTree.Node, + options: { + filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T; + includeComments: boolean; + skip?: number | undefined; + }, + ): T | null; + ( + node: ESTree.Node, + options?: + | { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; skip?: number | undefined } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token | null; + ( + node: ESTree.Node, + options: { + filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined; + includeComments: boolean; + skip?: number | undefined; + }, + ): AST.Token | ESTree.Comment | null; + } + + interface UnaryNodeCursorWithCountOptions { + ( + node: ESTree.Node, + options: + | ((token: AST.Token) => token is T) + | { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; count?: number | undefined }, + ): T[]; + ( + node: ESTree.Node, + options: { + filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T; + includeComments: boolean; + count?: number | undefined; + }, + ): T[]; + ( + node: ESTree.Node, + options?: + | { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; count?: number | undefined } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token[]; + ( + node: ESTree.Node, + options: { + filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined; + includeComments: boolean; + count?: number | undefined; + }, + ): Array; + } + + interface UnaryCursorWithSkipOptions { + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; skip?: number | undefined }, + ): T | null; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T; + includeComments: boolean; + skip?: number | undefined; + }, + ): T | null; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; skip?: number | undefined } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token | null; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined; + includeComments: boolean; + skip?: number | undefined; + }, + ): AST.Token | ESTree.Comment | null; + } + + interface UnaryCursorWithCountOptions { + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; count?: number | undefined }, + ): T[]; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T; + includeComments: boolean; + count?: number | undefined; + }, + ): T[]; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; count?: number | undefined } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token[]; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined; + includeComments: boolean; + count?: number | undefined; + }, + ): Array; + } + + interface BinaryCursorWithSkipOptions { + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; skip?: number | undefined }, + ): T | null; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T; + includeComments: boolean; + skip?: number | undefined; + }, + ): T | null; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; skip?: number | undefined } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token | null; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined; + includeComments: boolean; + skip?: number | undefined; + }, + ): AST.Token | ESTree.Comment | null; + } + + interface BinaryCursorWithCountOptions { + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; count?: number | undefined }, + ): T[]; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T; + includeComments: boolean; + count?: number | undefined; + }, + ): T[]; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; count?: number | undefined } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token[]; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined; + includeComments: boolean; + count?: number | undefined; + }, + ): Array; + } +} + +//#endregion + +export namespace Rule { + interface RuleModule { + create(context: RuleContext): RuleListener; + meta?: RuleMetaData | undefined; + } + + type NodeTypes = ESTree.Node["type"]; + interface NodeListener { + ArrayExpression?: ((node: ESTree.ArrayExpression & NodeParentExtension) => void) | undefined; + ArrayPattern?: ((node: ESTree.ArrayPattern & NodeParentExtension) => void) | undefined; + ArrowFunctionExpression?: ((node: ESTree.ArrowFunctionExpression & NodeParentExtension) => void) | undefined; + AssignmentExpression?: ((node: ESTree.AssignmentExpression & NodeParentExtension) => void) | undefined; + AssignmentPattern?: ((node: ESTree.AssignmentPattern & NodeParentExtension) => void) | undefined; + AwaitExpression?: ((node: ESTree.AwaitExpression & NodeParentExtension) => void) | undefined; + BinaryExpression?: ((node: ESTree.BinaryExpression & NodeParentExtension) => void) | undefined; + BlockStatement?: ((node: ESTree.BlockStatement & NodeParentExtension) => void) | undefined; + BreakStatement?: ((node: ESTree.BreakStatement & NodeParentExtension) => void) | undefined; + CallExpression?: ((node: ESTree.CallExpression & NodeParentExtension) => void) | undefined; + CatchClause?: ((node: ESTree.CatchClause & NodeParentExtension) => void) | undefined; + ChainExpression?: ((node: ESTree.ChainExpression & NodeParentExtension) => void) | undefined; + ClassBody?: ((node: ESTree.ClassBody & NodeParentExtension) => void) | undefined; + ClassDeclaration?: ((node: ESTree.ClassDeclaration & NodeParentExtension) => void) | undefined; + ClassExpression?: ((node: ESTree.ClassExpression & NodeParentExtension) => void) | undefined; + ConditionalExpression?: ((node: ESTree.ConditionalExpression & NodeParentExtension) => void) | undefined; + ContinueStatement?: ((node: ESTree.ContinueStatement & NodeParentExtension) => void) | undefined; + DebuggerStatement?: ((node: ESTree.DebuggerStatement & NodeParentExtension) => void) | undefined; + DoWhileStatement?: ((node: ESTree.DoWhileStatement & NodeParentExtension) => void) | undefined; + EmptyStatement?: ((node: ESTree.EmptyStatement & NodeParentExtension) => void) | undefined; + ExportAllDeclaration?: ((node: ESTree.ExportAllDeclaration & NodeParentExtension) => void) | undefined; + ExportDefaultDeclaration?: ((node: ESTree.ExportDefaultDeclaration & NodeParentExtension) => void) | undefined; + ExportNamedDeclaration?: ((node: ESTree.ExportNamedDeclaration & NodeParentExtension) => void) | undefined; + ExportSpecifier?: ((node: ESTree.ExportSpecifier & NodeParentExtension) => void) | undefined; + ExpressionStatement?: ((node: ESTree.ExpressionStatement & NodeParentExtension) => void) | undefined; + ForInStatement?: ((node: ESTree.ForInStatement & NodeParentExtension) => void) | undefined; + ForOfStatement?: ((node: ESTree.ForOfStatement & NodeParentExtension) => void) | undefined; + ForStatement?: ((node: ESTree.ForStatement & NodeParentExtension) => void) | undefined; + FunctionDeclaration?: ((node: ESTree.FunctionDeclaration & NodeParentExtension) => void) | undefined; + FunctionExpression?: ((node: ESTree.FunctionExpression & NodeParentExtension) => void) | undefined; + Identifier?: ((node: ESTree.Identifier & NodeParentExtension) => void) | undefined; + IfStatement?: ((node: ESTree.IfStatement & NodeParentExtension) => void) | undefined; + ImportDeclaration?: ((node: ESTree.ImportDeclaration & NodeParentExtension) => void) | undefined; + ImportDefaultSpecifier?: ((node: ESTree.ImportDefaultSpecifier & NodeParentExtension) => void) | undefined; + ImportExpression?: ((node: ESTree.ImportExpression & NodeParentExtension) => void) | undefined; + ImportNamespaceSpecifier?: ((node: ESTree.ImportNamespaceSpecifier & NodeParentExtension) => void) | undefined; + ImportSpecifier?: ((node: ESTree.ImportSpecifier & NodeParentExtension) => void) | undefined; + LabeledStatement?: ((node: ESTree.LabeledStatement & NodeParentExtension) => void) | undefined; + Literal?: ((node: ESTree.Literal & NodeParentExtension) => void) | undefined; + LogicalExpression?: ((node: ESTree.LogicalExpression & NodeParentExtension) => void) | undefined; + MemberExpression?: ((node: ESTree.MemberExpression & NodeParentExtension) => void) | undefined; + MetaProperty?: ((node: ESTree.MetaProperty & NodeParentExtension) => void) | undefined; + MethodDefinition?: ((node: ESTree.MethodDefinition & NodeParentExtension) => void) | undefined; + NewExpression?: ((node: ESTree.NewExpression & NodeParentExtension) => void) | undefined; + ObjectExpression?: ((node: ESTree.ObjectExpression & NodeParentExtension) => void) | undefined; + ObjectPattern?: ((node: ESTree.ObjectPattern & NodeParentExtension) => void) | undefined; + Program?: ((node: ESTree.Program) => void) | undefined; + Property?: ((node: ESTree.Property & NodeParentExtension) => void) | undefined; + RestElement?: ((node: ESTree.RestElement & NodeParentExtension) => void) | undefined; + ReturnStatement?: ((node: ESTree.ReturnStatement & NodeParentExtension) => void) | undefined; + SequenceExpression?: ((node: ESTree.SequenceExpression & NodeParentExtension) => void) | undefined; + SpreadElement?: ((node: ESTree.SpreadElement & NodeParentExtension) => void) | undefined; + Super?: ((node: ESTree.Super & NodeParentExtension) => void) | undefined; + SwitchCase?: ((node: ESTree.SwitchCase & NodeParentExtension) => void) | undefined; + SwitchStatement?: ((node: ESTree.SwitchStatement & NodeParentExtension) => void) | undefined; + TaggedTemplateExpression?: ((node: ESTree.TaggedTemplateExpression & NodeParentExtension) => void) | undefined; + TemplateElement?: ((node: ESTree.TemplateElement & NodeParentExtension) => void) | undefined; + TemplateLiteral?: ((node: ESTree.TemplateLiteral & NodeParentExtension) => void) | undefined; + ThisExpression?: ((node: ESTree.ThisExpression & NodeParentExtension) => void) | undefined; + ThrowStatement?: ((node: ESTree.ThrowStatement & NodeParentExtension) => void) | undefined; + TryStatement?: ((node: ESTree.TryStatement & NodeParentExtension) => void) | undefined; + UnaryExpression?: ((node: ESTree.UnaryExpression & NodeParentExtension) => void) | undefined; + UpdateExpression?: ((node: ESTree.UpdateExpression & NodeParentExtension) => void) | undefined; + VariableDeclaration?: ((node: ESTree.VariableDeclaration & NodeParentExtension) => void) | undefined; + VariableDeclarator?: ((node: ESTree.VariableDeclarator & NodeParentExtension) => void) | undefined; + WhileStatement?: ((node: ESTree.WhileStatement & NodeParentExtension) => void) | undefined; + WithStatement?: ((node: ESTree.WithStatement & NodeParentExtension) => void) | undefined; + YieldExpression?: ((node: ESTree.YieldExpression & NodeParentExtension) => void) | undefined; + } + + interface NodeParentExtension { + parent: Node; + } + type Node = ESTree.Node & NodeParentExtension; + + interface RuleListener extends NodeListener { + onCodePathStart?(codePath: CodePath, node: Node): void; + + onCodePathEnd?(codePath: CodePath, node: Node): void; + + onCodePathSegmentStart?(segment: CodePathSegment, node: Node): void; + + onCodePathSegmentEnd?(segment: CodePathSegment, node: Node): void; + + onCodePathSegmentLoop?(fromSegment: CodePathSegment, toSegment: CodePathSegment, node: Node): void; + + [key: string]: + | ((codePath: CodePath, node: Node) => void) + | ((segment: CodePathSegment, node: Node) => void) + | ((fromSegment: CodePathSegment, toSegment: CodePathSegment, node: Node) => void) + | ((node: Node) => void) + | NodeListener[keyof NodeListener] + | undefined; + } + + interface CodePath { + id: string; + initialSegment: CodePathSegment; + finalSegments: CodePathSegment[]; + returnedSegments: CodePathSegment[]; + thrownSegments: CodePathSegment[]; + currentSegments: CodePathSegment[]; + upper: CodePath | null; + childCodePaths: CodePath[]; + } + + interface CodePathSegment { + id: string; + nextSegments: CodePathSegment[]; + prevSegments: CodePathSegment[]; + reachable: boolean; + } + + interface RuleMetaData { + docs?: { + /** provides the short description of the rule in the [rules index](https://eslint.org/docs/rules/) */ + description?: string | undefined; + /** specifies the heading under which the rule is listed in the [rules index](https://eslint.org/docs/rules/) */ + category?: string | undefined; + /** is whether the `"extends": "eslint:recommended"` property in a [configuration file](https://eslint.org/docs/user-guide/configuring#extending-configuration-files) enables the rule */ + recommended?: boolean | undefined; + /** specifies the URL at which the full documentation can be accessed */ + url?: string | undefined; + /** specifies whether rules can return suggestions (defaults to false if omitted) */ + suggestion?: boolean | undefined; + } | undefined; + messages?: { [messageId: string]: string } | undefined; + fixable?: "code" | "whitespace" | undefined; + schema?: JSONSchema4 | JSONSchema4[] | undefined; + deprecated?: boolean | undefined; + type?: "problem" | "suggestion" | "layout" | undefined; + /** specifies whether rules can return suggestions (defaults to false if omitted) */ + hasSuggestions?: boolean | undefined; + } + + interface RuleContext { + id: string; + options: any[]; + settings: { [name: string]: any }; + parserPath: string; + parserOptions: Linter.ParserOptions; + parserServices: SourceCode.ParserServices; + + getAncestors(): ESTree.Node[]; + + getDeclaredVariables(node: ESTree.Node): Scope.Variable[]; + + getFilename(): string; + + getPhysicalFilename(): string; + + getCwd(): string; + + getScope(): Scope.Scope; + + getSourceCode(): SourceCode; + + markVariableAsUsed(name: string): boolean; + + report(descriptor: ReportDescriptor): void; + } + + type ReportFixer = (fixer: RuleFixer) => null | Fix | IterableIterator | Fix[]; + + interface ReportDescriptorOptionsBase { + data?: { [key: string]: string }; + + fix?: null | ReportFixer; + } + + interface SuggestionReportOptions { + data?: { [key: string]: string }; + + fix: ReportFixer; + } + + type SuggestionDescriptorMessage = { desc: string } | { messageId: string }; + type SuggestionReportDescriptor = SuggestionDescriptorMessage & SuggestionReportOptions; + + interface ReportDescriptorOptions extends ReportDescriptorOptionsBase { + suggest?: SuggestionReportDescriptor[] | null | undefined; + } + + type ReportDescriptor = ReportDescriptorMessage & ReportDescriptorLocation & ReportDescriptorOptions; + type ReportDescriptorMessage = { message: string } | { messageId: string }; + type ReportDescriptorLocation = + | { node: ESTree.Node } + | { loc: AST.SourceLocation | { line: number; column: number } }; + + interface RuleFixer { + insertTextAfter(nodeOrToken: ESTree.Node | AST.Token, text: string): Fix; + + insertTextAfterRange(range: AST.Range, text: string): Fix; + + insertTextBefore(nodeOrToken: ESTree.Node | AST.Token, text: string): Fix; + + insertTextBeforeRange(range: AST.Range, text: string): Fix; + + remove(nodeOrToken: ESTree.Node | AST.Token): Fix; + + removeRange(range: AST.Range): Fix; + + replaceText(nodeOrToken: ESTree.Node | AST.Token, text: string): Fix; + + replaceTextRange(range: AST.Range, text: string): Fix; + } + + interface Fix { + range: AST.Range; + text: string; + } +} + +//#region Linter + +export class Linter { + static version: string; + + version: string; + + constructor(options?: { cwd?: string | undefined }); + + verify(code: SourceCode | string, config: Linter.Config, filename?: string): Linter.LintMessage[]; + verify(code: SourceCode | string, config: Linter.Config, options: Linter.LintOptions): Linter.LintMessage[]; + + verifyAndFix(code: string, config: Linter.Config, filename?: string): Linter.FixReport; + verifyAndFix(code: string, config: Linter.Config, options: Linter.FixOptions): Linter.FixReport; + + getSourceCode(): SourceCode; + + defineRule(name: string, rule: Rule.RuleModule): void; + + defineRules(rules: { [name: string]: Rule.RuleModule }): void; + + getRules(): Map; + + defineParser(name: string, parser: Linter.ParserModule): void; +} + +export namespace Linter { + type Severity = 0 | 1 | 2; + + type RuleLevel = Severity | "off" | "warn" | "error"; + type RuleLevelAndOptions = Prepend, RuleLevel>; + + type RuleEntry = RuleLevel | RuleLevelAndOptions; + + interface RulesRecord { + [rule: string]: RuleEntry; + } + + interface HasRules { + rules?: Partial | undefined; + } + + interface BaseConfig extends HasRules { + $schema?: string | undefined; + env?: { [name: string]: boolean } | undefined; + extends?: string | string[] | undefined; + globals?: { [name: string]: boolean | "readonly" | "readable" | "writable" | "writeable" } | undefined; + noInlineConfig?: boolean | undefined; + overrides?: ConfigOverride[] | undefined; + parser?: string | undefined; + parserOptions?: ParserOptions | undefined; + plugins?: string[] | undefined; + processor?: string | undefined; + reportUnusedDisableDirectives?: boolean | undefined; + settings?: { [name: string]: any } | undefined; + } + + interface ConfigOverride extends BaseConfig { + excludedFiles?: string | string[] | undefined; + files: string | string[]; + } + + // https://github.com/eslint/eslint/blob/v6.8.0/conf/config-schema.js + interface Config extends BaseConfig { + ignorePatterns?: string | string[] | undefined; + root?: boolean | undefined; + } + + interface ParserOptions { + ecmaVersion?: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | "latest" | undefined; + sourceType?: "script" | "module" | undefined; + ecmaFeatures?: { + globalReturn?: boolean | undefined; + impliedStrict?: boolean | undefined; + jsx?: boolean | undefined; + experimentalObjectRestSpread?: boolean | undefined; + [key: string]: any; + } | undefined; + [key: string]: any; + } + + interface LintOptions { + filename?: string | undefined; + preprocess?: ((code: string) => string[]) | undefined; + postprocess?: ((problemLists: LintMessage[][]) => LintMessage[]) | undefined; + filterCodeBlock?: boolean | undefined; + disableFixes?: boolean | undefined; + allowInlineConfig?: boolean | undefined; + reportUnusedDisableDirectives?: boolean | undefined; + } + + interface LintSuggestion { + desc: string; + fix: Rule.Fix; + messageId?: string | undefined; + } + + interface LintMessage { + column: number; + line: number; + endColumn?: number | undefined; + endLine?: number | undefined; + ruleId: string | null; + message: string; + messageId?: string | undefined; + nodeType?: string | undefined; + fatal?: true | undefined; + severity: Severity; + fix?: Rule.Fix | undefined; + /** @deprecated Use `linter.getSourceCode()` */ + source?: string | null | undefined; + suggestions?: LintSuggestion[] | undefined; + } + + interface FixOptions extends LintOptions { + fix?: boolean | undefined; + } + + interface FixReport { + fixed: boolean; + output: string; + messages: LintMessage[]; + } + + type ParserModule = + | { + parse(text: string, options?: any): AST.Program; + } + | { + parseForESLint(text: string, options?: any): ESLintParseResult; + }; + + interface ESLintParseResult { + ast: AST.Program; + parserServices?: SourceCode.ParserServices | undefined; + scopeManager?: Scope.ScopeManager | undefined; + visitorKeys?: SourceCode.VisitorKeys | undefined; + } + + interface ProcessorFile { + text: string; + filename: string; + } + + // https://eslint.org/docs/developer-guide/working-with-plugins#processors-in-plugins + interface Processor { + supportsAutofix?: boolean | undefined; + preprocess?(text: string, filename: string): T[]; + postprocess?(messages: LintMessage[][], filename: string): LintMessage[]; + } +} + +//#endregion + +//#region ESLint + +export class ESLint { + static version: string; + + static outputFixes(results: ESLint.LintResult[]): Promise; + + static getErrorResults(results: ESLint.LintResult[]): ESLint.LintResult[]; + + constructor(options?: ESLint.Options); + + lintFiles(patterns: string | string[]): Promise; + + lintText(code: string, options?: { filePath?: string | undefined; warnIgnored?: boolean | undefined }): Promise; + + getRulesMetaForResults(results: ESLint.LintResult[]): ESLint.LintResultData['rulesMeta']; + + calculateConfigForFile(filePath: string): Promise; + + isPathIgnored(filePath: string): Promise; + + loadFormatter(nameOrPath?: string): Promise; +} + +export namespace ESLint { + interface Options { + // File enumeration + cwd?: string | undefined; + errorOnUnmatchedPattern?: boolean | undefined; + extensions?: string[] | undefined; + globInputPaths?: boolean | undefined; + ignore?: boolean | undefined; + ignorePath?: string | undefined; + + // Linting + allowInlineConfig?: boolean | undefined; + baseConfig?: Linter.Config | undefined; + overrideConfig?: Linter.Config | undefined; + overrideConfigFile?: string | undefined; + plugins?: Record | undefined; + reportUnusedDisableDirectives?: Linter.RuleLevel | undefined; + resolvePluginsRelativeTo?: string | undefined; + rulePaths?: string[] | undefined; + useEslintrc?: boolean | undefined; + + // Autofix + fix?: boolean | ((message: Linter.LintMessage) => boolean) | undefined; + fixTypes?: Array | undefined; + + // Cache-related + cache?: boolean | undefined; + cacheLocation?: string | undefined; + cacheStrategy?: "content" | "metadata" | undefined; + } + + interface LintResult { + filePath: string; + messages: Linter.LintMessage[]; + errorCount: number; + fatalErrorCount: number; + warningCount: number; + fixableErrorCount: number; + fixableWarningCount: number; + output?: string | undefined; + source?: string | undefined; + usedDeprecatedRules: DeprecatedRuleUse[]; + } + + interface LintResultData { + cwd: string; + rulesMeta: { + [ruleId: string]: Rule.RuleMetaData; + }; + } + + interface DeprecatedRuleUse { + ruleId: string; + replacedBy: string[]; + } + + interface Formatter { + format(results: LintResult[], data?: LintResultData): string | Promise; + } + + // Docs reference the type by this name + type EditInfo = Rule.Fix; +} + +//#endregion + +//#region RuleTester + +export class RuleTester { + constructor(config?: any); + + run( + name: string, + rule: Rule.RuleModule, + tests: { + valid?: Array | undefined; + invalid?: RuleTester.InvalidTestCase[] | undefined; + }, + ): void; + + static only( + item: string | RuleTester.ValidTestCase | RuleTester.InvalidTestCase, + ): RuleTester.ValidTestCase | RuleTester.InvalidTestCase; +} + +export namespace RuleTester { + interface ValidTestCase { + name?: string; + code: string; + options?: any; + filename?: string | undefined; + only?: boolean; + parserOptions?: Linter.ParserOptions | undefined; + settings?: { [name: string]: any } | undefined; + parser?: string | undefined; + globals?: { [name: string]: boolean } | undefined; + } + + interface SuggestionOutput { + messageId?: string | undefined; + desc?: string | undefined; + data?: Record | undefined; + output: string; + } + + interface InvalidTestCase extends ValidTestCase { + errors: number | Array; + output?: string | null | undefined; + } + + interface TestCaseError { + message?: string | RegExp | undefined; + messageId?: string | undefined; + type?: string | undefined; + data?: any; + line?: number | undefined; + column?: number | undefined; + endLine?: number | undefined; + endColumn?: number | undefined; + suggestions?: SuggestionOutput[] | undefined; + } +} + +//#endregion diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/package.json b/node_modules/mathjs/examples/node_modules/@types/eslint/package.json new file mode 100644 index 0000000..71fdf84 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/package.json @@ -0,0 +1,65 @@ +{ + "name": "@types/eslint", + "version": "8.4.1", + "description": "TypeScript definitions for eslint", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/eslint", + "license": "MIT", + "contributors": [ + { + "name": "Pierre-Marie Dartus", + "url": "https://github.com/pmdartus", + "githubUsername": "pmdartus" + }, + { + "name": "Jed Fox", + "url": "https://github.com/j-f1", + "githubUsername": "j-f1" + }, + { + "name": "Saad Quadri", + "url": "https://github.com/saadq", + "githubUsername": "saadq" + }, + { + "name": "Jason Kwok", + "url": "https://github.com/JasonHK", + "githubUsername": "JasonHK" + }, + { + "name": "Brad Zacher", + "url": "https://github.com/bradzacher", + "githubUsername": "bradzacher" + }, + { + "name": "JounQin", + "url": "https://github.com/JounQin", + "githubUsername": "JounQin" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/eslint" + }, + "scripts": {}, + "dependencies": { + "@types/estree": "*", + "@types/json-schema": "*" + }, + "typesPublisherContentHash": "90cb9cf20ae7859ce7f641c07d2d274a142d14ed7b4824a89b6abc48c961d03f", + "typeScriptVersion": "3.8", + "exports": { + ".": { + "types": "./index.d.ts" + }, + "./use-at-your-own-risk": { + "types": "./use-at-your-own-risk.d.ts" + }, + "./rules": { + "types": "./rules/index.d.ts" + }, + "./package.json": "./package.json" + } +} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/rules/best-practices.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/best-practices.d.ts new file mode 100644 index 0000000..68be5d9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/best-practices.d.ts @@ -0,0 +1,931 @@ +import { Linter } from "../index"; + +export interface BestPractices extends Linter.RulesRecord { + /** + * Rule to enforce getter and setter pairs in objects. + * + * @since 0.22.0 + * @see https://eslint.org/docs/rules/accessor-pairs + */ + "accessor-pairs": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + setWithoutGet: boolean; + /** + * @default false + */ + getWithoutSet: boolean; + }>, + ] + >; + + /** + * Rule to enforce `return` statements in callbacks of array methods. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/rules/array-callback-return + */ + "array-callback-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowImplicit: boolean; + }>, + ] + >; + + /** + * Rule to enforce the use of variables within the scope they are defined. + * + * @since 0.1.0 + * @see https://eslint.org/docs/rules/block-scoped-var + */ + "block-scoped-var": Linter.RuleEntry<[]>; + + /** + * Rule to enforce that class methods utilize `this`. + * + * @since 3.4.0 + * @see https://eslint.org/docs/rules/class-methods-use-this + */ + "class-methods-use-this": Linter.RuleEntry< + [ + Partial<{ + exceptMethods: string[]; + }>, + ] + >; + + /** + * Rule to enforce a maximum cyclomatic complexity allowed in a program. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/complexity + */ + complexity: Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 20 + */ + max: number; + /** + * @deprecated + * @default 20 + */ + maximum: number; + }> + | number, + ] + >; + + /** + * Rule to require `return` statements to either always or never specify values. + * + * @since 0.4.0 + * @see https://eslint.org/docs/rules/consistent-return + */ + "consistent-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + treatUndefinedAsUnspecified: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent brace style for all control statements. + * + * @since 0.0.2 + * @see https://eslint.org/docs/rules/curly + */ + curly: Linter.RuleEntry<["all" | "multi" | "multi-line" | "multi-or-nest" | "consistent"]>; + + /** + * Rule to require `default` cases in `switch` statements. + * + * @since 0.6.0 + * @see https://eslint.org/docs/rules/default-case + */ + "default-case": Linter.RuleEntry< + [ + Partial<{ + /** + * @default '^no default$' + */ + commentPattern: string; + }>, + ] + >; + + /** + * Rule to enforce consistent newlines before and after dots. + * + * @since 0.21.0 + * @see https://eslint.org/docs/rules/dot-location + */ + "dot-location": Linter.RuleEntry<["object" | "property"]>; + + /** + * Rule to enforce dot notation whenever possible. + * + * @since 0.0.7 + * @see https://eslint.org/docs/rules/dot-notation + */ + "dot-notation": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + allowKeywords: boolean; + allowPattern: string; + }>, + ] + >; + + /** + * Rule to require the use of `===` and `!==`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/rules/eqeqeq + */ + eqeqeq: + | Linter.RuleEntry< + [ + "always", + Partial<{ + /** + * @default 'always' + */ + null: "always" | "never" | "ignore"; + }>, + ] + > + | Linter.RuleEntry<["smart" | "allow-null"]>; + + /** + * Rule to require `for-in` loops to include an `if` statement. + * + * @since 0.0.6 + * @see https://eslint.org/docs/rules/guard-for-in + */ + "guard-for-in": Linter.RuleEntry<[]>; + + /** + * Rule to enforce a maximum number of classes per file. + * + * @since 5.0.0-alpha.3 + * @see https://eslint.org/docs/rules/max-classes-per-file + */ + "max-classes-per-file": Linter.RuleEntry<[number]>; + + /** + * Rule to disallow the use of `alert`, `confirm`, and `prompt`. + * + * @since 0.0.5 + * @see https://eslint.org/docs/rules/no-alert + */ + "no-alert": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `arguments.caller` or `arguments.callee`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/rules/no-caller + */ + "no-caller": Linter.RuleEntry<[]>; + + /** + * Rule to disallow lexical declarations in case clauses. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.9.0 + * @see https://eslint.org/docs/rules/no-case-declarations + */ + "no-case-declarations": Linter.RuleEntry<[]>; + + /** + * Rule to disallow division operators explicitly at the beginning of regular expressions. + * + * @since 0.1.0 + * @see https://eslint.org/docs/rules/no-div-regex + */ + "no-div-regex": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `else` blocks after `return` statements in `if` statements. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-else-return + */ + "no-else-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + allowElseIf: boolean; + }>, + ] + >; + + /** + * Rule to disallow empty functions. + * + * @since 2.0.0 + * @see https://eslint.org/docs/rules/no-empty-function + */ + "no-empty-function": Linter.RuleEntry< + [ + Partial<{ + /** + * @default [] + */ + allow: Array< + | "functions" + | "arrowFunctions" + | "generatorFunctions" + | "methods" + | "generatorMethods" + | "getters" + | "setters" + | "constructors" + >; + }>, + ] + >; + + /** + * Rule to disallow empty destructuring patterns. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.7.0 + * @see https://eslint.org/docs/rules/no-empty-pattern + */ + "no-empty-pattern": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `null` comparisons without type-checking operators. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-eq-null + */ + "no-eq-null": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `eval()`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/rules/no-eval + */ + "no-eval": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowIndirect: boolean; + }>, + ] + >; + + /** + * Rule to disallow extending native types. + * + * @since 0.1.4 + * @see https://eslint.org/docs/rules/no-extend-native + */ + "no-extend-native": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to disallow unnecessary calls to `.bind()`. + * + * @since 0.8.0 + * @see https://eslint.org/docs/rules/no-extra-bind + */ + "no-extra-bind": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary labels. + * + * @since 2.0.0-rc.0 + * @see https://eslint.org/docs/rules/no-extra-label + */ + "no-extra-label": Linter.RuleEntry<[]>; + + /** + * Rule to disallow fallthrough of `case` statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.7 + * @see https://eslint.org/docs/rules/no-fallthrough + */ + "no-fallthrough": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'falls?\s?through' + */ + commentPattern: string; + }>, + ] + >; + + /** + * Rule to disallow leading or trailing decimal points in numeric literals. + * + * @since 0.0.6 + * @see https://eslint.org/docs/rules/no-floating-decimal + */ + "no-floating-decimal": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assignments to native objects or read-only global variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 3.3.0 + * @see https://eslint.org/docs/rules/no-global-assign + */ + "no-global-assign": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to disallow shorthand type conversions. + * + * @since 1.0.0-rc-2 + * @see https://eslint.org/docs/rules/no-implicit-coercion + */ + "no-implicit-coercion": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + boolean: boolean; + /** + * @default true + */ + number: boolean; + /** + * @default true + */ + string: boolean; + /** + * @default [] + */ + allow: Array<"~" | "!!" | "+" | "*">; + }>, + ] + >; + + /** + * Rule to disallow variable and `function` declarations in the global scope. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/rules/no-implicit-globals + */ + "no-implicit-globals": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `eval()`-like methods. + * + * @since 0.0.7 + * @see https://eslint.org/docs/rules/no-implied-eval + */ + "no-implied-eval": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `this` keywords outside of classes or class-like objects. + * + * @since 1.0.0-rc-2 + * @see https://eslint.org/docs/rules/no-invalid-this + */ + "no-invalid-this": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of the `__iterator__` property. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-iterator + */ + "no-iterator": Linter.RuleEntry<[]>; + + /** + * Rule to disallow labeled statements. + * + * @since 0.4.0 + * @see https://eslint.org/docs/rules/no-labels + */ + "no-labels": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowLoop: boolean; + /** + * @default false + */ + allowSwitch: boolean; + }>, + ] + >; + + /** + * Rule to disallow unnecessary nested blocks. + * + * @since 0.4.0 + * @see https://eslint.org/docs/rules/no-lone-blocks + */ + "no-lone-blocks": Linter.RuleEntry<[]>; + + /** + * Rule to disallow function declarations that contain unsafe references inside loop statements. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-loop-func + */ + "no-loop-func": Linter.RuleEntry<[]>; + + /** + * Rule to disallow magic numbers. + * + * @since 1.7.0 + * @see https://eslint.org/docs/rules/no-magic-numbers + */ + "no-magic-numbers": Linter.RuleEntry< + [ + Partial<{ + /** + * @default [] + */ + ignore: number[]; + /** + * @default false + */ + ignoreArrayIndexes: boolean; + /** + * @default false + */ + enforceConst: boolean; + /** + * @default false + */ + detectObjects: boolean; + }>, + ] + >; + + /** + * Rule to disallow multiple spaces. + * + * @since 0.9.0 + * @see https://eslint.org/docs/rules/no-multi-spaces + */ + "no-multi-spaces": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreEOLComments: boolean; + /** + * @default { Property: true } + */ + exceptions: Record; + }>, + ] + >; + + /** + * Rule to disallow multiline strings. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-multi-str + */ + "no-multi-str": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators outside of assignments or comparisons. + * + * @since 0.0.7 + * @see https://eslint.org/docs/rules/no-new + */ + "no-new": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with the `Function` object. + * + * @since 0.0.7 + * @see https://eslint.org/docs/rules/no-new-func + */ + "no-new-func": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with the `String`, `Number`, and `Boolean` objects. + * + * @since 0.0.6 + * @see https://eslint.org/docs/rules/no-new-wrappers + */ + "no-new-wrappers": Linter.RuleEntry<[]>; + + /** + * Rule to disallow octal literals. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/rules/no-octal + */ + "no-octal": Linter.RuleEntry<[]>; + + /** + * Rule to disallow octal escape sequences in string literals. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-octal-escape + */ + "no-octal-escape": Linter.RuleEntry<[]>; + + /** + * Rule to disallow reassigning `function` parameters. + * + * @since 0.18.0 + * @see https://eslint.org/docs/rules/no-param-reassign + */ + "no-param-reassign": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + props: boolean; + /** + * @default [] + */ + ignorePropertyModificationsFor: string[]; + }>, + ] + >; + + /** + * Rule to disallow the use of the `__proto__` property. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-proto + */ + "no-proto": Linter.RuleEntry<[]>; + + /** + * Rule to disallow variable redeclaration. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-redeclare + */ + "no-redeclare": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + builtinGlobals: boolean; + }>, + ] + >; + + /** + * Rule to disallow certain properties on certain objects. + * + * @since 3.5.0 + * @see https://eslint.org/docs/rules/no-restricted-properties + */ + "no-restricted-properties": Linter.RuleEntry< + [ + ...Array< + | { + object: string; + property?: string | undefined; + message?: string | undefined; + } + | { + property: string; + message?: string | undefined; + } + > + ] + >; + + /** + * Rule to disallow assignment operators in `return` statements. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-return-assign + */ + "no-return-assign": Linter.RuleEntry<["except-parens" | "always"]>; + + /** + * Rule to disallow unnecessary `return await`. + * + * @since 3.10.0 + * @see https://eslint.org/docs/rules/no-return-await + */ + "no-return-await": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `javascript:` urls. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-script-url + */ + "no-script-url": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assignments where both sides are exactly the same. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.0.0-rc.0 + * @see https://eslint.org/docs/rules/no-self-assign + */ + "no-self-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow comparisons where both sides are exactly the same. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-self-compare + */ + "no-self-compare": Linter.RuleEntry<[]>; + + /** + * Rule to disallow comma operators. + * + * @since 0.5.1 + * @see https://eslint.org/docs/rules/no-sequences + */ + "no-sequences": Linter.RuleEntry<[]>; + + /** + * Rule to disallow throwing literals as exceptions. + * + * @since 0.15.0 + * @see https://eslint.org/docs/rules/no-throw-literal + */ + "no-throw-literal": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unmodified loop conditions. + * + * @since 2.0.0-alpha-2 + * @see https://eslint.org/docs/rules/no-unmodified-loop-condition + */ + "no-unmodified-loop-condition": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unused expressions. + * + * @since 0.1.0 + * @see https://eslint.org/docs/rules/no-unused-expressions + */ + "no-unused-expressions": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowShortCircuit: boolean; + /** + * @default false + */ + allowTernary: boolean; + /** + * @default false + */ + allowTaggedTemplates: boolean; + }>, + ] + >; + + /** + * Rule to disallow unused labels. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.0.0-rc.0 + * @see https://eslint.org/docs/rules/no-unused-labels + */ + "no-unused-labels": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary calls to `.call()` and `.apply()`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/rules/no-useless-call + */ + "no-useless-call": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary `catch` clauses. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 5.11.0 + * @see https://eslint.org/docs/rules/no-useless-catch + */ + "no-useless-catch": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary concatenation of literals or template literals. + * + * @since 1.3.0 + * @see https://eslint.org/docs/rules/no-useless-concat + */ + "no-useless-concat": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary escape characters. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.5.0 + * @see https://eslint.org/docs/rules/no-useless-escape + */ + "no-useless-escape": Linter.RuleEntry<[]>; + + /** + * Rule to disallow redundant return statements. + * + * @since 3.9.0 + * @see https://eslint.org/docs/rules/no-useless-return + */ + "no-useless-return": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `void` operators. + * + * @since 0.8.0 + * @see https://eslint.org/docs/rules/no-void + */ + "no-void": Linter.RuleEntry<[]>; + + /** + * Rule to disallow specified warning terms in comments. + * + * @since 0.4.4 + * @see https://eslint.org/docs/rules/no-warning-comments + */ + "no-warning-comments": Linter.RuleEntry< + [ + { + /** + * @default ["todo", "fixme", "xxx"] + */ + terms: string[]; + /** + * @default 'start' + */ + location: "start" | "anywhere"; + }, + ] + >; + + /** + * Rule to disallow `with` statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/rules/no-with + */ + "no-with": Linter.RuleEntry<[]>; + + /** + * Rule to enforce using named capture group in regular expression. + * + * @since 5.15.0 + * @see https://eslint.org/docs/rules/prefer-named-capture-group + */ + "prefer-named-capture-group": Linter.RuleEntry<[]>; + + /** + * Rule to require using Error objects as Promise rejection reasons. + * + * @since 3.14.0 + * @see https://eslint.org/docs/rules/prefer-promise-reject-errors + */ + "prefer-promise-reject-errors": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowEmptyReject: boolean; + }>, + ] + >; + + /** + * Rule to enforce the consistent use of the radix argument when using `parseInt()`. + * + * @since 0.0.7 + * @see https://eslint.org/docs/rules/radix + */ + radix: Linter.RuleEntry<["always" | "as-needed"]>; + + /** + * Rule to disallow async functions which have no `await` expression. + * + * @since 3.11.0 + * @see https://eslint.org/docs/rules/require-await + */ + "require-await": Linter.RuleEntry<[]>; + + /** + * Rule to enforce the use of `u` flag on RegExp. + * + * @since 5.3.0 + * @see https://eslint.org/docs/rules/require-unicode-regexp + */ + "require-unicode-regexp": Linter.RuleEntry<[]>; + + /** + * Rule to require `var` declarations be placed at the top of their containing scope. + * + * @since 0.8.0 + * @see https://eslint.org/docs/rules/vars-on-top + */ + "vars-on-top": Linter.RuleEntry<[]>; + + /** + * Rule to require parentheses around immediate `function` invocations. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/wrap-iife + */ + "wrap-iife": Linter.RuleEntry< + [ + "outside" | "inside" | "any", + Partial<{ + /** + * @default false + */ + functionPrototypeMethods: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow “Yoda” conditions. + * + * @since 0.7.1 + * @see https://eslint.org/docs/rules/yoda + */ + yoda: + | Linter.RuleEntry< + [ + "never", + Partial<{ + exceptRange: boolean; + onlyEquality: boolean; + }>, + ] + > + | Linter.RuleEntry<["always"]>; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/rules/deprecated.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/deprecated.d.ts new file mode 100644 index 0000000..f18607c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/deprecated.d.ts @@ -0,0 +1,267 @@ +import { Linter } from "../index"; + +export interface Deprecated extends Linter.RulesRecord { + /** + * Rule to enforce consistent indentation. + * + * @since 4.0.0-alpha.0 + * @deprecated since 4.0.0, use [`indent`](https://eslint.org/docs/rules/indent) instead. + * @see https://eslint.org/docs/rules/indent-legacy + */ + "indent-legacy": Linter.RuleEntry< + [ + number | "tab", + Partial<{ + /** + * @default 0 + */ + SwitchCase: number; + /** + * @default 1 + */ + VariableDeclarator: + | Partial<{ + /** + * @default 1 + */ + var: number | "first"; + /** + * @default 1 + */ + let: number | "first"; + /** + * @default 1 + */ + const: number | "first"; + }> + | number + | "first"; + /** + * @default 1 + */ + outerIIFEBody: number; + /** + * @default 1 + */ + MemberExpression: number | "off"; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionDeclaration: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionExpression: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { arguments: 1 } + */ + CallExpression: Partial<{ + /** + * @default 1 + */ + arguments: number | "first" | "off"; + }>; + /** + * @default 1 + */ + ArrayExpression: number | "first" | "off"; + /** + * @default 1 + */ + ObjectExpression: number | "first" | "off"; + /** + * @default 1 + */ + ImportDeclaration: number | "first" | "off"; + /** + * @default false + */ + flatTernaryExpressions: boolean; + ignoredNodes: string[]; + /** + * @default false + */ + ignoreComments: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow newlines around directives. + * + * @since 3.5.0 + * @deprecated since 4.0.0, use [`padding-line-between-statements`](https://eslint.org/docs/rules/padding-line-between-statements) instead. + * @see https://eslint.org/docs/rules/lines-around-directive + */ + "lines-around-directive": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require or disallow an empty line after variable declarations. + * + * @since 0.18.0 + * @deprecated since 4.0.0, use [`padding-line-between-statements`](https://eslint.org/docs/rules/padding-line-between-statements) instead. + * @see https://eslint.org/docs/rules/newline-after-var + */ + "newline-after-var": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require an empty line before `return` statements. + * + * @since 2.3.0 + * @deprecated since 4.0.0, use [`padding-line-between-statements`](https://eslint.org/docs/rules/padding-line-between-statements) instead. + * @see https://eslint.org/docs/rules/newline-before-return + */ + "newline-before-return": Linter.RuleEntry<[]>; + + /** + * Rule to disallow shadowing of variables inside of `catch`. + * + * @since 0.0.9 + * @deprecated since 5.1.0, use [`no-shadow`](https://eslint.org/docs/rules/no-shadow) instead. + * @see https://eslint.org/docs/rules/no-catch-shadow + */ + "no-catch-shadow": Linter.RuleEntry<[]>; + + /** + * Rule to disallow reassignment of native objects. + * + * @since 0.0.9 + * @deprecated since 3.3.0, use [`no-global-assign`](https://eslint.org/docs/rules/no-global-assign) instead. + * @see https://eslint.org/docs/rules/no-native-reassign + */ + "no-native-reassign": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to disallow negating the left operand in `in` expressions. + * + * @since 0.1.2 + * @deprecated since 3.3.0, use [`no-unsafe-negation`](https://eslint.org/docs/rules/no-unsafe-negation) instead. + * @see https://eslint.org/docs/rules/no-negated-in-lhs + */ + "no-negated-in-lhs": Linter.RuleEntry<[]>; + + /** + * Rule to disallow spacing between function identifiers and their applications. + * + * @since 0.1.2 + * @deprecated since 3.3.0, use [`func-call-spacing`](https://eslint.org/docs/rules/func-call-spacing) instead. + * @see https://eslint.org/docs/rules/no-spaced-func + */ + "no-spaced-func": Linter.RuleEntry<[]>; + + /** + * Rule to suggest using `Reflect` methods where applicable. + * + * @since 1.0.0-rc-2 + * @deprecated since 3.9.0 + * @see https://eslint.org/docs/rules/prefer-reflect + */ + "prefer-reflect": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to require JSDoc comments. + * + * @since 1.4.0 + * @deprecated since 5.10.0 + * @see https://eslint.org/docs/rules/require-jsdoc + */ + "require-jsdoc": Linter.RuleEntry< + [ + Partial<{ + require: Partial<{ + /** + * @default true + */ + FunctionDeclaration: boolean; + /** + * @default false + */ + MethodDefinition: boolean; + /** + * @default false + */ + ClassDeclaration: boolean; + /** + * @default false + */ + ArrowFunctionExpression: boolean; + /** + * @default false + */ + FunctionExpression: boolean; + }>; + }>, + ] + >; + + /** + * Rule to enforce valid JSDoc comments. + * + * @since 0.4.0 + * @deprecated since 5.10.0 + * @see https://eslint.org/docs/rules/valid-jsdoc + */ + "valid-jsdoc": Linter.RuleEntry< + [ + Partial<{ + prefer: Record; + preferType: Record; + /** + * @default true + */ + requireReturn: boolean; + /** + * @default true + */ + requireReturnType: boolean; + /** + * @remarks + * Also accept for regular expression pattern + */ + matchDescription: string; + /** + * @default true + */ + requireParamDescription: boolean; + /** + * @default true + */ + requireReturnDescription: boolean; + /** + * @default true + */ + requireParamType: boolean; + }>, + ] + >; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/rules/ecmascript-6.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/ecmascript-6.d.ts new file mode 100644 index 0000000..966f359 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/ecmascript-6.d.ts @@ -0,0 +1,502 @@ +import { Linter } from "../index"; + +export interface ECMAScript6 extends Linter.RulesRecord { + /** + * Rule to require braces around arrow function bodies. + * + * @since 1.8.0 + * @see https://eslint.org/docs/rules/arrow-body-style + */ + "arrow-body-style": + | Linter.RuleEntry< + [ + "as-needed", + Partial<{ + /** + * @default false + */ + requireReturnForObjectLiteral: boolean; + }>, + ] + > + | Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require parentheses around arrow function arguments. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/rules/arrow-parens + */ + "arrow-parens": + | Linter.RuleEntry<["always"]> + | Linter.RuleEntry< + [ + "as-needed", + Partial<{ + /** + * @default false + */ + requireForBlockBody: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before and after the arrow in arrow functions. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/rules/arrow-spacing + */ + "arrow-spacing": Linter.RuleEntry<[]>; + + /** + * Rule to require `super()` calls in constructors. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.24.0 + * @see https://eslint.org/docs/rules/constructor-super + */ + "constructor-super": Linter.RuleEntry<[]>; + + /** + * Rule to enforce consistent spacing around `*` operators in generator functions. + * + * @since 0.17.0 + * @see https://eslint.org/docs/rules/generator-star-spacing + */ + "generator-star-spacing": Linter.RuleEntry< + [ + | Partial<{ + before: boolean; + after: boolean; + named: + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither"; + anonymous: + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither"; + method: + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither"; + }> + | "before" + | "after" + | "both" + | "neither", + ] + >; + + /** + * Rule to disallow reassigning class members. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/rules/no-class-assign + */ + "no-class-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow arrow functions where they could be confused with comparisons. + * + * @since 2.0.0-alpha-2 + * @see https://eslint.org/docs/rules/no-confusing-arrow + */ + "no-confusing-arrow": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + allowParens: boolean; + }>, + ] + >; + + /** + * Rule to disallow reassigning `const` variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/rules/no-const-assign + */ + "no-const-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate class members. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.2.0 + * @see https://eslint.org/docs/rules/no-dupe-class-members + */ + "no-dupe-class-members": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate module imports. + * + * @since 2.5.0 + * @see https://eslint.org/docs/rules/no-duplicate-import + */ + "no-duplicate-import": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + includeExports: boolean; + }>, + ] + >; + + /** + * Rule to disallow `new` operators with the `Symbol` object. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.0.0-beta.1 + * @see https://eslint.org/docs/rules/no-new-symbol + */ + "no-new-symbol": Linter.RuleEntry<[]>; + + /** + * Rule to disallow specified modules when loaded by `import`. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/rules/no-restricted-imports + */ + "no-restricted-imports": Linter.RuleEntry< + [ + ...Array< + | string + | { + name: string; + importNames?: string[] | undefined; + message?: string | undefined; + } + | Partial<{ + paths: Array< + | string + | { + name: string; + importNames?: string[] | undefined; + message?: string | undefined; + } + >; + patterns: string[]; + }> + > + ] + >; + + /** + * Rule to disallow `this`/`super` before calling `super()` in constructors. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.24.0 + * @see https://eslint.org/docs/rules/no-this-before-super + */ + "no-this-before-super": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary computed property keys in object literals. + * + * @since 2.9.0 + * @see https://eslint.org/docs/rules/no-useless-computed-key + */ + "no-useless-computed-key": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary constructors. + * + * @since 2.0.0-beta.1 + * @see https://eslint.org/docs/rules/no-useless-constructor + */ + "no-useless-constructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow renaming import, export, and destructured assignments to the same name. + * + * @since 2.11.0 + * @see https://eslint.org/docs/rules/no-useless-rename + */ + "no-useless-rename": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreImport: boolean; + /** + * @default false + */ + ignoreExport: boolean; + /** + * @default false + */ + ignoreDestructuring: boolean; + }>, + ] + >; + + /** + * Rule to require `let` or `const` instead of `var`. + * + * @since 0.12.0 + * @see https://eslint.org/docs/rules/no-var + */ + "no-var": Linter.RuleEntry<[]>; + + /** + * Rule to require or disallow method and property shorthand syntax for object literals. + * + * @since 0.20.0 + * @see https://eslint.org/docs/rules/object-shorthand + */ + "object-shorthand": + | Linter.RuleEntry< + [ + "always" | "methods", + Partial<{ + /** + * @default false + */ + avoidQuotes: boolean; + /** + * @default false + */ + ignoreConstructors: boolean; + /** + * @default false + */ + avoidExplicitReturnArrows: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "properties", + Partial<{ + /** + * @default false + */ + avoidQuotes: boolean; + }>, + ] + > + | Linter.RuleEntry<["never" | "consistent" | "consistent-as-needed"]>; + + /** + * Rule to require using arrow functions for callbacks. + * + * @since 1.2.0 + * @see https://eslint.org/docs/rules/prefer-arrow-callback + */ + "prefer-arrow-callback": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowNamedFunctions: boolean; + /** + * @default true + */ + allowUnboundThis: boolean; + }>, + ] + >; + + /** + * Rule to require `const` declarations for variables that are never reassigned after declared. + * + * @since 0.23.0 + * @see https://eslint.org/docs/rules/prefer-const + */ + "prefer-const": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'any' + */ + destructuring: "any" | "all"; + /** + * @default false + */ + ignoreReadBeforeAssign: boolean; + }>, + ] + >; + + /** + * Rule to require destructuring from arrays and/or objects. + * + * @since 3.13.0 + * @see https://eslint.org/docs/rules/prefer-destructuring + */ + "prefer-destructuring": Linter.RuleEntry< + [ + Partial< + | { + VariableDeclarator: Partial<{ + array: boolean; + object: boolean; + }>; + AssignmentExpression: Partial<{ + array: boolean; + object: boolean; + }>; + } + | { + array: boolean; + object: boolean; + } + >, + Partial<{ + enforceForRenamedProperties: boolean; + }>, + ] + >; + + /** + * Rule to disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals. + * + * @since 3.5.0 + * @see https://eslint.org/docs/rules/prefer-numeric-literals + */ + "prefer-numeric-literals": Linter.RuleEntry<[]>; + + /** + * Rule to require rest parameters instead of `arguments`. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/rules/prefer-rest-params + */ + "prefer-rest-params": Linter.RuleEntry<[]>; + + /** + * Rule to require spread operators instead of `.apply()`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/rules/prefer-spread + */ + "prefer-spread": Linter.RuleEntry<[]>; + + /** + * Rule to require template literals instead of string concatenation. + * + * @since 1.2.0 + * @see https://eslint.org/docs/rules/prefer-template + */ + "prefer-template": Linter.RuleEntry<[]>; + + /** + * Rule to require generator functions to contain `yield`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/rules/require-yield + */ + "require-yield": Linter.RuleEntry<[]>; + + /** + * Rule to enforce spacing between rest and spread operators and their expressions. + * + * @since 2.12.0 + * @see https://eslint.org/docs/rules/rest-spread-spacing + */ + "rest-spread-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to enforce sorted import declarations within modules. + * + * @since 2.0.0-beta.1 + * @see https://eslint.org/docs/rules/sort-imports + */ + "sort-imports": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreCase: boolean; + /** + * @default false + */ + ignoreDeclarationSort: boolean; + /** + * @default false + */ + ignoreMemberSort: boolean; + /** + * @default ['none', 'all', 'multiple', 'single'] + */ + memberSyntaxSortOrder: Array<"none" | "all" | "multiple" | "single">; + }>, + ] + >; + + /** + * Rule to require symbol descriptions. + * + * @since 3.4.0 + * @see https://eslint.org/docs/rules/symbol-description + */ + "symbol-description": Linter.RuleEntry<[]>; + + /** + * Rule to require or disallow spacing around embedded expressions of template strings. + * + * @since 2.0.0-rc.0 + * @see https://eslint.org/docs/rules/template-curly-spacing + */ + "template-curly-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require or disallow spacing around the `*` in `yield*` expressions. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/rules/yield-star-spacing + */ + "yield-star-spacing": Linter.RuleEntry< + [ + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither", + ] + >; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/rules/index.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/index.d.ts new file mode 100644 index 0000000..e0f517b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/index.d.ts @@ -0,0 +1,21 @@ +import { Linter } from "../index"; + +import { BestPractices } from "./best-practices"; +import { Deprecated } from "./deprecated"; +import { ECMAScript6 } from "./ecmascript-6"; +import { NodeJSAndCommonJS } from "./node-commonjs"; +import { PossibleErrors } from "./possible-errors"; +import { StrictMode } from "./strict-mode"; +import { StylisticIssues } from "./stylistic-issues"; +import { Variables } from "./variables"; + +export interface ESLintRules + extends Linter.RulesRecord, + PossibleErrors, + BestPractices, + StrictMode, + Variables, + NodeJSAndCommonJS, + StylisticIssues, + ECMAScript6, + Deprecated {} diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/rules/node-commonjs.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/node-commonjs.d.ts new file mode 100644 index 0000000..c248029 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/node-commonjs.d.ts @@ -0,0 +1,133 @@ +import { Linter } from "../index"; + +export interface NodeJSAndCommonJS extends Linter.RulesRecord { + /** + * Rule to require `return` statements after callbacks. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/rules/callback-return + */ + "callback-return": Linter.RuleEntry<[string[]]>; + + /** + * Rule to require `require()` calls to be placed at top-level module scope. + * + * @since 1.4.0 + * @see https://eslint.org/docs/rules/global-require + */ + "global-require": Linter.RuleEntry<[]>; + + /** + * Rule to require error handling in callbacks. + * + * @since 0.4.5 + * @see https://eslint.org/docs/rules/handle-callback-err + */ + "handle-callback-err": Linter.RuleEntry<[string]>; + + /** + * Rule to disallow use of the `Buffer()` constructor. + * + * @since 4.0.0-alpha.0 + * @see https://eslint.org/docs/rules/no-buffer-constructor + */ + "no-buffer-constructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `require` calls to be mixed with regular variable declarations. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-mixed-requires + */ + "no-mixed-requires": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + grouping: boolean; + /** + * @default false + */ + allowCall: boolean; + }>, + ] + >; + + /** + * Rule to disallow `new` operators with calls to `require`. + * + * @since 0.6.0 + * @see https://eslint.org/docs/rules/no-new-require + */ + "no-new-require": Linter.RuleEntry<[]>; + + /** + * Rule to disallow string concatenation when using `__dirname` and `__filename`. + * + * @since 0.4.0 + * @see https://eslint.org/docs/rules/no-path-concat + */ + "no-path-concat": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `process.env`. + * + * @since 0.9.0 + * @see https://eslint.org/docs/rules/no-process-env + */ + "no-process-env": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `process.exit()`. + * + * @since 0.4.0 + * @see https://eslint.org/docs/rules/no-process-exit + */ + "no-process-exit": Linter.RuleEntry<[]>; + + /** + * Rule to disallow specified modules when loaded by `require`. + * + * @since 0.6.0 + * @see https://eslint.org/docs/rules/no-restricted-modules + */ + "no-restricted-modules": Linter.RuleEntry< + [ + ...Array< + | string + | { + name: string; + message?: string | undefined; + } + | Partial<{ + paths: Array< + | string + | { + name: string; + message?: string | undefined; + } + >; + patterns: string[]; + }> + > + ] + >; + + /** + * Rule to disallow synchronous methods. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-sync + */ + "no-sync": Linter.RuleEntry< + [ + { + /** + * @default false + */ + allowAtRootLevel: boolean; + }, + ] + >; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/rules/possible-errors.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/possible-errors.d.ts new file mode 100644 index 0000000..c27a862 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/possible-errors.d.ts @@ -0,0 +1,484 @@ +import { Linter } from "../index"; + +export interface PossibleErrors extends Linter.RulesRecord { + /** + * Rule to enforce `for` loop update clause moving the counter in the right direction. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 4.0.0-beta.0 + * @see https://eslint.org/docs/rules/for-direction + */ + "for-direction": Linter.RuleEntry<[]>; + + /** + * Rule to enforce `return` statements in getters. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 4.2.0 + * @see https://eslint.org/docs/rules/getter-return + */ + "getter-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowImplicit: boolean; + }>, + ] + >; + + /** + * Rule to disallow using an async function as a `Promise` executor. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 5.3.0 + * @see https://eslint.org/docs/rules/no-async-promise-executor + */ + "no-async-promise-executor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `await` inside of loops. + * + * @since 3.12.0 + * @see https://eslint.org/docs/rules/no-await-in-loop + */ + "no-await-in-loop": Linter.RuleEntry<[]>; + + /** + * Rule to disallow comparing against `-0`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 3.17.0 + * @see https://eslint.org/docs/rules/no-compare-neg-zero + */ + "no-compare-neg-zero": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assignment operators in conditional statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-cond-assign + */ + "no-cond-assign": Linter.RuleEntry<["except-parens" | "always"]>; + + /** + * Rule to disallow the use of `console`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/rules/no-console + */ + "no-console": Linter.RuleEntry< + [ + Partial<{ + allow: Array; + }>, + ] + >; + + /** + * Rule to disallow constant expressions in conditions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.1 + * @see https://eslint.org/docs/rules/no-constant-condition + */ + "no-constant-condition": Linter.RuleEntry< + [ + { + /** + * @default true + */ + checkLoops: boolean; + }, + ] + >; + + /** + * Rule to disallow control characters in regular expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.1.0 + * @see https://eslint.org/docs/rules/no-control-regex + */ + "no-control-regex": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `debugger`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/rules/no-debugger + */ + "no-debugger": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate arguments in `function` definitions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.16.0 + * @see https://eslint.org/docs/rules/no-dupe-args + */ + "no-dupe-args": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate keys in object literals. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-dupe-keys + */ + "no-dupe-keys": Linter.RuleEntry<[]>; + + /** + * Rule to disallow a duplicate case label. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.17.0 + * @see https://eslint.org/docs/rules/no-duplicate-case + */ + "no-duplicate-case": Linter.RuleEntry<[]>; + + /** + * Rule to disallow empty block statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/rules/no-empty + */ + "no-empty": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowEmptyCatch: boolean; + }>, + ] + >; + + /** + * Rule to disallow empty character classes in regular expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.22.0 + * @see https://eslint.org/docs/rules/no-empty-character-class + */ + "no-empty-character-class": Linter.RuleEntry<[]>; + + /** + * Rule to disallow reassigning exceptions in `catch` clauses. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-ex-assign + */ + "no-ex-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary boolean casts. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.0 + * @see https://eslint.org/docs/rules/no-extra-boolean-cast + */ + "no-extra-boolean-cast": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary parentheses. + * + * @since 0.1.4 + * @see https://eslint.org/docs/rules/no-extra-parens + */ + "no-extra-parens": + | Linter.RuleEntry< + [ + "all", + Partial<{ + /** + * @default true, + */ + conditionalAssign: boolean; + /** + * @default true + */ + returnAssign: boolean; + /** + * @default true + */ + nestedBinaryExpressions: boolean; + /** + * @default 'none' + */ + ignoreJSX: "none" | "all" | "multi-line" | "single-line"; + /** + * @default true + */ + enforceForArrowConditionals: boolean; + }>, + ] + > + | Linter.RuleEntry<["functions"]>; + + /** + * Rule to disallow unnecessary semicolons. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-extra-semi + */ + "no-extra-semi": Linter.RuleEntry<[]>; + + /** + * Rule to disallow reassigning `function` declarations. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-func-assign + */ + "no-func-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow variable or `function` declarations in nested blocks. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.6.0 + * @see https://eslint.org/docs/rules/no-inner-declarations + */ + "no-inner-declarations": Linter.RuleEntry<["functions" | "both"]>; + + /** + * Rule to disallow invalid regular expression strings in `RegExp` constructors. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.1.4 + * @see https://eslint.org/docs/rules/no-invalid-regexp + */ + "no-invalid-regexp": Linter.RuleEntry< + [ + Partial<{ + allowConstructorFlags: string[]; + }>, + ] + >; + + /** + * Rule to disallow irregular whitespace. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.9.0 + * @see https://eslint.org/docs/rules/no-irregular-whitespace + */ + "no-irregular-whitespace": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + skipStrings: boolean; + /** + * @default false + */ + skipComments: boolean; + /** + * @default false + */ + skipRegExps: boolean; + /** + * @default false + */ + skipTemplates: boolean; + }>, + ] + >; + + /** + * Rule to disallow characters which are made with multiple code points in character class syntax. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 5.3.0 + * @see https://eslint.org/docs/rules/no-misleading-character-class + */ + "no-misleading-character-class": Linter.RuleEntry<[]>; + + /** + * Rule to disallow calling global object properties as functions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-obj-calls + */ + "no-obj-calls": Linter.RuleEntry<[]>; + + /** + * Rule to disallow use of `Object.prototypes` builtins directly. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.11.0 + * @see https://eslint.org/docs/rules/no-prototype-builtins + */ + "no-prototype-builtins": Linter.RuleEntry<[]>; + + /** + * Rule to disallow multiple spaces in regular expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.0 + * @see https://eslint.org/docs/rules/no-regex-spaces + */ + "no-regex-spaces": Linter.RuleEntry<[]>; + + /** + * Rule to disallow sparse arrays. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.0 + * @see https://eslint.org/docs/rules/no-sparse-arrays + */ + "no-sparse-arrays": Linter.RuleEntry<[]>; + + /** + * Rule to disallow template literal placeholder syntax in regular strings. + * + * @since 3.3.0 + * @see https://eslint.org/docs/rules/no-template-curly-in-string + */ + "no-template-curly-in-string": Linter.RuleEntry<[]>; + + /** + * Rule to disallow confusing multiline expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.24.0 + * @see https://eslint.org/docs/rules/no-unexpected-multiline + */ + "no-unexpected-multiline": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unreachable code after `return`, `throw`, `continue`, and `break` statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/rules/no-unreachable + */ + "no-unreachable": Linter.RuleEntry<[]>; + + /** + * Rule to disallow control flow statements in `finally` blocks. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.9.0 + * @see https://eslint.org/docs/rules/no-unsafe-finally + */ + "no-unsafe-finally": Linter.RuleEntry<[]>; + + /** + * Rule to disallow negating the left operand of relational operators. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 3.3.0 + * @see https://eslint.org/docs/rules/no-unsafe-negation + */ + "no-unsafe-negation": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assignments that can lead to race conditions due to usage of `await` or `yield`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 5.3.0 + * @see https://eslint.org/docs/rules/require-atomic-updates + */ + "require-atomic-updates": Linter.RuleEntry<[]>; + + /** + * Rule to require calls to `isNaN()` when checking for `NaN`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/rules/use-isnan + */ + "use-isnan": Linter.RuleEntry<[]>; + + /** + * Rule to enforce comparing `typeof` expressions against valid strings. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.5.0 + * @see https://eslint.org/docs/rules/valid-typeof + */ + "valid-typeof": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + requireStringLiterals: boolean; + }>, + ] + >; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/rules/strict-mode.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/strict-mode.d.ts new file mode 100644 index 0000000..d63929b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/strict-mode.d.ts @@ -0,0 +1,11 @@ +import { Linter } from "../index"; + +export interface StrictMode extends Linter.RulesRecord { + /** + * Rule to require or disallow strict mode directives. + * + * @since 0.1.0 + * @see https://eslint.org/docs/rules/strict + */ + strict: Linter.RuleEntry<["safe" | "global" | "function" | "never"]>; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/rules/stylistic-issues.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/stylistic-issues.d.ts new file mode 100644 index 0000000..af7e0c7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/stylistic-issues.d.ts @@ -0,0 +1,1893 @@ +import { Linter } from "../index"; + +export interface StylisticIssues extends Linter.RulesRecord { + /** + * Rule to enforce linebreaks after opening and before closing array brackets. + * + * @since 4.0.0-alpha.1 + * @see https://eslint.org/docs/rules/array-bracket-newline + */ + "array-bracket-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | "consistent" + | Partial<{ + /** + * @default true + */ + multiline: boolean; + /** + * @default null + */ + minItems: number | null; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing inside array brackets. + * + * @since 0.24.0 + * @see https://eslint.org/docs/rules/array-bracket-spacing + */ + "array-bracket-spacing": + | Linter.RuleEntry< + [ + "never", + Partial<{ + /** + * @default false + */ + singleValue: boolean; + /** + * @default false + */ + objectsInArrays: boolean; + /** + * @default false + */ + arraysInArrays: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "always", + Partial<{ + /** + * @default true + */ + singleValue: boolean; + /** + * @default true + */ + objectsInArrays: boolean; + /** + * @default true + */ + arraysInArrays: boolean; + }>, + ] + >; + + /** + * Rule to enforce line breaks after each array element. + * + * @since 4.0.0-rc.0 + * @see https://eslint.org/docs/rules/array-element-newline + */ + "array-element-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | "consistent" + | Partial<{ + /** + * @default true + */ + multiline: boolean; + /** + * @default null + */ + minItems: number | null; + }>, + ] + >; + + /** + * Rule to disallow or enforce spaces inside of blocks after opening block and before closing block. + * + * @since 1.2.0 + * @see https://eslint.org/docs/rules/block-spacing + */ + "block-spacing": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to enforce consistent brace style for blocks. + * + * @since 0.0.7 + * @see https://eslint.org/docs/rules/brace-style + */ + "brace-style": Linter.RuleEntry< + [ + "1tbs" | "stroustrup" | "allman", + Partial<{ + /** + * @default false + */ + allowSingleLine: boolean; + }>, + ] + >; + + /** + * Rule to enforce camelcase naming convention. + * + * @since 0.0.2 + * @see https://eslint.org/docs/rules/camelcase + */ + camelcase: Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'always' + */ + properties: "always" | "never"; + /** + * @default false + */ + ignoreDestructuring: boolean; + /** + * @remarks + * Also accept for regular expression patterns + */ + allow: string[]; + }>, + ] + >; + + /** + * Rule to enforce or disallow capitalization of the first letter of a comment. + * + * @since 3.11.0 + * @see https://eslint.org/docs/rules/capitalized-comments + */ + "capitalized-comments": Linter.RuleEntry< + [ + "always" | "never", + Partial<{ + ignorePattern: string; + /** + * @default false + */ + ignoreInlineComments: boolean; + /** + * @default false + */ + ignoreConsecutiveComments: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow trailing commas. + * + * @since 0.16.0 + * @see https://eslint.org/docs/rules/comma-dangle + */ + "comma-dangle": Linter.RuleEntry< + [ + | "never" + | "always" + | "always-multiline" + | "only-multiline" + | Partial<{ + /** + * @default 'never' + */ + arrays: "never" | "always" | "always-multiline" | "only-multiline"; + /** + * @default 'never' + */ + objects: "never" | "always" | "always-multiline" | "only-multiline"; + /** + * @default 'never' + */ + imports: "never" | "always" | "always-multiline" | "only-multiline"; + /** + * @default 'never' + */ + exports: "never" | "always" | "always-multiline" | "only-multiline"; + /** + * @default 'never' + */ + functions: "never" | "always" | "always-multiline" | "only-multiline"; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before and after commas. + * + * @since 0.9.0 + * @see https://eslint.org/docs/rules/comma-spacing + */ + "comma-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + before: boolean; + /** + * @default true + */ + after: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent comma style. + * + * @since 0.9.0 + * @see https://eslint.org/docs/rules/comma-style + */ + "comma-style": Linter.RuleEntry< + [ + "last" | "first", + Partial<{ + exceptions: Record; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing inside computed property brackets. + * + * @since 0.23.0 + * @see https://eslint.org/docs/rules/computed-property-spacing + */ + "computed-property-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to enforce consistent naming when capturing the current execution context. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/consistent-this + */ + "consistent-this": Linter.RuleEntry<[...string[]]>; + + /** + * Rule to require or disallow newline at the end of files. + * + * @since 0.7.1 + * @see https://eslint.org/docs/rules/eol-last + */ + "eol-last": Linter.RuleEntry< + [ + "always" | "never", // | 'unix' | 'windows' + ] + >; + + /** + * Rule to require or disallow spacing between function identifiers and their invocations. + * + * @since 3.3.0 + * @see https://eslint.org/docs/rules/func-call-spacing + */ + "func-call-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require function names to match the name of the variable or property to which they are assigned. + * + * @since 3.8.0 + * @see https://eslint.org/docs/rules/func-name-matching + */ + "func-name-matching": + | Linter.RuleEntry< + [ + "always" | "never", + Partial<{ + /** + * @default false + */ + considerPropertyDescriptor: boolean; + /** + * @default false + */ + includeCommonJSModuleExports: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + considerPropertyDescriptor: boolean; + /** + * @default false + */ + includeCommonJSModuleExports: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow named `function` expressions. + * + * @since 0.4.0 + * @see https://eslint.org/docs/rules/func-names + */ + "func-names": Linter.RuleEntry< + [ + "always" | "as-needed" | "never", + Partial<{ + generators: "always" | "as-needed" | "never"; + }>, + ] + >; + + /** + * Rule to enforce the consistent use of either `function` declarations or expressions. + * + * @since 0.2.0 + * @see https://eslint.org/docs/rules/func-style + */ + "func-style": Linter.RuleEntry< + [ + "expression" | "declaration", + Partial<{ + /** + * @default false + */ + allowArrowFunctions: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent line breaks inside function parentheses. + * + * @since 4.6.0 + * @see https://eslint.org/docs/rules/function-paren-newline + */ + "function-paren-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | "multiline" + | "multiline-arguments" + | "consistent" + | Partial<{ + minItems: number; + }>, + ] + >; + + /** + * Rule to disallow specified identifiers. + * + * @since 2.0.0-beta.2 + * @see https://eslint.org/docs/rules/id-blacklist + */ + "id-blacklist": Linter.RuleEntry<[...string[]]>; + + /** + * Rule to enforce minimum and maximum identifier lengths. + * + * @since 1.0.0 + * @see https://eslint.org/docs/rules/id-length + */ + "id-length": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 2 + */ + min: number; + /** + * @default Infinity + */ + max: number; + /** + * @default 'always' + */ + properties: "always" | "never"; + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to require identifiers to match a specified regular expression. + * + * @since 1.0.0 + * @see https://eslint.org/docs/rules/id-match + */ + "id-match": Linter.RuleEntry< + [ + string, + Partial<{ + /** + * @default false + */ + properties: boolean; + /** + * @default false + */ + onlyDeclarations: boolean; + /** + * @default false + */ + ignoreDestructuring: boolean; + }>, + ] + >; + + /** + * Rule to enforce the location of arrow function bodies. + * + * @since 4.12.0 + * @see https://eslint.org/docs/rules/implicit-arrow-linebreak + */ + "implicit-arrow-linebreak": Linter.RuleEntry<["beside" | "below"]>; + + /** + * Rule to enforce consistent indentation. + * + * @since 0.14.0 + * @see https://eslint.org/docs/rules/indent + */ + indent: Linter.RuleEntry< + [ + number | "tab", + Partial<{ + /** + * @default 0 + */ + SwitchCase: number; + /** + * @default 1 + */ + VariableDeclarator: + | Partial<{ + /** + * @default 1 + */ + var: number | "first"; + /** + * @default 1 + */ + let: number | "first"; + /** + * @default 1 + */ + const: number | "first"; + }> + | number + | "first"; + /** + * @default 1 + */ + outerIIFEBody: number; + /** + * @default 1 + */ + MemberExpression: number | "off"; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionDeclaration: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionExpression: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { arguments: 1 } + */ + CallExpression: Partial<{ + /** + * @default 1 + */ + arguments: number | "first" | "off"; + }>; + /** + * @default 1 + */ + ArrayExpression: number | "first" | "off"; + /** + * @default 1 + */ + ObjectExpression: number | "first" | "off"; + /** + * @default 1 + */ + ImportDeclaration: number | "first" | "off"; + /** + * @default false + */ + flatTernaryExpressions: boolean; + ignoredNodes: string[]; + /** + * @default false + */ + ignoreComments: boolean; + }>, + ] + >; + + /** + * Rule to enforce the consistent use of either double or single quotes in JSX attributes. + * + * @since 1.4.0 + * @see https://eslint.org/docs/rules/jsx-quotes + */ + "jsx-quotes": Linter.RuleEntry<["prefer-double" | "prefer-single"]>; + + /** + * Rule to enforce consistent spacing between keys and values in object literal properties. + * + * @since 0.9.0 + * @see https://eslint.org/docs/rules/key-spacing + */ + "key-spacing": Linter.RuleEntry< + [ + | Partial< + | { + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + align: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'colon' + */ + on: "value" | "colon"; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | "value" + | "colon"; + } + | { + singleLine?: Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> | undefined; + multiLine?: Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + align: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'colon' + */ + on: "value" | "colon"; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | "value" + | "colon"; + }> | undefined; + } + > + | { + align: Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'colon' + */ + on: "value" | "colon"; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }>; + singleLine?: Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> | undefined; + multiLine?: Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> | undefined; + }, + ] + >; + + /** + * Rule to enforce consistent spacing before and after keywords. + * + * @since 2.0.0-beta.1 + * @see https://eslint.org/docs/rules/keyword-spacing + */ + "keyword-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + before: boolean; + /** + * @default true + */ + after: boolean; + overrides: Record< + string, + Partial<{ + before: boolean; + after: boolean; + }> + >; + }>, + ] + >; + + /** + * Rule to enforce position of line comments. + * + * @since 3.5.0 + * @see https://eslint.org/docs/rules/line-comment-position + */ + "line-comment-position": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'above' + */ + position: "above" | "beside"; + ignorePattern: string; + /** + * @default true + */ + applyDefaultIgnorePatterns: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent linebreak style. + * + * @since 0.21.0 + * @see https://eslint.org/docs/rules/linebreak-style + */ + "linebreak-style": Linter.RuleEntry<["unix" | "windows"]>; + + /** + * Rule to require empty lines around comments. + * + * @since 0.22.0 + * @see https://eslint.org/docs/rules/lines-around-comment + */ + "lines-around-comment": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + beforeBlockComment: boolean; + /** + * @default false + */ + afterBlockComment: boolean; + /** + * @default false + */ + beforeLineComment: boolean; + /** + * @default false + */ + afterLineComment: boolean; + /** + * @default false + */ + allowBlockStart: boolean; + /** + * @default false + */ + allowBlockEnd: boolean; + /** + * @default false + */ + allowObjectStart: boolean; + /** + * @default false + */ + allowObjectEnd: boolean; + /** + * @default false + */ + allowArrayStart: boolean; + /** + * @default false + */ + allowArrayEnd: boolean; + /** + * @default false + */ + allowClassStart: boolean; + /** + * @default false + */ + allowClassEnd: boolean; + ignorePattern: string; + /** + * @default true + */ + applyDefaultIgnorePatterns: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow an empty line between class members. + * + * @since 4.9.0 + * @see https://eslint.org/docs/rules/lines-between-class-members + */ + "lines-between-class-members": Linter.RuleEntry< + [ + "always" | "never", + Partial<{ + /** + * @default false + */ + exceptAfterSingleLine: boolean; + }>, + ] + >; + + /** + * Rule to enforce a maximum depth that blocks can be nested. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/max-depth + */ + "max-depth": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 4 + */ + max: number; + }>, + ] + >; + + /** + * Rule to enforce a maximum line length. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/max-len + */ + "max-len": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 80 + */ + code: number; + /** + * @default 4 + */ + tabWidth: number; + comments: number; + ignorePattern: string; + /** + * @default false + */ + ignoreComments: boolean; + /** + * @default false + */ + ignoreTrailingComments: boolean; + /** + * @default false + */ + ignoreUrls: boolean; + /** + * @default false + */ + ignoreStrings: boolean; + /** + * @default false + */ + ignoreTemplateLiterals: boolean; + /** + * @default false + */ + ignoreRegExpLiterals: boolean; + }>, + ] + >; + + /** + * Rule to enforce a maximum number of lines per file. + * + * @since 2.12.0 + * @see https://eslint.org/docs/rules/max-lines + */ + "max-lines": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 300 + */ + max: number; + /** + * @default false + */ + skipBlankLines: boolean; + /** + * @default false + */ + skipComments: boolean; + }> + | number, + ] + >; + + /** + * Rule to enforce a maximum number of line of code in a function. + * + * @since 5.0.0 + * @see https://eslint.org/docs/rules/max-lines-per-function + */ + "max-lines-per-function": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 50 + */ + max: number; + /** + * @default false + */ + skipBlankLines: boolean; + /** + * @default false + */ + skipComments: boolean; + /** + * @default false + */ + IIFEs: boolean; + }>, + ] + >; + + /** + * Rule to enforce a maximum depth that callbacks can be nested. + * + * @since 0.2.0 + * @see https://eslint.org/docs/rules/max-nested-callbacks + */ + "max-nested-callbacks": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 10 + */ + max: number; + }> + | number, + ] + >; + + /** + * Rule to enforce a maximum number of parameters in function definitions. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/max-params + */ + "max-params": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 3 + */ + max: number; + }> + | number, + ] + >; + + /** + * Rule to enforce a maximum number of statements allowed in function blocks. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/max-statements + */ + "max-statements": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 10 + */ + max: number; + /** + * @default false + */ + ignoreTopLevelFunctions: boolean; + }> + | number, + ] + >; + + /** + * Rule to enforce a maximum number of statements allowed per line. + * + * @since 2.5.0 + * @see https://eslint.org/docs/rules/max-statements-per-line + */ + "max-statements-per-line": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 1 + */ + max: number; + }> + | number, + ] + >; + + /** + * Rule to enforce a particular style for multiline comments. + * + * @since 4.10.0 + * @see https://eslint.org/docs/rules/multiline-comment-style + */ + "multiline-comment-style": Linter.RuleEntry<["starred-block" | "bare-block" | "separate-lines"]>; + + /** + * Rule to enforce newlines between operands of ternary expressions. + * + * @since 3.1.0 + * @see https://eslint.org/docs/rules/multiline-ternary + */ + "multiline-ternary": Linter.RuleEntry<["always" | "always-multiline" | "never"]>; + + /** + * Rule to require constructor names to begin with a capital letter. + * + * @since 0.0.3-0 + * @see https://eslint.org/docs/rules/new-cap + */ + "new-cap": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + newIsCap: boolean; + /** + * @default true + */ + capIsNew: boolean; + newIsCapExceptions: string[]; + newIsCapExceptionPattern: string; + capIsNewExceptions: string[]; + capIsNewExceptionPattern: string; + /** + * @default true + */ + properties: boolean; + }>, + ] + >; + + /** + * Rule to enforce or disallow parentheses when invoking a constructor with no arguments. + * + * @since 0.0.6 + * @see https://eslint.org/docs/rules/new-parens + */ + "new-parens": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require a newline after each call in a method chain. + * + * @since 2.0.0-rc.0 + * @see https://eslint.org/docs/rules/newline-per-chained-call + */ + "newline-per-chained-call": Linter.RuleEntry< + [ + { + /** + * @default 2 + */ + ignoreChainWithDepth: number; + }, + ] + >; + + /** + * Rule to disallow `Array` constructors. + * + * @since 0.4.0 + * @see https://eslint.org/docs/rules/no-array-constructor + */ + "no-array-constructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow bitwise operators. + * + * @since 0.0.2 + * @see https://eslint.org/docs/rules/no-bitwise + */ + "no-bitwise": Linter.RuleEntry< + [ + Partial<{ + allow: string[]; + /** + * @default false + */ + int32Hint: boolean; + }>, + ] + >; + + /** + * Rule to disallow `continue` statements. + * + * @since 0.19.0 + * @see https://eslint.org/docs/rules/no-continue + */ + "no-continue": Linter.RuleEntry<[]>; + + /** + * Rule to disallow inline comments after code. + * + * @since 0.10.0 + * @see https://eslint.org/docs/rules/no-inline-comments + */ + "no-inline-comments": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `if` statements as the only statement in `else` blocks. + * + * @since 0.6.0 + * @see https://eslint.org/docs/rules/no-lonely-if + */ + "no-lonely-if": Linter.RuleEntry<[]>; + + /** + * Rule to disallow mixed binary operators. + * + * @since 2.12.0 + * @see https://eslint.org/docs/rules/no-mixed-operators + */ + "no-mixed-operators": Linter.RuleEntry< + [ + Partial<{ + /** + * @default + * [ + * ["+", "-", "*", "/", "%", "**"], + * ["&", "|", "^", "~", "<<", ">>", ">>>"], + * ["==", "!=", "===", "!==", ">", ">=", "<", "<="], + * ["&&", "||"], + * ["in", "instanceof"] + * ] + */ + groups: string[][]; + /** + * @default true + */ + allowSamePrecedence: boolean; + }>, + ] + >; + + /** + * Rule to disallow mixed spaces and tabs for indentation. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.7.1 + * @see https://eslint.org/docs/rules/no-mixed-spaces-and-tabs + */ + "no-mixed-spaces-and-tabs": Linter.RuleEntry<["smart-tabs"]>; + + /** + * Rule to disallow use of chained assignment expressions. + * + * @since 3.14.0 + * @see https://eslint.org/docs/rules/no-multi-assign + */ + "no-multi-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow multiple empty lines. + * + * @since 0.9.0 + * @see https://eslint.org/docs/rules/no-multiple-empty-lines + */ + "no-multiple-empty-lines": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 2 + */ + max: number; + maxEOF: number; + maxBOF: number; + }> + | number, + ] + >; + + /** + * Rule to disallow negated conditions. + * + * @since 1.6.0 + * @see https://eslint.org/docs/rules/no-negated-condition + */ + "no-negated-condition": Linter.RuleEntry<[]>; + + /** + * Rule to disallow nested ternary expressions. + * + * @since 0.2.0 + * @see https://eslint.org/docs/rules/no-nested-ternary + */ + "no-nested-ternary": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `Object` constructors. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-new-object + */ + "no-new-object": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the unary operators `++` and `--`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-plusplus + */ + "no-plusplus": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowForLoopAfterthoughts: boolean; + }>, + ] + >; + + /** + * Rule to disallow specified syntax. + * + * @since 1.4.0 + * @see https://eslint.org/docs/rules/no-restricted-syntax + */ + "no-restricted-syntax": Linter.RuleEntry< + [ + ...Array< + | string + | { + selector: string; + message?: string | undefined; + } + > + ] + >; + + /** + * Rule to disallow all tabs. + * + * @since 3.2.0 + * @see https://eslint.org/docs/rules/no-tabs + */ + "no-tabs": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowIndentationTabs: boolean; + }>, + ] + >; + + /** + * Rule to disallow ternary operators. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-ternary + */ + "no-ternary": Linter.RuleEntry<[]>; + + /** + * Rule to disallow trailing whitespace at the end of lines. + * + * @since 0.7.1 + * @see https://eslint.org/docs/rules/no-trailing-spaces + */ + "no-trailing-spaces": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + skipBlankLines: boolean; + /** + * @default false + */ + ignoreComments: boolean; + }>, + ] + >; + + /** + * Rule to disallow dangling underscores in identifiers. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-underscore-dangle + */ + "no-underscore-dangle": Linter.RuleEntry< + [ + Partial<{ + allow: string[]; + /** + * @default false + */ + allowAfterThis: boolean; + /** + * @default false + */ + allowAfterSuper: boolean; + /** + * @default false + */ + enforceInMethodNames: boolean; + }>, + ] + >; + + /** + * Rule to disallow ternary operators when simpler alternatives exist. + * + * @since 0.21.0 + * @see https://eslint.org/docs/rules/no-unneeded-ternary + */ + "no-unneeded-ternary": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + defaultAssignment: boolean; + }>, + ] + >; + + /** + * Rule to disallow whitespace before properties. + * + * @since 2.0.0-beta.1 + * @see https://eslint.org/docs/rules/no-whitespace-before-property + */ + "no-whitespace-before-property": Linter.RuleEntry<[]>; + + /** + * Rule to enforce the location of single-line statements. + * + * @since 3.17.0 + * @see https://eslint.org/docs/rules/nonblock-statement-body-position + */ + "nonblock-statement-body-position": Linter.RuleEntry< + [ + "beside" | "below" | "any", + Partial<{ + overrides: Record; + }>, + ] + >; + + /** + * Rule to enforce consistent line breaks inside braces. + * + * @since 2.12.0 + * @see https://eslint.org/docs/rules/object-curly-newline + */ + "object-curly-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | Partial<{ + /** + * @default false + */ + multiline: boolean; + minProperties: number; + /** + * @default true + */ + consistent: boolean; + }> + | Partial< + Record< + "ObjectExpression" | "ObjectPattern" | "ImportDeclaration" | "ExportDeclaration", + | "always" + | "never" + | Partial<{ + /** + * @default false + */ + multiline: boolean; + minProperties: number; + /** + * @default true + */ + consistent: boolean; + }> + > + >, + ] + >; + + /** + * Rule to enforce consistent spacing inside braces. + * + * @since 0.22.0 + * @see https://eslint.org/docs/rules/object-curly-spacing + */ + "object-curly-spacing": + | Linter.RuleEntry< + [ + "never", + { + /** + * @default false + */ + arraysInObjects: boolean; + /** + * @default false + */ + objectsInObjects: boolean; + }, + ] + > + | Linter.RuleEntry< + [ + "always", + { + /** + * @default true + */ + arraysInObjects: boolean; + /** + * @default true + */ + objectsInObjects: boolean; + }, + ] + >; + + /** + * Rule to enforce placing object properties on separate lines. + * + * @since 2.10.0 + * @see https://eslint.org/docs/rules/object-property-newline + */ + "object-property-newline": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowAllPropertiesOnSameLine: boolean; + }>, + ] + >; + + /** + * Rule to enforce variables to be declared either together or separately in functions. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/one-var + */ + "one-var": Linter.RuleEntry< + [ + | "always" + | "never" + | "consecutive" + | Partial< + { + /** + * @default false + */ + separateRequires: boolean; + } & Record<"var" | "let" | "const", "always" | "never" | "consecutive"> + > + | Partial>, + ] + >; + + /** + * Rule to require or disallow newlines around variable declarations. + * + * @since 2.0.0-beta.3 + * @see https://eslint.org/docs/rules/one-var-declaration-per-line + */ + "one-var-declaration-per-line": Linter.RuleEntry<["initializations" | "always"]>; + + /** + * Rule to require or disallow assignment operator shorthand where possible. + * + * @since 0.10.0 + * @see https://eslint.org/docs/rules/operator-assignment + */ + "operator-assignment": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to enforce consistent linebreak style for operators. + * + * @since 0.19.0 + * @see https://eslint.org/docs/rules/operator-linebreak + */ + "operator-linebreak": Linter.RuleEntry< + [ + "after" | "before" | "none", + Partial<{ + overrides: Record; + }>, + ] + >; + + /** + * Rule to require or disallow padding within blocks. + * + * @since 0.9.0 + * @see https://eslint.org/docs/rules/padded-blocks + */ + "padded-blocks": Linter.RuleEntry< + [ + "always" | "never" | Partial>, + { + /** + * @default false + */ + allowSingleLineBlocks: boolean; + }, + ] + >; + + /** + * Rule to require or disallow padding lines between statements. + * + * @since 4.0.0-beta.0 + * @see https://eslint.org/docs/rules/padding-line-between-statements + */ + "padding-line-between-statements": Linter.RuleEntry< + [ + ...Array< + { + blankLine: "any" | "never" | "always"; + } & Record<"prev" | "next", string | string[]> + > + ] + >; + + /** + * Rule to disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead. + * + * @since 5.0.0-alpha.3 + * @see https://eslint.org/docs/rules/prefer-object-spread + */ + "prefer-object-spread": Linter.RuleEntry<[]>; + + /** + * Rule to require quotes around object literal property names. + * + * @since 0.0.6 + * @see https://eslint.org/docs/rules/quote-props + */ + "quote-props": + | Linter.RuleEntry<["always" | "consistent"]> + | Linter.RuleEntry< + [ + "as-needed", + Partial<{ + /** + * @default false + */ + keywords: boolean; + /** + * @default true + */ + unnecessary: boolean; + /** + * @default false + */ + numbers: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "consistent-as-needed", + Partial<{ + /** + * @default false + */ + keywords: boolean; + }>, + ] + >; + + /** + * Rule to enforce the consistent use of either backticks, double, or single quotes. + * + * @since 0.0.7 + * @see https://eslint.org/docs/rules/quotes + */ + quotes: Linter.RuleEntry< + [ + "double" | "single" | "backtick", + Partial<{ + /** + * @default false + */ + avoidEscape: boolean; + /** + * @default false + */ + allowTemplateLiterals: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow semicolons instead of ASI. + * + * @since 0.0.6 + * @see https://eslint.org/docs/rules/semi + */ + semi: + | Linter.RuleEntry< + [ + "always", + Partial<{ + /** + * @default false + */ + omitLastInOneLineBlock: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "never", + Partial<{ + /** + * @default 'any' + */ + beforeStatementContinuationChars: "any" | "always" | "never"; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before and after semicolons. + * + * @since 0.16.0 + * @see https://eslint.org/docs/rules/semi-spacing + */ + "semi-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + before: boolean; + /** + * @default true + */ + after: boolean; + }>, + ] + >; + + /** + * Rule to enforce location of semicolons. + * + * @since 4.0.0-beta.0 + * @see https://eslint.org/docs/rules/semi-style + */ + "semi-style": Linter.RuleEntry<["last" | "first"]>; + + /** + * Rule to require object keys to be sorted. + * + * @since 3.3.0 + * @see https://eslint.org/docs/rules/sort-keys + */ + "sort-keys": Linter.RuleEntry< + [ + "asc" | "desc", + Partial<{ + /** + * @default true + */ + caseSensitive: boolean; + /** + * @default 2 + */ + minKeys: number; + /** + * @default false + */ + natural: boolean; + }>, + ] + >; + + /** + * Rule to require variables within the same declaration block to be sorted. + * + * @since 0.2.0 + * @see https://eslint.org/docs/rules/sort-vars + */ + "sort-vars": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreCase: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before blocks. + * + * @since 0.9.0 + * @see https://eslint.org/docs/rules/space-before-blocks + */ + "space-before-blocks": Linter.RuleEntry< + ["always" | "never" | Partial>] + >; + + /** + * Rule to enforce consistent spacing before `function` definition opening parenthesis. + * + * @since 0.18.0 + * @see https://eslint.org/docs/rules/space-before-function-paren + */ + "space-before-function-paren": Linter.RuleEntry< + ["always" | "never" | Partial>] + >; + + /** + * Rule to enforce consistent spacing inside parentheses. + * + * @since 0.8.0 + * @see https://eslint.org/docs/rules/space-in-parens + */ + "space-in-parens": Linter.RuleEntry< + [ + "never" | "always", + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to require spacing around infix operators. + * + * @since 0.2.0 + * @see https://eslint.org/docs/rules/space-infix-ops + */ + "space-infix-ops": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + int32Hint: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before or after unary operators. + * + * @since 0.10.0 + * @see https://eslint.org/docs/rules/space-unary-ops + */ + "space-unary-ops": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + words: boolean; + /** + * @default false + */ + nonwords: boolean; + overrides: Record; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing after the `//` or `/*` in a comment. + * + * @since 0.23.0 + * @see https://eslint.org/docs/rules/spaced-comment + */ + "spaced-comment": Linter.RuleEntry< + [ + "always" | "never", + { + exceptions: string[]; + markers: string[]; + line: { + exceptions: string[]; + markers: string[]; + }; + block: { + exceptions: string[]; + markers: string[]; + /** + * @default false + */ + balanced: boolean; + }; + }, + ] + >; + + /** + * Rule to enforce spacing around colons of switch statements. + * + * @since 4.0.0-beta.0 + * @see https://eslint.org/docs/rules/switch-colon-spacing + */ + "switch-colon-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + before: boolean; + /** + * @default true + */ + after: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow spacing between template tags and their literals. + * + * @since 3.15.0 + * @see https://eslint.org/docs/rules/template-tag-spacing + */ + "template-tag-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require or disallow Unicode byte order mark (BOM). + * + * @since 2.11.0 + * @see https://eslint.org/docs/rules/unicode-bom + */ + "unicode-bom": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require parenthesis around regex literals. + * + * @since 0.1.0 + * @see https://eslint.org/docs/rules/wrap-regex + */ + "wrap-regex": Linter.RuleEntry<[]>; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/rules/variables.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/variables.d.ts new file mode 100644 index 0000000..6347531 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/rules/variables.d.ts @@ -0,0 +1,187 @@ +import { Linter } from "../index"; + +export interface Variables extends Linter.RulesRecord { + /** + * Rule to require or disallow initialization in variable declarations. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/rules/init-declarations + */ + "init-declarations": + | Linter.RuleEntry<["always"]> + | Linter.RuleEntry< + [ + "never", + Partial<{ + ignoreForLoopInit: boolean; + }>, + ] + >; + + /** + * Rule to disallow deleting variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-delete-var + */ + "no-delete-var": Linter.RuleEntry<[]>; + + /** + * Rule to disallow labels that share a name with a variable. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-label-var + */ + "no-label-var": Linter.RuleEntry<[]>; + + /** + * Rule to disallow specified global variables. + * + * @since 2.3.0 + * @see https://eslint.org/docs/rules/no-restricted-globals + */ + "no-restricted-globals": Linter.RuleEntry< + [ + ...Array< + | string + | { + name: string; + message?: string | undefined; + } + > + ] + >; + + /** + * Rule to disallow variable declarations from shadowing variables declared in the outer scope. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-shadow + */ + "no-shadow": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + builtinGlobals: boolean; + /** + * @default 'functions' + */ + hoist: "functions" | "all" | "never"; + allow: string[]; + }>, + ] + >; + + /** + * Rule to disallow identifiers from shadowing restricted names. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.1.4 + * @see https://eslint.org/docs/rules/no-shadow-restricted-names + */ + "no-shadow-restricted-names": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of undeclared variables unless mentioned in `global` comments. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-undef + */ + "no-undef": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + typeof: boolean; + }>, + ] + >; + + /** + * Rule to disallow initializing variables to `undefined`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/rules/no-undef-init + */ + "no-undef-init": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `undefined` as an identifier. + * + * @since 0.7.1 + * @see https://eslint.org/docs/rules/no-undefined + */ + "no-undefined": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unused variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-unused-vars + */ + "no-unused-vars": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'all' + */ + vars: "all" | "local"; + varsIgnorePattern: string; + /** + * @default 'after-used' + */ + args: "after-used" | "all" | "none"; + /** + * @default false + */ + ignoreRestSiblings: boolean; + argsIgnorePattern: string; + /** + * @default 'none' + */ + caughtErrors: "none" | "all"; + caughtErrorsIgnorePattern: string; + }>, + ] + >; + + /** + * Rule to disallow the use of variables before they are defined. + * + * @since 0.0.9 + * @see https://eslint.org/docs/rules/no-use-before-define + */ + "no-use-before-define": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default true + */ + functions: boolean; + /** + * @default true + */ + classes: boolean; + /** + * @default true + */ + variables: boolean; + }> + | "nofunc", + ] + >; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/eslint/use-at-your-own-risk.d.ts b/node_modules/mathjs/examples/node_modules/@types/eslint/use-at-your-own-risk.d.ts new file mode 100644 index 0000000..29492ca --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/eslint/use-at-your-own-risk.d.ts @@ -0,0 +1,8 @@ +/** @deprecated */ +export const builtinRules: Map; +/** @deprecated */ +export class FileEnumerator { + constructor(params?: {cwd?: string, configArrayFactory?: any, extensions?: any, globInputPaths?: boolean, errorOnUnmatchedPattern?: boolean, ignore?: boolean}); + isTargetPath(filePath: string, providedConfig?: any): boolean; + iterateFiles(patternOrPatterns: string | string[]): IterableIterator<{config: any, filePath: string, ignored: boolean}>; +} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/@types/estree/LICENSE b/node_modules/mathjs/examples/node_modules/@types/estree/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/estree/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/node_modules/mathjs/examples/node_modules/@types/estree/README.md b/node_modules/mathjs/examples/node_modules/@types/estree/README.md new file mode 100644 index 0000000..1d3dfee --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/estree/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/estree` + +# Summary +This package contains type definitions for ESTree AST specification (https://github.com/estree/estree). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree. + +### Additional Details + * Last updated: Sun, 06 Feb 2022 12:01:26 GMT + * Dependencies: none + * Global values: none + +# Credits +These definitions were written by [RReverser](https://github.com/RReverser). diff --git a/node_modules/mathjs/examples/node_modules/@types/estree/flow.d.ts b/node_modules/mathjs/examples/node_modules/@types/estree/flow.d.ts new file mode 100644 index 0000000..605765e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/estree/flow.d.ts @@ -0,0 +1,174 @@ +// Type definitions for ESTree AST extensions for Facebook Flow +// Project: https://github.com/estree/estree +// Definitions by: RReverser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + +declare namespace ESTree { + interface FlowTypeAnnotation extends Node {} + + interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {} + + interface FlowLiteralTypeAnnotation extends FlowTypeAnnotation, Literal {} + + interface FlowDeclaration extends Declaration {} + + interface AnyTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ArrayTypeAnnotation extends FlowTypeAnnotation { + elementType: FlowTypeAnnotation; + } + + interface BooleanLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface BooleanTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ClassImplements extends Node { + id: Identifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface ClassProperty { + key: Expression; + value?: Expression | null; + typeAnnotation?: TypeAnnotation | null; + computed: boolean; + static: boolean; + } + + interface DeclareClass extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + body: ObjectTypeAnnotation; + extends: Array; + } + + interface DeclareFunction extends FlowDeclaration { + id: Identifier; + } + + interface DeclareModule extends FlowDeclaration { + id: Literal | Identifier; + body: BlockStatement; + } + + interface DeclareVariable extends FlowDeclaration { + id: Identifier; + } + + interface FunctionTypeAnnotation extends FlowTypeAnnotation { + params: Array; + returnType: FlowTypeAnnotation; + rest?: FunctionTypeParam | null; + typeParameters?: TypeParameterDeclaration | null; + } + + interface FunctionTypeParam { + name: Identifier; + typeAnnotation: FlowTypeAnnotation; + optional: boolean; + } + + interface GenericTypeAnnotation extends FlowTypeAnnotation { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceExtends extends Node { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceDeclaration extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + extends: Array; + body: ObjectTypeAnnotation; + } + + interface IntersectionTypeAnnotation extends FlowTypeAnnotation { + types: Array; + } + + interface MixedTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface NullableTypeAnnotation extends FlowTypeAnnotation { + typeAnnotation: TypeAnnotation; + } + + interface NumberLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface NumberTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface StringLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface StringTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface TupleTypeAnnotation extends FlowTypeAnnotation { + types: Array; + } + + interface TypeofTypeAnnotation extends FlowTypeAnnotation { + argument: FlowTypeAnnotation; + } + + interface TypeAlias extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + right: FlowTypeAnnotation; + } + + interface TypeAnnotation extends Node { + typeAnnotation: FlowTypeAnnotation; + } + + interface TypeCastExpression extends Expression { + expression: Expression; + typeAnnotation: TypeAnnotation; + } + + interface TypeParameterDeclaration extends Node { + params: Array; + } + + interface TypeParameterInstantiation extends Node { + params: Array; + } + + interface ObjectTypeAnnotation extends FlowTypeAnnotation { + properties: Array; + indexers: Array; + callProperties: Array; + } + + interface ObjectTypeCallProperty extends Node { + value: FunctionTypeAnnotation; + static: boolean; + } + + interface ObjectTypeIndexer extends Node { + id: Identifier; + key: FlowTypeAnnotation; + value: FlowTypeAnnotation; + static: boolean; + } + + interface ObjectTypeProperty extends Node { + key: Expression; + value: FlowTypeAnnotation; + optional: boolean; + static: boolean; + } + + interface QualifiedTypeIdentifier extends Node { + qualification: Identifier | QualifiedTypeIdentifier; + id: Identifier; + } + + interface UnionTypeAnnotation extends FlowTypeAnnotation { + types: Array; + } + + interface VoidTypeAnnotation extends FlowBaseTypeAnnotation {} +} diff --git a/node_modules/mathjs/examples/node_modules/@types/estree/index.d.ts b/node_modules/mathjs/examples/node_modules/@types/estree/index.d.ts new file mode 100644 index 0000000..c0db842 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/estree/index.d.ts @@ -0,0 +1,595 @@ +// Type definitions for ESTree AST specification +// Project: https://github.com/estree/estree +// Definitions by: RReverser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// This definition file follows a somewhat unusual format. ESTree allows +// runtime type checks based on the `type` parameter. In order to explain this +// to typescript we want to use discriminated union types: +// https://github.com/Microsoft/TypeScript/pull/9163 +// +// For ESTree this is a bit tricky because the high level interfaces like +// Node or Function are pulling double duty. We want to pass common fields down +// to the interfaces that extend them (like Identifier or +// ArrowFunctionExpression), but you can't extend a type union or enforce +// common fields on them. So we've split the high level interfaces into two +// types, a base type which passes down inherited fields, and a type union of +// all types which extend the base type. Only the type union is exported, and +// the union is how other types refer to the collection of inheriting types. +// +// This makes the definitions file here somewhat more difficult to maintain, +// but it has the notable advantage of making ESTree much easier to use as +// an end user. + +interface BaseNodeWithoutComments { + // Every leaf interface that extends BaseNode must specify a type property. + // The type property should be a string literal. For example, Identifier + // has: `type: "Identifier"` + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; +} + +interface BaseNode extends BaseNodeWithoutComments { + leadingComments?: Array | undefined; + trailingComments?: Array | undefined; +} + +export type Node = + Identifier | Literal | Program | Function | SwitchCase | CatchClause | + VariableDeclarator | Statement | Expression | PrivateIdentifier | Property | PropertyDefinition | + AssignmentProperty | Super | TemplateElement | SpreadElement | Pattern | + ClassBody | Class | MethodDefinition | ModuleDeclaration | ModuleSpecifier; + +export interface Comment extends BaseNodeWithoutComments { + type: "Line" | "Block"; + value: string; +} + +interface SourceLocation { + source?: string | null | undefined; + start: Position; + end: Position; +} + +export interface Position { + /** >= 1 */ + line: number; + /** >= 0 */ + column: number; +} + +export interface Program extends BaseNode { + type: "Program"; + sourceType: "script" | "module"; + body: Array; + comments?: Array | undefined; +} + +export interface Directive extends BaseNode { + type: "ExpressionStatement"; + expression: Literal; + directive: string; +} + +interface BaseFunction extends BaseNode { + params: Array; + generator?: boolean | undefined; + async?: boolean | undefined; + // The body is either BlockStatement or Expression because arrow functions + // can have a body that's either. FunctionDeclarations and + // FunctionExpressions have only BlockStatement bodies. + body: BlockStatement | Expression; +} + +export type Function = + FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; + +export type Statement = + ExpressionStatement | BlockStatement | StaticBlock | EmptyStatement | + DebuggerStatement | WithStatement | ReturnStatement | LabeledStatement | + BreakStatement | ContinueStatement | IfStatement | SwitchStatement | + ThrowStatement | TryStatement | WhileStatement | DoWhileStatement | + ForStatement | ForInStatement | ForOfStatement | Declaration; + +interface BaseStatement extends BaseNode { } + +export interface EmptyStatement extends BaseStatement { + type: "EmptyStatement"; +} + +export interface BlockStatement extends BaseStatement { + type: "BlockStatement"; + body: Array; + innerComments?: Array | undefined; +} + +export interface StaticBlock extends Omit { + type: "StaticBlock"; +} + +export interface ExpressionStatement extends BaseStatement { + type: "ExpressionStatement"; + expression: Expression; +} + +export interface IfStatement extends BaseStatement { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate?: Statement | null | undefined; +} + +export interface LabeledStatement extends BaseStatement { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +export interface BreakStatement extends BaseStatement { + type: "BreakStatement"; + label?: Identifier | null | undefined; +} + +export interface ContinueStatement extends BaseStatement { + type: "ContinueStatement"; + label?: Identifier | null | undefined; +} + +export interface WithStatement extends BaseStatement { + type: "WithStatement"; + object: Expression; + body: Statement; +} + +export interface SwitchStatement extends BaseStatement { + type: "SwitchStatement"; + discriminant: Expression; + cases: Array; +} + +export interface ReturnStatement extends BaseStatement { + type: "ReturnStatement"; + argument?: Expression | null | undefined; +} + +export interface ThrowStatement extends BaseStatement { + type: "ThrowStatement"; + argument: Expression; +} + +export interface TryStatement extends BaseStatement { + type: "TryStatement"; + block: BlockStatement; + handler?: CatchClause | null | undefined; + finalizer?: BlockStatement | null | undefined; +} + +export interface WhileStatement extends BaseStatement { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +export interface DoWhileStatement extends BaseStatement { + type: "DoWhileStatement"; + body: Statement; + test: Expression; +} + +export interface ForStatement extends BaseStatement { + type: "ForStatement"; + init?: VariableDeclaration | Expression | null | undefined; + test?: Expression | null | undefined; + update?: Expression | null | undefined; + body: Statement; +} + +interface BaseForXStatement extends BaseStatement { + left: VariableDeclaration | Pattern; + right: Expression; + body: Statement; +} + +export interface ForInStatement extends BaseForXStatement { + type: "ForInStatement"; +} + +export interface DebuggerStatement extends BaseStatement { + type: "DebuggerStatement"; +} + +export type Declaration = + FunctionDeclaration | VariableDeclaration | ClassDeclaration; + +interface BaseDeclaration extends BaseStatement { } + +export interface FunctionDeclaration extends BaseFunction, BaseDeclaration { + type: "FunctionDeclaration"; + /** It is null when a function declaration is a part of the `export default function` statement */ + id: Identifier | null; + body: BlockStatement; +} + +export interface VariableDeclaration extends BaseDeclaration { + type: "VariableDeclaration"; + declarations: Array; + kind: "var" | "let" | "const"; +} + +export interface VariableDeclarator extends BaseNode { + type: "VariableDeclarator"; + id: Pattern; + init?: Expression | null | undefined; +} + +type Expression = + ThisExpression | ArrayExpression | ObjectExpression | FunctionExpression | + ArrowFunctionExpression | YieldExpression | Literal | UnaryExpression | + UpdateExpression | BinaryExpression | AssignmentExpression | + LogicalExpression | MemberExpression | ConditionalExpression | + CallExpression | NewExpression | SequenceExpression | TemplateLiteral | + TaggedTemplateExpression | ClassExpression | MetaProperty | Identifier | + AwaitExpression | ImportExpression | ChainExpression; + +export interface BaseExpression extends BaseNode { } + +type ChainElement = SimpleCallExpression | MemberExpression; + +export interface ChainExpression extends BaseExpression { + type: "ChainExpression"; + expression: ChainElement; +} + +export interface ThisExpression extends BaseExpression { + type: "ThisExpression"; +} + +export interface ArrayExpression extends BaseExpression { + type: "ArrayExpression"; + elements: Array; +} + +export interface ObjectExpression extends BaseExpression { + type: "ObjectExpression"; + properties: Array; +} + +export interface PrivateIdentifier extends BaseNode { + type: "PrivateIdentifier"; + name: string; +} + +export interface Property extends BaseNode { + type: "Property"; + key: Expression | PrivateIdentifier; + value: Expression | Pattern; // Could be an AssignmentProperty + kind: "init" | "get" | "set"; + method: boolean; + shorthand: boolean; + computed: boolean; +} + +export interface PropertyDefinition extends BaseNode { + type: "PropertyDefinition"; + key: Expression | PrivateIdentifier; + value?: Expression | null | undefined; + computed: boolean; + static: boolean; +} + +export interface FunctionExpression extends BaseFunction, BaseExpression { + id?: Identifier | null | undefined; + type: "FunctionExpression"; + body: BlockStatement; +} + +export interface SequenceExpression extends BaseExpression { + type: "SequenceExpression"; + expressions: Array; +} + +export interface UnaryExpression extends BaseExpression { + type: "UnaryExpression"; + operator: UnaryOperator; + prefix: true; + argument: Expression; +} + +export interface BinaryExpression extends BaseExpression { + type: "BinaryExpression"; + operator: BinaryOperator; + left: Expression; + right: Expression; +} + +export interface AssignmentExpression extends BaseExpression { + type: "AssignmentExpression"; + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; +} + +export interface UpdateExpression extends BaseExpression { + type: "UpdateExpression"; + operator: UpdateOperator; + argument: Expression; + prefix: boolean; +} + +export interface LogicalExpression extends BaseExpression { + type: "LogicalExpression"; + operator: LogicalOperator; + left: Expression; + right: Expression; +} + +export interface ConditionalExpression extends BaseExpression { + type: "ConditionalExpression"; + test: Expression; + alternate: Expression; + consequent: Expression; +} + +interface BaseCallExpression extends BaseExpression { + callee: Expression | Super; + arguments: Array; +} +export type CallExpression = SimpleCallExpression | NewExpression; + +export interface SimpleCallExpression extends BaseCallExpression { + type: "CallExpression"; + optional: boolean; +} + +export interface NewExpression extends BaseCallExpression { + type: "NewExpression"; +} + +export interface MemberExpression extends BaseExpression, BasePattern { + type: "MemberExpression"; + object: Expression | Super; + property: Expression | PrivateIdentifier; + computed: boolean; + optional: boolean; +} + +export type Pattern = + Identifier | ObjectPattern | ArrayPattern | RestElement | + AssignmentPattern | MemberExpression; + +interface BasePattern extends BaseNode { } + +export interface SwitchCase extends BaseNode { + type: "SwitchCase"; + test?: Expression | null | undefined; + consequent: Array; +} + +export interface CatchClause extends BaseNode { + type: "CatchClause"; + param: Pattern | null; + body: BlockStatement; +} + +export interface Identifier extends BaseNode, BaseExpression, BasePattern { + type: "Identifier"; + name: string; +} + +export type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; + +export interface SimpleLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value: string | boolean | number | null; + raw?: string | undefined; +} + +export interface RegExpLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: RegExp | null | undefined; + regex: { + pattern: string; + flags: string; + }; + raw?: string | undefined; +} + +export interface BigIntLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: bigint | null | undefined; + bigint: string; + raw?: string | undefined; +} + +export type UnaryOperator = + "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + +export type BinaryOperator = + "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | + ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "**" | "|" | "^" | "&" | "in" | + "instanceof"; + +export type LogicalOperator = "||" | "&&" | "??"; + +export type AssignmentOperator = + "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "**=" | "<<=" | ">>=" | ">>>=" | + "|=" | "^=" | "&="; + +export type UpdateOperator = "++" | "--"; + +export interface ForOfStatement extends BaseForXStatement { + type: "ForOfStatement"; + await: boolean; +} + +export interface Super extends BaseNode { + type: "Super"; +} + +export interface SpreadElement extends BaseNode { + type: "SpreadElement"; + argument: Expression; +} + +export interface ArrowFunctionExpression extends BaseExpression, BaseFunction { + type: "ArrowFunctionExpression"; + expression: boolean; + body: BlockStatement | Expression; +} + +export interface YieldExpression extends BaseExpression { + type: "YieldExpression"; + argument?: Expression | null | undefined; + delegate: boolean; +} + +export interface TemplateLiteral extends BaseExpression { + type: "TemplateLiteral"; + quasis: Array; + expressions: Array; +} + +export interface TaggedTemplateExpression extends BaseExpression { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +export interface TemplateElement extends BaseNode { + type: "TemplateElement"; + tail: boolean; + value: { + /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ + cooked?: string | null | undefined; + raw: string; + }; +} + +export interface AssignmentProperty extends Property { + value: Pattern; + kind: "init"; + method: boolean; // false +} + +export interface ObjectPattern extends BasePattern { + type: "ObjectPattern"; + properties: Array; +} + +export interface ArrayPattern extends BasePattern { + type: "ArrayPattern"; + elements: Array; +} + +export interface RestElement extends BasePattern { + type: "RestElement"; + argument: Pattern; +} + +export interface AssignmentPattern extends BasePattern { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +export type Class = ClassDeclaration | ClassExpression; +interface BaseClass extends BaseNode { + superClass?: Expression | null | undefined; + body: ClassBody; +} + +export interface ClassBody extends BaseNode { + type: "ClassBody"; + body: Array; +} + +export interface MethodDefinition extends BaseNode { + type: "MethodDefinition"; + key: Expression | PrivateIdentifier; + value: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; +} + +export interface ClassDeclaration extends BaseClass, BaseDeclaration { + type: "ClassDeclaration"; + /** It is null when a class declaration is a part of the `export default class` statement */ + id: Identifier | null; +} + +export interface ClassExpression extends BaseClass, BaseExpression { + type: "ClassExpression"; + id?: Identifier | null | undefined; +} + +export interface MetaProperty extends BaseExpression { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +export type ModuleDeclaration = + ImportDeclaration | ExportNamedDeclaration | ExportDefaultDeclaration | + ExportAllDeclaration; +interface BaseModuleDeclaration extends BaseNode { } + +export type ModuleSpecifier = + ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | + ExportSpecifier; +interface BaseModuleSpecifier extends BaseNode { + local: Identifier; +} + +export interface ImportDeclaration extends BaseModuleDeclaration { + type: "ImportDeclaration"; + specifiers: Array; + source: Literal; +} + +export interface ImportSpecifier extends BaseModuleSpecifier { + type: "ImportSpecifier"; + imported: Identifier; +} + +export interface ImportExpression extends BaseExpression { + type: "ImportExpression"; + source: Expression; +} + +export interface ImportDefaultSpecifier extends BaseModuleSpecifier { + type: "ImportDefaultSpecifier"; +} + +export interface ImportNamespaceSpecifier extends BaseModuleSpecifier { + type: "ImportNamespaceSpecifier"; +} + +export interface ExportNamedDeclaration extends BaseModuleDeclaration { + type: "ExportNamedDeclaration"; + declaration?: Declaration | null | undefined; + specifiers: Array; + source?: Literal | null | undefined; +} + +export interface ExportSpecifier extends BaseModuleSpecifier { + type: "ExportSpecifier"; + exported: Identifier; +} + +export interface ExportDefaultDeclaration extends BaseModuleDeclaration { + type: "ExportDefaultDeclaration"; + declaration: Declaration | Expression; +} + +export interface ExportAllDeclaration extends BaseModuleDeclaration { + type: "ExportAllDeclaration"; + exported: Identifier | null; + source: Literal; +} + +export interface AwaitExpression extends BaseExpression { + type: "AwaitExpression"; + argument: Expression; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/estree/package.json b/node_modules/mathjs/examples/node_modules/@types/estree/package.json new file mode 100644 index 0000000..dea75b7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/estree/package.json @@ -0,0 +1,25 @@ +{ + "name": "@types/estree", + "version": "0.0.51", + "description": "TypeScript definitions for ESTree AST specification", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree", + "license": "MIT", + "contributors": [ + { + "name": "RReverser", + "url": "https://github.com/RReverser", + "githubUsername": "RReverser" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/estree" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "95cbccd2dde8b8492f61e0e8049641ae05129705d9ba742955b711cfb71f3621", + "typeScriptVersion": "3.8" +} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/@types/json-schema/LICENSE b/node_modules/mathjs/examples/node_modules/@types/json-schema/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/json-schema/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/node_modules/mathjs/examples/node_modules/@types/json-schema/README.md b/node_modules/mathjs/examples/node_modules/@types/json-schema/README.md new file mode 100644 index 0000000..e410136 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/json-schema/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/json-schema` + +# Summary +This package contains type definitions for json-schema 4.0, 6.0 and (https://github.com/kriszyp/json-schema). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/json-schema. + +### Additional Details + * Last updated: Fri, 25 Mar 2022 14:01:45 GMT + * Dependencies: none + * Global values: none + +# Credits +These definitions were written by [Boris Cherny](https://github.com/bcherny), [Lucian Buzzo](https://github.com/lucianbuzzo), [Roland Groza](https://github.com/rolandjitsu), and [Jason Kwok](https://github.com/JasonHK). diff --git a/node_modules/mathjs/examples/node_modules/@types/json-schema/index.d.ts b/node_modules/mathjs/examples/node_modules/@types/json-schema/index.d.ts new file mode 100644 index 0000000..7a92dec --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/json-schema/index.d.ts @@ -0,0 +1,758 @@ +// Type definitions for json-schema 4.0, 6.0 and 7.0 +// Project: https://github.com/kriszyp/json-schema +// Definitions by: Boris Cherny +// Lucian Buzzo +// Roland Groza +// Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +//================================================================================================== +// JSON Schema Draft 04 +//================================================================================================== + +/** + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1 + */ +export type JSONSchema4TypeName = + | 'string' // + | 'number' + | 'integer' + | 'boolean' + | 'object' + | 'array' + | 'null' + | 'any'; + +/** + * @see https://tools.ietf.org/html/draft-zyp-json-schema-04#section-3.5 + */ +export type JSONSchema4Type = + | string // + | number + | boolean + | JSONSchema4Object + | JSONSchema4Array + | null; + +// Workaround for infinite type recursion +export interface JSONSchema4Object { + [key: string]: JSONSchema4Type; +} + +// Workaround for infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +export interface JSONSchema4Array extends Array {} + +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-04/schema#' + * - 'http://json-schema.org/draft-04/hyper-schema#' + * - 'http://json-schema.org/draft-03/schema#' + * - 'http://json-schema.org/draft-03/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema4Version = string; + +/** + * JSON Schema V4 + * @see https://tools.ietf.org/html/draft-zyp-json-schema-04 + */ +export interface JSONSchema4 { + id?: string | undefined; + $ref?: string | undefined; + $schema?: JSONSchema4Version | undefined; + + /** + * This attribute is a string that provides a short description of the + * instance property. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.21 + */ + title?: string | undefined; + + /** + * This attribute is a string that provides a full description of the of + * purpose the instance property. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.22 + */ + description?: string | undefined; + + default?: JSONSchema4Type | undefined; + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: boolean | undefined; + minimum?: number | undefined; + exclusiveMinimum?: boolean | undefined; + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + + /** + * May only be defined when "items" is defined, and is a tuple of JSONSchemas. + * + * This provides a definition for additional items in an array instance + * when tuple definitions of the items is provided. This can be false + * to indicate additional items in the array are not allowed, or it can + * be a schema that defines the schema of the additional items. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.6 + */ + additionalItems?: boolean | JSONSchema4 | undefined; + + /** + * This attribute defines the allowed items in an instance array, and + * MUST be a schema or an array of schemas. The default value is an + * empty schema which allows any value for items in the instance array. + * + * When this attribute value is a schema and the instance value is an + * array, then all the items in the array MUST be valid according to the + * schema. + * + * When this attribute value is an array of schemas and the instance + * value is an array, each position in the instance array MUST conform + * to the schema in the corresponding position for this array. This + * called tuple typing. When tuple typing is used, additional items are + * allowed, disallowed, or constrained by the "additionalItems" + * (Section 5.6) attribute using the same rules as + * "additionalProperties" (Section 5.4) for objects. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.5 + */ + items?: JSONSchema4 | JSONSchema4[] | undefined; + + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + maxProperties?: number | undefined; + minProperties?: number | undefined; + + /** + * This attribute indicates if the instance must have a value, and not + * be undefined. This is false by default, making the instance + * optional. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.7 + */ + required?: boolean | string[] | undefined; + + /** + * This attribute defines a schema for all properties that are not + * explicitly defined in an object type definition. If specified, the + * value MUST be a schema or a boolean. If false is provided, no + * additional properties are allowed beyond the properties defined in + * the schema. The default value is an empty schema which allows any + * value for additional properties. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.4 + */ + additionalProperties?: boolean | JSONSchema4 | undefined; + + definitions?: { + [k: string]: JSONSchema4; + } | undefined; + + /** + * This attribute is an object with property definitions that define the + * valid values of instance object property values. When the instance + * value is an object, the property values of the instance object MUST + * conform to the property definitions in this object. In this object, + * each property definition's value MUST be a schema, and the property's + * name MUST be the name of the instance property that it defines. The + * instance property value MUST be valid according to the schema from + * the property definition. Properties are considered unordered, the + * order of the instance properties MAY be in any order. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.2 + */ + properties?: { + [k: string]: JSONSchema4; + } | undefined; + + /** + * This attribute is an object that defines the schema for a set of + * property names of an object instance. The name of each property of + * this attribute's object is a regular expression pattern in the ECMA + * 262/Perl 5 format, while the value is a schema. If the pattern + * matches the name of a property on the instance object, the value of + * the instance's property MUST be valid against the pattern name's + * schema value. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.3 + */ + patternProperties?: { + [k: string]: JSONSchema4; + } | undefined; + dependencies?: { + [k: string]: JSONSchema4 | string[]; + } | undefined; + + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19 + */ + enum?: JSONSchema4Type[] | undefined; + + /** + * A single type, or a union of simple types + */ + type?: JSONSchema4TypeName | JSONSchema4TypeName[] | undefined; + + allOf?: JSONSchema4[] | undefined; + anyOf?: JSONSchema4[] | undefined; + oneOf?: JSONSchema4[] | undefined; + not?: JSONSchema4 | undefined; + + /** + * The value of this property MUST be another schema which will provide + * a base schema which the current schema will inherit from. The + * inheritance rules are such that any instance that is valid according + * to the current schema MUST be valid according to the referenced + * schema. This MAY also be an array, in which case, the instance MUST + * be valid for all the schemas in the array. A schema that extends + * another schema MAY define additional attributes, constrain existing + * attributes, or add other constraints. + * + * Conceptually, the behavior of extends can be seen as validating an + * instance against all constraints in the extending schema as well as + * the extended schema(s). + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.26 + */ + extends?: string | string[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-zyp-json-schema-04#section-5.6 + */ + [k: string]: any; + + format?: string | undefined; +} + +//================================================================================================== +// JSON Schema Draft 06 +//================================================================================================== + +export type JSONSchema6TypeName = + | 'string' // + | 'number' + | 'integer' + | 'boolean' + | 'object' + | 'array' + | 'null' + | 'any'; + +export type JSONSchema6Type = + | string // + | number + | boolean + | JSONSchema6Object + | JSONSchema6Array + | null; + +// Workaround for infinite type recursion +export interface JSONSchema6Object { + [key: string]: JSONSchema6Type; +} + +// Workaround for infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +export interface JSONSchema6Array extends Array {} + +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-06/schema#' + * - 'http://json-schema.org/draft-06/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema6Version = string; + +/** + * JSON Schema V6 + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01 + */ +export type JSONSchema6Definition = JSONSchema6 | boolean; +export interface JSONSchema6 { + $id?: string | undefined; + $ref?: string | undefined; + $schema?: JSONSchema6Version | undefined; + + /** + * Must be strictly greater than 0. + * A numeric instance is valid only if division by this keyword's value results in an integer. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.1 + */ + multipleOf?: number | undefined; + + /** + * Representing an inclusive upper limit for a numeric instance. + * This keyword validates only if the instance is less than or exactly equal to "maximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.2 + */ + maximum?: number | undefined; + + /** + * Representing an exclusive upper limit for a numeric instance. + * This keyword validates only if the instance is strictly less than (not equal to) to "exclusiveMaximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.3 + */ + exclusiveMaximum?: number | undefined; + + /** + * Representing an inclusive lower limit for a numeric instance. + * This keyword validates only if the instance is greater than or exactly equal to "minimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.4 + */ + minimum?: number | undefined; + + /** + * Representing an exclusive lower limit for a numeric instance. + * This keyword validates only if the instance is strictly greater than (not equal to) to "exclusiveMinimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.5 + */ + exclusiveMinimum?: number | undefined; + + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.6 + */ + maxLength?: number | undefined; + + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.7 + */ + minLength?: number | undefined; + + /** + * Should be a valid regular expression, according to the ECMA 262 regular expression dialect. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.8 + */ + pattern?: string | undefined; + + /** + * This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.9 + */ + items?: JSONSchema6Definition | JSONSchema6Definition[] | undefined; + + /** + * This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself. + * If "items" is an array of schemas, validation succeeds if every instance element + * at a position greater than the size of "items" validates against "additionalItems". + * Otherwise, "additionalItems" MUST be ignored, as the "items" schema + * (possibly the default value of an empty schema) is applied to all elements. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.10 + */ + additionalItems?: JSONSchema6Definition | undefined; + + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.11 + */ + maxItems?: number | undefined; + + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.12 + */ + minItems?: number | undefined; + + /** + * If this keyword has boolean value false, the instance validates successfully. + * If it has boolean value true, the instance validates successfully if all of its elements are unique. + * Omitting this keyword has the same behavior as a value of false. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.13 + */ + uniqueItems?: boolean | undefined; + + /** + * An array instance is valid against "contains" if at least one of its elements is valid against the given schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.14 + */ + contains?: JSONSchema6Definition | undefined; + + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.15 + */ + maxProperties?: number | undefined; + + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is greater than, + * or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.16 + */ + minProperties?: number | undefined; + + /** + * Elements of this array must be unique. + * An object instance is valid against this keyword if every item in the array is the name of a property in the instance. + * Omitting this keyword has the same behavior as an empty array. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.17 + */ + required?: string[] | undefined; + + /** + * This keyword determines how child instances validate for objects, and does not directly validate the immediate instance itself. + * Validation succeeds if, for each name that appears in both the instance and as a name within this keyword's value, + * the child instance for that name successfully validates against the corresponding schema. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.18 + */ + properties?: { + [k: string]: JSONSchema6Definition; + } | undefined; + + /** + * This attribute is an object that defines the schema for a set of property names of an object instance. + * The name of each property of this attribute's object is a regular expression pattern in the ECMA 262, while the value is a schema. + * If the pattern matches the name of a property on the instance object, the value of the instance's property + * MUST be valid against the pattern name's schema value. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.19 + */ + patternProperties?: { + [k: string]: JSONSchema6Definition; + } | undefined; + + /** + * This attribute defines a schema for all properties that are not explicitly defined in an object type definition. + * If specified, the value MUST be a schema or a boolean. + * If false is provided, no additional properties are allowed beyond the properties defined in the schema. + * The default value is an empty schema which allows any value for additional properties. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.20 + */ + additionalProperties?: JSONSchema6Definition | undefined; + + /** + * This keyword specifies rules that are evaluated if the instance is an object and contains a certain property. + * Each property specifies a dependency. + * If the dependency value is an array, each element in the array must be unique. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.21 + */ + dependencies?: { + [k: string]: JSONSchema6Definition | string[]; + } | undefined; + + /** + * Takes a schema which validates the names of all properties rather than their values. + * Note the property name that the schema is testing will always be a string. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.22 + */ + propertyNames?: JSONSchema6Definition | undefined; + + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.23 + */ + enum?: JSONSchema6Type[] | undefined; + + /** + * More readable form of a one-element "enum" + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.24 + */ + const?: JSONSchema6Type | undefined; + + /** + * A single type, or a union of simple types + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.25 + */ + type?: JSONSchema6TypeName | JSONSchema6TypeName[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.26 + */ + allOf?: JSONSchema6Definition[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.27 + */ + anyOf?: JSONSchema6Definition[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.28 + */ + oneOf?: JSONSchema6Definition[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.29 + */ + not?: JSONSchema6Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.1 + */ + definitions?: { + [k: string]: JSONSchema6Definition; + } | undefined; + + /** + * This attribute is a string that provides a short description of the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + title?: string | undefined; + + /** + * This attribute is a string that provides a full description of the of purpose the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + description?: string | undefined; + + /** + * This keyword can be used to supply a default JSON value associated with a particular schema. + * It is RECOMMENDED that a default value be valid against the associated schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.3 + */ + default?: JSONSchema6Type | undefined; + + /** + * Array of examples with no validation effect the value of "default" is usable as an example without repeating it under this keyword + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.4 + */ + examples?: JSONSchema6Type[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-8 + */ + format?: string | undefined; +} + +//================================================================================================== +// JSON Schema Draft 07 +//================================================================================================== +// https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 +//-------------------------------------------------------------------------------------------------- + +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchema7TypeName = + | 'string' // + | 'number' + | 'integer' + | 'boolean' + | 'object' + | 'array' + | 'null'; + +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchema7Type = + | string // + | number + | boolean + | JSONSchema7Object + | JSONSchema7Array + | null; + +// Workaround for infinite type recursion +export interface JSONSchema7Object { + [key: string]: JSONSchema7Type; +} + +// Workaround for infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +export interface JSONSchema7Array extends Array {} + +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-07/schema#' + * - 'http://json-schema.org/draft-07/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema7Version = string; + +/** + * JSON Schema v7 + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 + */ +export type JSONSchema7Definition = JSONSchema7 | boolean; +export interface JSONSchema7 { + $id?: string | undefined; + $ref?: string | undefined; + $schema?: JSONSchema7Version | undefined; + $comment?: string | undefined; + + /** + * @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-8.2.4 + * @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#appendix-A + */ + $defs?: { + [key: string]: JSONSchema7Definition; + } | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1 + */ + type?: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined; + enum?: JSONSchema7Type[] | undefined; + const?: JSONSchema7Type | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2 + */ + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: number | undefined; + minimum?: number | undefined; + exclusiveMinimum?: number | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3 + */ + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4 + */ + items?: JSONSchema7Definition | JSONSchema7Definition[] | undefined; + additionalItems?: JSONSchema7Definition | undefined; + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + contains?: JSONSchema7 | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5 + */ + maxProperties?: number | undefined; + minProperties?: number | undefined; + required?: string[] | undefined; + properties?: { + [key: string]: JSONSchema7Definition; + } | undefined; + patternProperties?: { + [key: string]: JSONSchema7Definition; + } | undefined; + additionalProperties?: JSONSchema7Definition | undefined; + dependencies?: { + [key: string]: JSONSchema7Definition | string[]; + } | undefined; + propertyNames?: JSONSchema7Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6 + */ + if?: JSONSchema7Definition | undefined; + then?: JSONSchema7Definition | undefined; + else?: JSONSchema7Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7 + */ + allOf?: JSONSchema7Definition[] | undefined; + anyOf?: JSONSchema7Definition[] | undefined; + oneOf?: JSONSchema7Definition[] | undefined; + not?: JSONSchema7Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7 + */ + format?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-8 + */ + contentMediaType?: string | undefined; + contentEncoding?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-9 + */ + definitions?: { + [key: string]: JSONSchema7Definition; + } | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10 + */ + title?: string | undefined; + description?: string | undefined; + default?: JSONSchema7Type | undefined; + readOnly?: boolean | undefined; + writeOnly?: boolean | undefined; + examples?: JSONSchema7Type | undefined; +} + +export interface ValidationResult { + valid: boolean; + errors: ValidationError[]; +} + +export interface ValidationError { + property: string; + message: string; +} + +/** + * To use the validator call JSONSchema.validate with an instance object and an optional schema object. + * If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), + * that schema will be used to validate and the schema parameter is not necessary (if both exist, + * both validations will occur). + */ +export function validate(instance: {}, schema: JSONSchema4 | JSONSchema6 | JSONSchema7): ValidationResult; + +/** + * The checkPropertyChange method will check to see if an value can legally be in property with the given schema + * This is slightly different than the validate method in that it will fail if the schema is readonly and it will + * not check for self-validation, it is assumed that the passed in value is already internally valid. + */ +export function checkPropertyChange( + value: any, + schema: JSONSchema4 | JSONSchema6 | JSONSchema7, + property: string, +): ValidationResult; + +/** + * This checks to ensure that the result is valid and will throw an appropriate error message if it is not. + */ +export function mustBeValid(result: ValidationResult): void; diff --git a/node_modules/mathjs/examples/node_modules/@types/json-schema/package.json b/node_modules/mathjs/examples/node_modules/@types/json-schema/package.json new file mode 100644 index 0000000..f4ac271 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/json-schema/package.json @@ -0,0 +1,40 @@ +{ + "name": "@types/json-schema", + "version": "7.0.11", + "description": "TypeScript definitions for json-schema 4.0, 6.0 and", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/json-schema", + "license": "MIT", + "contributors": [ + { + "name": "Boris Cherny", + "url": "https://github.com/bcherny", + "githubUsername": "bcherny" + }, + { + "name": "Lucian Buzzo", + "url": "https://github.com/lucianbuzzo", + "githubUsername": "lucianbuzzo" + }, + { + "name": "Roland Groza", + "url": "https://github.com/rolandjitsu", + "githubUsername": "rolandjitsu" + }, + { + "name": "Jason Kwok", + "url": "https://github.com/JasonHK", + "githubUsername": "JasonHK" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/json-schema" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "84a402b9e31ddb097f08b5c07c08590bf087035c483db7a4071a04903775dc44", + "typeScriptVersion": "3.9" +} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/@types/node/LICENSE b/node_modules/mathjs/examples/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/node_modules/mathjs/examples/node_modules/@types/node/README.md b/node_modules/mathjs/examples/node_modules/@types/node/README.md new file mode 100644 index 0000000..cb40e88 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for Node.js (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Wed, 23 Mar 2022 17:01:45 GMT + * Dependencies: none + * Global values: `AbortController`, `AbortSignal`, `__dirname`, `__filename`, `console`, `exports`, `gc`, `global`, `module`, `process`, `require` + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), and [wafuwafu13](https://github.com/wafuwafu13). diff --git a/node_modules/mathjs/examples/node_modules/@types/node/assert.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..fb71586 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/assert.d.ts @@ -0,0 +1,912 @@ +/** + * The `assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/assert.js) + */ +declare module 'assert' { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `assert` module + * will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // tslint:disable-next-line:ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is currently experimental and behavior might still change. + * @since v14.2.0, v12.19.0 + * @experimental + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * function foo() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * tracker.report(); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return of objects containing information about the wrapper functions returned by `calls`. + */ + report(): CallTrackerReportInformation[]; + /** + * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new () => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // tslint:disable-next-line:ban-types + stackStartFn?: Function + ): never; + /** + * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison) ( `==` ). `NaN` is special handled + * and treated as being identical in case both sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison)(`!=` ). `NaN` is special handled and treated as + * being identical in case both + * sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error + * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'assert'; + * + * const obj1 = { + * a: { + * b: 1 + * } + * }; + * const obj2 = { + * a: { + * b: 2 + * } + * }; + * const obj3 = { + * a: { + * b: 1 + * } + * }; + * const obj4 = Object.create(obj1); + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default + * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text' + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text' + * } + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * } + * ); + * + * // Using regular expressions to validate error properties: + * throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text' + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i + * } + * ); + * + * // Fails due to the different `message` and `name` properties: + * throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/ + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error' + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. + * + * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops' + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error + * handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and`name` properties. + * + * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value' + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second + * argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; + function doesNotReject(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + const strict: Omit & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + }; + } + export = assert; +} +declare module 'node:assert' { + import assert = require('assert'); + export = assert; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/assert/strict.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000..b4319b9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module 'assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} +declare module 'node:assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/async_hooks.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000..f53198e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,501 @@ +/** + * The `async_hooks` module provides an API to track asynchronous resources. It + * can be accessed using: + * + * ```js + * import async_hooks from 'async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/async_hooks.js) + */ +declare module 'async_hooks' { + /** + * ```js + * import { executionAsyncId } from 'async_hooks'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on `promise execution tracking`. + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'fs'; + * import { executionAsyncId, executionAsyncResource } from 'async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook + * } from 'async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * } + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on `promise execution tracking`. + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { } + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false } + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since 9.3) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>( + fn: Func + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `async_hooks` module,`AsyncLocalStorage` should be preferred as it is a performant and memory safe + * implementation that involves significant optimizations that are non-obvious to + * implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'http'; + * import { AsyncLocalStorage } from 'async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 1: start + * // 0: finish + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } +} +declare module 'node:async_hooks' { + export * from 'async_hooks'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/buffer.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000..1a26043 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,2232 @@ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/buffer.js) + */ +declare module 'buffer' { + import { BinaryLike } from 'node:crypto'; + export const INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'latin1' | 'binary'; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new (size: number): Buffer; + prototype: Buffer; + }; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + * @experimental + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): unknown; // pending web streams types + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + global { + // Buffer class + type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex'; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new (str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new (arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: ReadonlyArray): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new (buffer: Buffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(arrayBuffer: WithImplicitCoercion, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | ReadonlyArray): Buffer; + from(data: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: 'string'): string; + }, + encoding?: BufferEncoding + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength(string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: ReadonlyArray, totalLength?: number): Buffer; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and_may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`,`Buffer.from(array)`, `Buffer.concat()`, and the + * deprecated`new Buffer(size)` constructor only when `size` is less than or equal + * to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. A zero-length `Buffer` is created + * if `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and_may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer extends Uint8Array { + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: 'Buffer'; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare(target: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This is the same behavior as `buf.subarray()`. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * ``` + * @since v0.3.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): Buffer; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): Buffer; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): Buffer; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.slice()`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @deprecated Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @deprecated Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + } +} +declare module 'node:buffer' { + export * from 'buffer'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/child_process.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000..7eae502 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1366 @@ +/** + * The `child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if it is in the `options` object. Otherwise, `process.env.PATH` is + * used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `child_process` module provides a handful of synchronous + * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/child_process.js) + */ +declare module 'child_process' { + import { ObjectEncodingOptions } from 'node:fs'; + import { EventEmitter, Abortable } from 'node:events'; + import * as net from 'node:net'; + import { Writable, Readable, Stream, Pipe } from 'node:stream'; + import { URL } from 'node:url'; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel currently exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * const assert = require('assert'); + * const fs = require('fs'); + * const child_process = require('child_process'); + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ] + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * const { spawn } = require('child_process'); + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'] + * } + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * const cp = require('child_process'); + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received + * and buffered in the socket will not be sent to the child. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * const subprocess = require('child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('net').createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on + * a `'message'` event instead of `'connection'` and using `server.bind()` instead + * of `server.listen()`. This is, however, currently only supported on Unix + * platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * const { fork } = require('child_process'); + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = require('net').createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, options?: MessageOptions, callback?: (error: Error | null) => void): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: 'spawn', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'exit', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'message', message: Serializable, sendHandle: SendHandle): boolean; + emit(event: 'spawn', listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: 'spawn', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: 'spawn', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: 'spawn', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: 'spawn', listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio extends ChildProcess { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = 'overlapped' | 'pipe' | 'ignore' | 'inherit'; + type StdioOptions = IOType | Array; + type SerializationType = 'json' | 'advanced'; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default true + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = 'inherit' | 'ignore' | Stream; + type StdioPipeNamed = 'pipe' | 'overlapped'; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * const { spawn } = require('child_process'); + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * const { spawn } = require('child_process'); + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent, + * retrieve it with the`process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { spawn } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * const { exec } = require('child_process'); + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * const { exec } = require('child_process'); + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const exec = util.promisify(require('child_process').exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { exec } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: (ObjectEncodingOptions & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + type ExecFileException = ExecException & NodeJS.ErrnoException; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * const { execFile } = require('child_process'); + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const execFile = util.promisify(require('child_process').execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { execFile } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + function execFile(file: string): ChildProcess; + function execFile(file: string, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + // no `options` definitely means stdout/stderr are `string`. + function execFile(file: string, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile(file: string, options: ExecFileOptionsWithOtherEncoding, callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * const { fork } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | 'buffer' | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: 'buffer' | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | 'buffer' | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: 'buffer' | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): string | Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: 'buffer' | null; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; + function execFileSync(file: string, args: ReadonlyArray): Buffer; + function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): string | Buffer; +} +declare module 'node:child_process' { + export * from 'child_process'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/cluster.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..c48084d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,414 @@ +/** + * A single instance of Node.js runs in a single thread. To take advantage of + * multi-core systems, the user will sometimes want to launch a cluster of Node.js + * processes to handle the load. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/cluster.js) + */ +declare module 'cluster' { + import * as child from 'node:child_process'; + import EventEmitter = require('node:events'); + import * as net from 'node:net'; + export interface ClusterSettings { + execArgv?: string[] | undefined; // default: process.execArgv + exec?: string | undefined; + args?: string[] | undefined; + silent?: boolean | undefined; + stdio?: any[] | undefined; + uid?: number | undefined; + gid?: number | undefined; + inspectPort?: number | (() => number) | undefined; + } + export interface Address { + address: string; + port: number; + addressType: number | 'udp4' | 'udp6'; // 4, 6, -1, "udp4", "udp6" + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the`id`. + * + * While a worker is alive, this is the key that indexes it in`cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using `child_process.fork()`, the returned object + * from this function is stored as `.process`. In a worker, the global `process`is stored. + * + * See: `Child Process module`. + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary this sends a message to a specific worker. It is identical to `ChildProcess.send()`. + * + * In a worker this sends a message to the primary. It is identical to`process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send(message: child.Serializable, sendHandle: child.SendHandle, callback?: (error: Error | null) => void): boolean; + send(message: child.Serializable, sendHandle: child.SendHandle, options?: child.MessageOptions, callback?: (error: Error | null) => void): boolean; + /** + * This function will kill the worker. In the primary, it does this + * by disconnecting the `worker.process`, and once disconnected, killing + * with `signal`. In the worker, it does it by disconnecting the channel, + * and then exiting with code `0`. + * + * Because `kill()` attempts to gracefully disconnect the worker process, it is + * susceptible to waiting indefinitely for the disconnect to complete. For example, + * if the worker enters an infinite loop, a graceful disconnect will never occur. + * If the graceful disconnect behavior is not needed, use `worker.process.kill()`. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * This method is aliased as `worker.destroy()` for backward compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is `kill()`. + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const net = require('net'); + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): void; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.kill()` or`.disconnect()`. If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'exit', listener: (code: number, signal: string) => void): this; + addListener(event: 'listening', listener: (address: Address) => void): this; + addListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: 'online', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'exit', code: number, signal: string): boolean; + emit(event: 'listening', address: Address): boolean; + emit(event: 'message', message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'exit', listener: (code: number, signal: string) => void): this; + on(event: 'listening', listener: (address: Address) => void): this; + on(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: 'online', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'exit', listener: (code: number, signal: string) => void): this; + once(event: 'listening', listener: (address: Address) => void): this; + once(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: 'online', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'exit', listener: (code: number, signal: string) => void): this; + prependListener(event: 'listening', listener: (address: Address) => void): this; + prependListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: 'online', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number, signal: string) => void): this; + prependOnceListener(event: 'listening', listener: (address: Address) => void): this; + prependOnceListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: 'online', listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + readonly isPrimary: boolean; + readonly isWorker: boolean; + schedulingPolicy: number; + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use setupPrimary. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. + */ + setupPrimary(settings?: ClusterSettings): void; + readonly worker?: Worker | undefined; + readonly workers?: NodeJS.Dict | undefined; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'disconnect', listener: (worker: Worker) => void): this; + addListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: 'fork', listener: (worker: Worker) => void): this; + addListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + addListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: 'online', listener: (worker: Worker) => void): this; + addListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'disconnect', worker: Worker): boolean; + emit(event: 'exit', worker: Worker, code: number, signal: string): boolean; + emit(event: 'fork', worker: Worker): boolean; + emit(event: 'listening', worker: Worker, address: Address): boolean; + emit(event: 'message', worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online', worker: Worker): boolean; + emit(event: 'setup', settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'disconnect', listener: (worker: Worker) => void): this; + on(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: 'fork', listener: (worker: Worker) => void): this; + on(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + on(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: 'online', listener: (worker: Worker) => void): this; + on(event: 'setup', listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'disconnect', listener: (worker: Worker) => void): this; + once(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: 'fork', listener: (worker: Worker) => void): this; + once(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + once(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: 'online', listener: (worker: Worker) => void): this; + once(event: 'setup', listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: 'fork', listener: (worker: Worker) => void): this; + prependListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: 'message', listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void): this; + prependListener(event: 'online', listener: (worker: Worker) => void): this; + prependListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: 'fork', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; + prependOnceListener(event: 'online', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module 'node:cluster' { + export * from 'cluster'; + export { default as default } from 'cluster'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/console.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000..9297018 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/console.d.ts @@ -0,0 +1,412 @@ +/** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/console.js) + */ +declare module 'console' { + import console = require('node:console'); + export = console; +} +declare module 'node:console' { + import { InspectOptions } from 'node:util'; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`. + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param label The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param label The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string + * values are concatenated. See `util.format()` for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation`length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation`length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See `util.format()` for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can’t be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: ReadonlyArray): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('100-elements'); + * for (let i = 0; i < 100; i++) {} + * console.timeEnd('100-elements'); + * // prints 100-elements: 225.438ms + * ``` + * @since v0.1.104 + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + ignoreErrors?: boolean | undefined; + colorMode?: boolean | 'auto' | undefined; + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new (stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new (options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/constants.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..208020d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/constants.d.ts @@ -0,0 +1,18 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module 'constants' { + import { constants as osConstants, SignalConstants } from 'node:os'; + import { constants as cryptoConstants } from 'node:crypto'; + import { constants as fsConstants } from 'node:fs'; + + const exp: typeof osConstants.errno & + typeof osConstants.priority & + SignalConstants & + typeof cryptoConstants & + typeof fsConstants; + export = exp; +} + +declare module 'node:constants' { + import constants = require('constants'); + export = constants; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/crypto.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000..4dff488 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,3307 @@ +/** + * The `crypto` module provides cryptographic functionality that includes a set of + * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. + * + * ```js + * const { createHmac } = await import('crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/crypto.js) + */ +declare module 'crypto' { + import * as stream from 'node:stream'; + import { PeerCertificate } from 'node:tls'; + interface Certificate { + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + const Certificate: Certificate & { + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + new (): Certificate; + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + (): Certificate; + /** + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + }; + namespace constants { + // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const ALPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHash + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = 'base64' | 'base64url' | 'hex' | 'binary'; + type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1'; + type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2'; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = 'compressed' | 'uncompressed' | 'hybrid'; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { createHash } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: stream.TransformOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = 'secret' | 'public' | 'private'; + interface KeyExportOptions { + type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1'; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: 'jwk'; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + interface JwkKeyExportOptions { + format: 'jwk'; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { webcrypto, KeyObject } = await import('crypto'); + * const { subtle } = webcrypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256 + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<'pem'>): string | Buffer; + export(options?: KeyExportOptions<'der'>): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305'; + type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike | null, options: CipherCCMOptions): CipherCCM; + function createCipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, options?: CipherGCMOptions): CipherGCM; + function createCipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * + * import { + * pipeline + * } from 'stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike | null, options: CipherCCMOptions): DecipherCCM; + function createDecipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, options?: CipherGCMOptions): DecipherGCM; + function createDecipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'pkcs8' | 'sec1' | undefined; + passphrase?: string | Buffer | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'spki' | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey + * } = await import('crypto'); + * + * generateKey('hmac', { length: 64 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: 'hmac' | 'aes', + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync + * } = await import('crypto'); + * + * const key = generateKeySync('hmac', { length: 64 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: 'hmac' | 'aes', + options: { + length: number; + } + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: 'jwk'; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = 'der' | 'ieee-p1363'; + interface SigningOptions { + /** + * @See crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1' + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, outputFormat: BinaryToTextEncoding): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createDiffieHellman + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `constants`module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, + * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The + * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman + * } = await import('crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellman; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2 + * } = await import('crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been + * deprecated and use should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey); // '3745e48...aa39b34' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync + * } = await import('crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use + * should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); + * console.log(key); // '3745e48...aa39b34' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 248. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt + * } = await import('crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt + * } = await import('crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void): void; + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, options: ScryptOptions, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync + * } = await import('crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * ```js + * const { + * getCiphers + * } = await import('crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves + * } = await import('crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * ```js + * const { + * getHashes + * } = await import('crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createECDH + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'`format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH + * } = await import('crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: 'latin1' | 'hex' | 'base64' | 'base64url', + format?: 'uncompressed' | 'compressed' | 'hybrid' + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function is based on a constant-time algorithm. + * Returns true if `a` is equal to `b`, without leaking timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: BufferEncoding; + type KeyType = 'rsa' | 'rsa-pss' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; + type KeyFormat = 'pem' | 'der'; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync + * } = await import('crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair + * } = await import('crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + namespace generateKeyPair { + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'rsa', options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'dsa', options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ec', options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'x448', options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + callback: (error: Error | null, data: Buffer) => void + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + type CipherMode = 'cbc' | 'ccm' | 'cfb' | 'ctr' | 'ecb' | 'gcm' | 'ocb' | 'ofb' | 'stream' | 'wrap' | 'xts'; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdf + * } = await import('crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf(digest: string, irm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => void): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdfSync + * } = await import('crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync(digest: string, ikm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): string; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject: 'always' | 'never'; + /** + * @default true + */ + wildcards: boolean; + /** + * @default true + */ + partialWildcards: boolean; + /** + * @default false + */ + multiLabelWildcards: boolean; + /** + * @default false + */ + singleLabelSubdomains: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (ca) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * @since v15.6.0 + */ + readonly subjectAltName: string; + /** + * The information access content of this certificate. + * @since v15.6.0 + */ + readonly infoAccess: string; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * @since v15.6.0 + * @return Returns `name` if the certificate matches, `undefined` if it does not. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether this certificate was issued by the given `otherCert`. + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsBigInt, callback: (err: Error | null, prime: bigint) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsArrayBuffer, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptions, callback: (err: Error | null, prime: ArrayBuffer | bigint) => void): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime(value: LargeNumberLike, options: CheckPrimeOptions, callback: (err: Error | null, result: boolean) => void): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + namespace webcrypto { + class CryptoKey {} // placeholder + } +} +declare module 'node:crypto' { + export * from 'crypto'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/dgram.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000..b4a9892 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,545 @@ +/** + * The `dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/dgram.js) + */ +declare module 'dgram' { + import { AddressInfo } from 'node:net'; + import * as dns from 'node:dns'; + import { EventEmitter, Abortable } from 'node:events'; + interface RemoteInfo { + address: string; + family: 'IPv4' | 'IPv6'; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = 'udp4' | 'udp6'; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: ((hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void) | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'cluster'; + * import dgram from 'dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family` and `port`properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on`localhost`: + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send(msg: string | Uint8Array | ReadonlyArray, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, callback?: (error: Error | null, bytes: number) => void): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no addition effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'message', msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + } +} +declare module 'node:dgram' { + export * from 'dgram'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000..915d2af --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,134 @@ +/** + * The `diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/diagnostics_channel.js) + */ +declare module 'diagnostics_channel' { + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string): boolean; + /** + * This is the primary entry-point for anyone wanting to interact with a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string): Channel; + type ChannelListener = (name: string, message: unknown) => void; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is use to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string); + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The previous subscribed handler to remove + */ + unsubscribe(onMessage: ChannelListener): void; + } +} +declare module 'node:diagnostics_channel' { + export * from 'diagnostics_channel'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/dns.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000..d59f554 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/dns.d.ts @@ -0,0 +1,659 @@ +/** + * The `dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * const dns = require('dns'); + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * const dns = require('dns'); + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the `Implementation considerations section` for more information. + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/dns.js) + */ +declare module 'dns' { + import * as dnsPromises from 'node:dns/promises'; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + family?: number | undefined; + hints?: number | undefined; + all?: boolean | undefined; + /** + * @default true + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + address: string; + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses, and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the `Implementation considerations section` before using`dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('dns'); + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties. + * @since v0.1.90 + */ + export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void; + export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void; + export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On an error, `err` is an `Error` object, where `err.code` is the error code. + * + * ```js + * const dns = require('dns'); + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: 'A'; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: 'AAAA'; + } + export interface CaaRecord { + critial: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: 'MX'; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: 'NAPTR'; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: 'SOA'; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: 'SRV'; + } + export interface AnyTxtRecord { + type: 'TXT'; + entries: string[]; + } + export interface AnyNsRecord { + type: 'NS'; + value: string; + } + export interface AnyPtrRecord { + type: 'PTR'; + value: string; + } + export interface AnyCnameRecord { + type: 'CNAME'; + value: string; + } + export type AnyRecord = AnyARecord | AnyAaaaRecord | AnyCnameRecord | AnyMxRecord | AnyNaptrRecord | AnyNsRecord | AnyPtrRecord | AnySoaRecord | AnySrvRecord | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an `Error` object, where `err.code` is one of theDNS error codes. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'A', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'AAAA', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'ANY', callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'CNAME', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'MX', callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'NAPTR', callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'NS', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'PTR', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'SOA', callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void; + export function resolve(hostname: string, rrtype: 'SRV', callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'TXT', callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export function resolve( + hostname: string, + rrtype: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: 'A' | 'AAAA' | 'CNAME' | 'NS' | 'PTR'): Promise; + function __promisify__(hostname: string, rrtype: 'ANY'): Promise; + function __promisify__(hostname: string, rrtype: 'MX'): Promise; + function __promisify__(hostname: string, rrtype: 'NAPTR'): Promise; + function __promisify__(hostname: string, rrtype: 'SOA'): Promise; + function __promisify__(hostname: string, rrtype: 'SRV'): Promise; + function __promisify__(hostname: string, rrtype: 'TXT'): Promise; + function __promisify__(hostname: string, rrtype: string): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa(hostname: string, callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC + * 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an `Error` object, where `err.code` is + * one of the `DNS error codes`. + * @since v0.1.16 + */ + export function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of `RFC 5952` formatted addresses + */ + export function setServers(servers: ReadonlyArray): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` and {@link setDefaultResultOrder} have higher + * priority than `--dns-result-order`. When using `worker threads`,{@link setDefaultResultOrder} from the main thread won't affect the default + * dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; + // Error codes + export const NODATA: string; + export const FORMERR: string; + export const SERVFAIL: string; + export const NOTFOUND: string; + export const NOTIMP: string; + export const REFUSED: string; + export const BADQUERY: string; + export const BADNAME: string; + export const BADFAMILY: string; + export const BADRESP: string; + export const CONNREFUSED: string; + export const TIMEOUT: string; + export const EOF: string; + export const FILE: string; + export const NOMEM: string; + export const DESTRUCTION: string; + export const BADSTR: string; + export const BADFLAGS: string; + export const NONAME: string; + export const BADHINTS: string; + export const NOTINITIALIZED: string; + export const LOADIPHLPAPI: string; + export const ADDRGETNETWORKPARAMS: string; + export const CANCELLED: string; + export interface ResolverOptions { + timeout?: number | undefined; + /** + * @default 4 + */ + tries?: number; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using `resolver.setServers()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('dns'); + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default, and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module 'node:dns' { + export * from 'dns'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/dns/promises.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000..165b62b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,370 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `require('dns').promises` or `require('dns/promises')`. + * @since v10.6.0 + */ +declare module 'dns/promises' { + import { + LookupAddress, + LookupOneOptions, + LookupAllOptions, + LookupOptions, + AnyRecord, + CaaRecord, + MxRecord, + NaptrRecord, + SoaRecord, + SrvRecord, + ResolveWithTtlOptions, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + } from 'node:dns'; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dnsPromises.lookup()` does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses, and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the `Implementation considerations section` before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('dns'); + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * + * ```js + * const dnsPromises = require('dns').promises; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the DNS error codes. + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: 'A'): Promise; + function resolve(hostname: string, rrtype: 'AAAA'): Promise; + function resolve(hostname: string, rrtype: 'ANY'): Promise; + function resolve(hostname: string, rrtype: 'CAA'): Promise; + function resolve(hostname: string, rrtype: 'CNAME'): Promise; + function resolve(hostname: string, rrtype: 'MX'): Promise; + function resolve(hostname: string, rrtype: 'NAPTR'): Promise; + function resolve(hostname: string, rrtype: 'NS'): Promise; + function resolve(hostname: string, rrtype: 'PTR'): Promise; + function resolve(hostname: string, rrtype: 'SOA'): Promise; + function resolve(hostname: string, rrtype: 'SRV'): Promise; + function resolve(hostname: string, rrtype: 'TXT'): Promise; + function resolve(hostname: string, rrtype: string): Promise; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname`(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the DNS error codes. + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: ReadonlyArray): void; + /** + * Set the default value of `verbatim` in `dns.lookup()` and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` and `dnsPromises.setDefaultResultOrder()` have + * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.setDefaultResultOrder()` from the main thread won't affect the + * default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; + class Resolver { + constructor(options?: ResolverOptions); + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module 'node:dns/promises' { + export * from 'dns/promises'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/domain.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..f8dd26e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/domain.d.ts @@ -0,0 +1,169 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should**not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/domain.js) + */ +declare module 'domain' { + import EventEmitter = require('node:events'); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and lowlevel requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * const domain = require('domain'); + * const fs = require('fs'); + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module 'node:domain' { + export * from 'domain'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/events.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000..c1cef43 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/events.d.ts @@ -0,0 +1,651 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * const EventEmitter = require('events'); + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/events.js) + */ +declare module 'events' { + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + interface DOMEventTarget { + addEventListener( + eventName: string, + listener: (...args: any[]) => void, + opts?: { + once: boolean; + }, + ): any; + } + interface StaticEventEmitterOptions { + signal?: AbortSignal | undefined; + } + interface EventEmitter extends NodeJS.EventEmitter {} + /** + * The `EventEmitter` class is defined and exposed by the `events` module: + * + * ```js + * const EventEmitter = require('events'); + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter { + constructor(options?: EventEmitterOptions); + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * const { once, EventEmitter } = require('events'); + * + * async function run() { + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.log('error happened', err); + * } + * } + * + * run(); + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.log('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once( + emitter: NodeEventTarget, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * const { on, EventEmitter } = require('events'); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * const { on, EventEmitter } = require('events'); + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * @since v13.6.0, v12.16.0 + * @param eventName The name of the event being listened for + * @return that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string, + options?: StaticEventEmitterOptions, + ): AsyncIterableIterator; + /** + * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * ```js + * const { EventEmitter, listenerCount } = require('events'); + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * const { getEventListeners, EventEmitter } = require('events'); + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * getEventListeners(ee, 'foo'); // [listener] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * getEventListeners(et, 'foo'); // [listener] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `EventEmitter.setMaxListeners()` method allows the default limit to be + * modified (if eventTargets is empty) or modify the limit specified in every `EventTarget` | `EventEmitter` passed as arguments. + * The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * ```js + * EventEmitter.setMaxListeners(20); + * // Equivalent to + * EventEmitter.defaultMaxListeners = 20; + * + * const eventTarget = new EventTarget(); + * // Only way to increase limit for `EventTarget` instances + * // as these doesn't expose its own `setMaxListeners` method + * EventEmitter.setMaxListeners(20, eventTarget); + * ``` + * @since v15.3.0, v14.17.0 + */ + static setMaxListeners(n?: number, ...eventTargets: Array): void; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` + * events. Listeners installed using this symbol are called before the regular + * `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an + * `'error'` event is emitted, therefore the process will still crash if no + * regular `'error'` listener is installed. + */ + static readonly errorMonitor: unique symbol; + static readonly captureRejectionSymbol: unique symbol; + /** + * Sets or gets the default captureRejection value for all emitters. + */ + // TODO: These should be described using static getter/setter pairs: + static captureRejections: boolean; + static defaultMaxListeners: number; + } + import internal = require('node:events'); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + } + global { + namespace NodeJS { + interface EventEmitter { + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds the `listener` function to the end of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes the specified `listener` from the listener array for the event named`eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and_before_ the last listener finishes execution will + * not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')`listener is removed: + * + * ```js + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(event?: string | symbol): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: string | symbol): Function[]; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: string | symbol): Function[]; + /** + * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * const EventEmitter = require('events'); + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: string | symbol, ...args: any[]): boolean; + /** + * Returns the number of listeners listening to the event named `eventName`. + * @since v3.2.0 + * @param eventName The name of the event being listened for + */ + listenerCount(eventName: string | symbol): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the_beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * const EventEmitter = require('events'); + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array; + } + } + } + export = EventEmitter; +} +declare module 'node:events' { + import events = require('events'); + export = events; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/fs.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000..c220c03 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/fs.d.ts @@ -0,0 +1,3869 @@ +/** + * The `fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/fs.js) + */ +declare module 'fs' { + import * as stream from 'node:stream'; + import { Abortable, EventEmitter } from 'node:events'; + import { URL } from 'node:url'; + import * as promises from 'node:fs/promises'; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | 'buffer' + | { + encoding: 'buffer'; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat} and {@link fstat} and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats {} + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be resolved after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be resolved with an `fs.Dirent`, or `null`if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'close', listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'close', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'close', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number | null): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number | null): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function stat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + } + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + } + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + } + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + } + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + } + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function fstat(fd: number, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + } + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function lstat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If + * the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. + * + * Relative targets are relative to the link’s parent directory. + * + * ```js + * import { symlink } from 'fs'; + * + * symlink('./mew', './example/mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` in the `example` which points + * to `mew` in the same directory: + * + * ```bash + * $ tree example/ + * example/ + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + */ + export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = 'dir' | 'file' | 'junction'; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..` and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + function native(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode soperations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. + * + * ```js + * import { mkdir } from 'fs'; + * + * // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. + * mkdir('/tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path?: string) => void): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs'; + * + * mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`require('path').sep`). + * + * ```js + * import { tmpdir } from 'os'; + * import { mkdtemp } from 'fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | 'buffer' + | { + encoding: 'buffer'; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer', + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | 'buffer' + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open(path: PathLike, flags: OpenMode, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, flags: OpenMode, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + /** + * Write `buffer` to the file specified by `fd`. If `buffer` is a normal object, it + * must have an own `toString` function property. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write(fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write(fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @return The number of bytes written. + */ + export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): number; + export type ReadPosition = number | bigint; + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadAsyncOptions extends ReadSyncOptions { + buffer?: TBuffer; + } + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadAsyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void + ): void; + export function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadAsyncOptions + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number + ): Promise<{ + bytesRead: number; + buffer: NodeJS.ArrayBufferView; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: ReadPosition | null): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile(path: PathOrFileDescriptor, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Buffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): string | Buffer; + export type WriteFileOptions = + | (ObjectEncodingOptions & + Abortable & { + mode?: Mode | undefined; + flag?: string | undefined; + }) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * If `data` is a plain object, it must have an own (not inherited) `toString`function property. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise; + } + /** + * Returns `undefined`. + * + * If `data` is a plain object, it must have an own (not inherited) `toString`function property. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile(path: PathOrFileDescriptor, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync(path: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: (curr: Stats, prev: Stats) => void + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: (curr: BigIntStats, prev: BigIntStats) => void + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | 'buffer' | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export type WatchEventType = 'rename' | 'change'; + export type WatchListener = (event: WatchEventType, filename: T) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of`eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer', + listener?: WatchListener + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options?: WatchOptions | BufferEncoding | null, listener?: WatchListener): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: WatchOptions | string, listener?: WatchListener): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won’t be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. Check `File access constants` for possible values + * of `mode`. It is possible to create a mask consisting of the bitwise OR of + * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file exists in the current directory, and if it is writable. + * access(file, constants.F_OK | constants.W_OK, (err) => { + * if (err) { + * console.error( + * `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`); + * } else { + * console.log(`${file} exists, and it is writable`); + * } + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. Check `File access constants` for + * possible values of `mode`. It is possible to create a mask consisting of + * the bitwise OR of two or more values + * (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + /** + * @default false + */ + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + } + interface ReadStreamOptions extends StreamOptions { + end?: number | undefined; + } + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for`open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than replacing + * it may require the `flags` option to be set to `r+` rather than the default `w`. + * The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev` and `close`. Overriding `write()`without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | StreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + */ + export function writev(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function writev( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: ReadonlyArray, position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + */ + export function readv(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function readv( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: ReadonlyArray, position?: number): number; + export interface OpenDirOptions { + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir(path: PathLike, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + export interface CopyOptions { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp(source: string, destination: string, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function cp(source: string, destination: string, opts: CopyOptions, callback: (err: NodeJS.ErrnoException | null) => void): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string, destination: string, opts?: CopyOptions): void; +} +declare module 'node:fs' { + export * from 'fs'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/fs/promises.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000..f6c77d3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1091 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module 'fs/promises' { + import { Abortable } from 'node:events'; + import { Stream } from 'node:stream'; + import { + Stats, + BigIntStats, + StatOptions, + WriteVResult, + ReadVResult, + PathLike, + RmDirOptions, + RmOptions, + MakeDirectoryOptions, + Dirent, + OpenDirOptions, + Dir, + ObjectEncodingOptions, + BufferEncodingOption, + OpenMode, + Mode, + WatchOptions, + WatchEventType, + CopyOptions, + ReadStream, + WriteStream, + } from 'node:fs'; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: number | null; + } + interface CreateReadStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than replacing + * it may require the `flags` `open` option to be set to `r+` rather than the + * default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fufills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read(buffer: T, offset?: number | null, length?: number | null, position?: number | null): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a`filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: { + encoding?: null | undefined; + flag?: OpenMode | undefined; + } | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + } + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then resolves the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object, or an + * object with an own `toString` function + * property. The promise is resolved with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode & Abortable) | BufferEncoding | null): Promise; + /** + * Write `buffer` to the file. + * + * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. + * + * The promise is resolved with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). For this + * scenario, use `fs.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param [offset=0] The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength] The number of bytes from `buffer` to write. + * @param position The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. + * See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is resolved with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be resolved (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param position The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: ReadonlyArray, position?: number): Promise; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param position The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: ReadonlyArray, position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. Check `File access constants` for possible values + * of `mode`. It is possible to create a mask consisting of the bitwise OR of + * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * If the accessibility check is successful, the promise is resolved with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access } from 'fs/promises'; + * import { constants } from 'fs'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { constants } from 'fs'; + * import { copyFile } from 'fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * resolved with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. Windows junction points require the destination path + * to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. + * @since v10.0.0 + * @param [type='file'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs/promises'; + * + * try { + * await mkdtemp(path.join(os.tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing + * platform-specific path separator + * (`require('path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a `Buffer`, or, an object with an own (not inherited)`toString` function property. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs/promises'; + * import { Buffer } from 'buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: string | NodeJS.ArrayBufferView | Iterable | AsyncIterable | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | (ObjectEncodingOptions & + Abortable & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('fs/promises'); + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer' + ): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: WatchOptions | string): AsyncIterable> | AsyncIterable>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string, destination: string, opts?: CopyOptions): Promise; +} +declare module 'node:fs/promises' { + export * from 'fs/promises'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/globals.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..4533f1c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/globals.d.ts @@ -0,0 +1,284 @@ +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + + stackTraceLimit: number; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + +// For backwards compability +interface NodeRequire extends NodeJS.Require { } +interface RequireResolve extends NodeJS.RequireResolve { } +interface NodeModule extends NodeJS.Module { } + +declare var process: NodeJS.Process; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare var require: NodeRequire; +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +/** + * Only available if `--expose-gc` is passed to the process. + */ +declare var gc: undefined | (() => void); + +//#region borrowed +// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib +/** A controller object that allows you to abort one or more DOM requests as and when desired. */ +interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(): void; +} + +/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ +interface AbortSignal { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; + // TODO: Add abort() static +}; +//#endregion borrowed + +//#region ArrayLike.at() +interface RelativeIndexable { + /** + * Takes an integer value and returns the item at that index, + * allowing for positive and negative integers. + * Negative integers count back from the last item in the array. + */ + at(index: number): T | undefined; +} +interface String extends RelativeIndexable {} +interface Array extends RelativeIndexable {} +interface Int8Array extends RelativeIndexable {} +interface Uint8Array extends RelativeIndexable {} +interface Uint8ClampedArray extends RelativeIndexable {} +interface Int16Array extends RelativeIndexable {} +interface Uint16Array extends RelativeIndexable {} +interface Int32Array extends RelativeIndexable {} +interface Uint32Array extends RelativeIndexable {} +interface Float32Array extends RelativeIndexable {} +interface Float64Array extends RelativeIndexable {} +interface BigInt64Array extends RelativeIndexable {} +interface BigUint64Array extends RelativeIndexable {} +//#endregion ArrayLike.at() end + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface CallSite { + /** + * Value of "this" + */ + getThis(): unknown; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface RefCounted { + ref(): this; + unref(): this; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined; }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + '.js': (m: Module, filename: string) => any; + '.json': (m: Module, filename: string) => any; + '.node': (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since 14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since 11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/globals.global.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/globals.global.d.ts new file mode 100644 index 0000000..ef1198c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/node_modules/mathjs/examples/node_modules/@types/node/http.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000..bb3a93c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/http.d.ts @@ -0,0 +1,1396 @@ +/** + * To use the HTTP server and client one must `require('http')`. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```js + * { 'content-length': '123', + * 'content-type': 'text/plain', + * 'connection': 'keep-alive', + * 'host': 'mysite.com', + * 'accept': '*' } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders`list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'mysite.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/http.js) + */ +declare module 'http' { + import * as stream from 'node:stream'; + import { URL } from 'node:url'; + import { TcpSocketConnectOpts, Socket, Server as NetServer, LookupFunction } from 'node:net'; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + 'accept-language'?: string | undefined; + 'accept-patch'?: string | undefined; + 'accept-ranges'?: string | undefined; + 'access-control-allow-credentials'?: string | undefined; + 'access-control-allow-headers'?: string | undefined; + 'access-control-allow-methods'?: string | undefined; + 'access-control-allow-origin'?: string | undefined; + 'access-control-expose-headers'?: string | undefined; + 'access-control-max-age'?: string | undefined; + 'access-control-request-headers'?: string | undefined; + 'access-control-request-method'?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + 'alt-svc'?: string | undefined; + authorization?: string | undefined; + 'cache-control'?: string | undefined; + connection?: string | undefined; + 'content-disposition'?: string | undefined; + 'content-encoding'?: string | undefined; + 'content-language'?: string | undefined; + 'content-length'?: string | undefined; + 'content-location'?: string | undefined; + 'content-range'?: string | undefined; + 'content-type'?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + 'if-match'?: string | undefined; + 'if-modified-since'?: string | undefined; + 'if-none-match'?: string | undefined; + 'if-unmodified-since'?: string | undefined; + 'last-modified'?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + 'proxy-authenticate'?: string | undefined; + 'proxy-authorization'?: string | undefined; + 'public-key-pins'?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + 'retry-after'?: string | undefined; + 'sec-websocket-accept'?: string | undefined; + 'sec-websocket-extensions'?: string | undefined; + 'sec-websocket-key'?: string | undefined; + 'sec-websocket-protocol'?: string | undefined; + 'sec-websocket-version'?: string | undefined; + 'set-cookie'?: string[] | undefined; + 'strict-transport-security'?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + 'transfer-encoding'?: string | undefined; + upgrade?: string | undefined; + 'user-agent'?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + 'www-authenticate'?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict {} + interface ClientRequestArgs { + signal?: AbortSignal | undefined; + protocol?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + family?: number | undefined; + port?: number | string | null | undefined; + defaultPort?: number | string | undefined; + localAddress?: string | undefined; + socketPath?: string | undefined; + /** + * @default 8192 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + headers?: OutgoingHttpHeaders | undefined; + auth?: string | null | undefined; + agent?: Agent | boolean | undefined; + _defaultAgent?: Agent | undefined; + timeout?: number | undefined; + setHost?: boolean | undefined; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) | undefined; + lookup?: LookupFunction | undefined; + } + interface ServerOptions { + IncomingMessage?: typeof IncomingMessage | undefined; + ServerResponse?: typeof ServerResponse | undefined; + /** + * Optionally overrides the value of + * `--max-http-header-size` for requests received by this server, i.e. + * the maximum length of request headers in bytes. + * @default 8192 + */ + maxHeaderSize?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when true. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + } + type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; + /** + * @since v0.1.17 + */ + class Server extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * In case of inactivity, the rules defined in `server.timeout` apply. However, + * that inactivity based timeout would still allow the connection to be kept open + * if the headers are being sent very slowly (by default, up to a byte per 2 + * minutes). In order to prevent this, whenever header data arrives an additional + * check is made that more than `server.headersTimeout` milliseconds has not + * passed since the connection was established. If the check fails, a `'timeout'`event is emitted on the server object, and (by default) the socket is destroyed. + * See `server.timeout` for more information on how timeout behavior can be + * customized. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Socket) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'checkContinue', listener: RequestListener): this; + addListener(event: 'checkExpectation', listener: RequestListener): this; + addListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + addListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: RequestListener): this; + addListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + emit(event: string, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Socket): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'checkContinue', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'checkExpectation', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean; + emit(event: 'connect', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + emit(event: 'request', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'upgrade', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Socket) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'checkContinue', listener: RequestListener): this; + on(event: 'checkExpectation', listener: RequestListener): this; + on(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'request', listener: RequestListener): this; + on(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Socket) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'checkContinue', listener: RequestListener): this; + once(event: 'checkExpectation', listener: RequestListener): this; + once(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + once(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once(event: 'request', listener: RequestListener): this; + once(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Socket) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'checkContinue', listener: RequestListener): this; + prependListener(event: 'checkExpectation', listener: RequestListener): this; + prependListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: RequestListener): this; + prependListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'checkContinue', listener: RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: RequestListener): this; + prependOnceListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from + * the perspective of the participants of HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: IncomingMessage; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Aliases of `outgoingMessage.socket` + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value for the header object. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | ReadonlyArray): this; + /** + * Gets the value of HTTP header with the given name. If such a name doesn't + * exist in message, it will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript Object. This means that + * typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.0.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array of names of headers of the outgoing outgoingMessage. All + * names are lowercase. + * @since v8.0.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v8.0.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers are **only** be emitted if the message is chunked encoded. If not, + * the trailer will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header fields in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Compulsorily flushes the message headers + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + constructor(req: IncomingMessage); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends a HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on`Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain' + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * does not check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.1.30 + */ + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + * + * Node.js does not check whether Content-Length and the length of the + * body which has been transmitted are equal or not. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * Whether the request is send through a reused socket. + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + * @default 2000 + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: 'abort', listener: () => void): this; + addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'continue', listener: () => void): this; + addListener(event: 'information', listener: (info: InformationEvent) => void): this; + addListener(event: 'response', listener: (response: IncomingMessage) => void): this; + addListener(event: 'socket', listener: (socket: Socket) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: 'abort', listener: () => void): this; + on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'continue', listener: () => void): this; + on(event: 'information', listener: (info: InformationEvent) => void): this; + on(event: 'response', listener: (response: IncomingMessage) => void): this; + on(event: 'socket', listener: (socket: Socket) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: 'abort', listener: () => void): this; + once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'continue', listener: () => void): this; + once(event: 'information', listener: (info: InformationEvent) => void): this; + once(event: 'response', listener: (response: IncomingMessage) => void): this; + once(event: 'socket', listener: (socket: Socket) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: 'abort', listener: () => void): this; + prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'continue', listener: () => void): this; + prependListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependListener(event: 'socket', listener: (socket: Socket) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: 'abort', listener: () => void): this; + prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'continue', listener: () => void): this; + prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0 - Check `message.destroyed` from [stream.Readable](https://nodejs.org/dist/latest-v17.x/docs/api/stream.html#class-streamreadable). + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST' + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket`. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with '; '. + * * For all other headers, the values are joined together with ', '. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(request.url, `http://${request.headers.host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and`request.headers.host` is `'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.headers.host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends Partial { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: 'fifo' | 'lifo' | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * @since v0.3.4 + */ + class Agent { + /** + * By default set to 256\. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * @since v0.1.13 + */ + function createServer(requestListener?: RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: RequestListener): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const http = require('http'); + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!' + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData) + * } + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request itself. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the + * response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!' + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; +} +declare module 'node:http' { + export * from 'http'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/http2.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..1166c90 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2100 @@ +/** + * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It + * can be accessed using: + * + * ```js + * const http2 = require('http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/http2.js) + */ +declare module 'http2' { + import EventEmitter = require('node:events'); + import * as fs from 'node:fs'; + import * as net from 'node:net'; + import * as stream from 'node:stream'; + import * as tls from 'node:tls'; + import * as url from 'node:url'; + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http'; + export { OutgoingHttpHeaders } from 'node:http'; + export interface IncomingHttpStatusHeader { + ':status'?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ':path'?: string | undefined; + ':method'?: string | undefined; + ':authority'?: string | undefined; + ':scheme'?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set the `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session; + /** + * Provides miscellaneous information about the current state of the`Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: 'aborted', listener: () => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'streamClosed', listener: (code: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'wantTrailers', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'aborted'): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'frameError', frameType: number, errorCode: number): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; + emit(event: 'streamClosed', code: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'trailers', trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'wantTrailers'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'aborted', listener: () => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: 'streamClosed', listener: (code: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'wantTrailers', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'aborted', listener: () => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: 'streamClosed', listener: (code: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'wantTrailers', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'aborted', listener: () => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'streamClosed', listener: (code: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'wantTrailers', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'aborted', listener: () => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'streamClosed', listener: (code: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'wantTrailers', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: 'continue', listener: () => {}): this; + addListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'continue'): boolean; + emit(event: 'headers', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: 'push', headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'response', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'continue', listener: () => {}): this; + on(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'continue', listener: () => {}): this; + once(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'continue', listener: () => {}): this; + prependListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'continue', listener: () => {}): this; + prependOnceListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + /** + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD(fd: number | fs.promises.FileHandle, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.log(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate`304` response: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: NodeJS.ArrayBufferView, callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + /** + * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings(settings: Settings): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: 'localSettings', listener: (settings: Settings) => void): this; + addListener(event: 'ping', listener: () => void): this; + addListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'frameError', frameType: number, errorCode: number, streamID: number): boolean; + emit(event: 'goaway', errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: 'localSettings', settings: Settings): boolean; + emit(event: 'ping'): boolean; + emit(event: 'remoteSettings', settings: Settings): boolean; + emit(event: 'timeout'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: 'localSettings', listener: (settings: Settings) => void): this; + on(event: 'ping', listener: () => void): this; + on(event: 'remoteSettings', listener: (settings: Settings) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: 'localSettings', listener: (settings: Settings) => void): this; + once(event: 'ping', listener: () => void): this; + once(event: 'remoteSettings', listener: (settings: Settings) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'ping', listener: () => void): this; + prependListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'ping', listener: () => void): this; + prependOnceListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + addListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: 'origin', listener: (origins: string[]) => void): this; + addListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'altsvc', alt: string, origin: string, stream: number): boolean; + emit(event: 'origin', origins: ReadonlyArray): boolean; + emit(event: 'connect', session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + on(event: 'origin', listener: (origins: string[]) => void): this; + on(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + once(event: 'origin', listener: (origins: string[]) => void): this; + once(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: 'origin', listener: (origins: string[]) => void): this; + prependListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: 'origin', listener: (origins: string[]) => void): this; + prependOnceListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'connect', session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + selectPadding?(frameLen: number, maxFrameLen: number): number; + createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: 'http:' | 'https:' | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'unknownProtocol', socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor(stream: ServerHttp2Stream, headers: IncomingHttpHeaders, options: stream.ReadableOptions, rawHeaders: ReadonlyArray); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns`'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'aborted', hadError: boolean, code: number): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'end'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 request object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ''; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | ReadonlyArray): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses_must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session`instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

    Hello World

    '); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem') + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

    Hello World

    '); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect(authority: string | url.URL, listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void + ): ClientHttp2Session; +} +declare module 'node:http2' { + export * from 'http2'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/https.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..9abd7b1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/https.d.ts @@ -0,0 +1,391 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/https.js) + */ +declare module 'https' { + import { Duplex } from 'node:stream'; + import * as tls from 'node:tls'; + import * as http from 'node:http'; + import { URL } from 'node:url'; + type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = http.RequestOptions & + tls.SecureContextOptions & { + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor(options: ServerOptions, requestListener?: http.RequestListener); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Duplex) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'checkContinue', listener: http.RequestListener): this; + addListener(event: 'checkExpectation', listener: http.RequestListener): this; + addListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + addListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: http.RequestListener): this; + addListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + emit(event: string, ...args: any[]): boolean; + emit(event: 'keylog', line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: 'secureConnection', tlsSocket: tls.TLSSocket): boolean; + emit(event: 'tlsClientError', err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Duplex): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'checkContinue', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'checkExpectation', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: Duplex): boolean; + emit(event: 'connect', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + emit(event: 'request', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'upgrade', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Duplex) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'checkContinue', listener: http.RequestListener): this; + on(event: 'checkExpectation', listener: http.RequestListener): this; + on(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + on(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + on(event: 'request', listener: http.RequestListener): this; + on(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Duplex) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'checkContinue', listener: http.RequestListener): this; + once(event: 'checkExpectation', listener: http.RequestListener): this; + once(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + once(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: 'request', listener: http.RequestListener): this; + once(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Duplex) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'checkContinue', listener: http.RequestListener): this; + prependListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + prependListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: http.RequestListener): this; + prependListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Duplex) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'checkContinue', listener: http.RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependOnceListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: http.RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample' + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer(requestListener?: http.RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const https = require('https'); + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET' + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * const tls = require('tls'); + * const https = require('https'); + * const crypto = require('crypto'); + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha25 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * const https = require('https'); + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + let globalAgent: Agent; +} +declare module 'node:https' { + export * from 'https'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/index.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..ae3e4cc --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/index.d.ts @@ -0,0 +1,129 @@ +// Type definitions for non-npm package Node.js 17.0 +// Project: https://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Chigozirim C. +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Hannes Magnusson +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Samuel Ainsworth +// Kyle Uehlein +// Thanik Bhongbhibhat +// Marcin Kopacz +// Trivikram Kamat +// Junxiao Shi +// Ilia Baryshnikov +// ExE Boss +// Piotr Błażejewicz +// Anna Henningsen +// Victor Perin +// Yongsheng Zhang +// NodeJS Contributors +// Linus Unnebäck +// wafuwafu13 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * 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. + */ + +// NOTE: These definitions support NodeJS and TypeScript 3.7+. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/node_modules/mathjs/examples/node_modules/@types/node/inspector.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..7b9598c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2744 @@ +// tslint:disable-next-line:dt-header +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +// tslint:disable:max-line-length + +/** + * The `inspector` module provides an API for interacting with the V8 inspector. + * + * It can be accessed using: + * + * ```js + * const inspector = require('inspector'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + * @since v8.0.0 + */ + connect(): void; + /** + * Connects a session to the main thread inspector back-end. An exception will + * be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + /** + * Immediately close the session. All pending message callbacks will be called + * with an error. `session.connect()` will need to be called to be able to send + * messages again. Reconnected session will lose all inspector state, such as + * enabled agents or configured breakpoints. + * @since v8.0.0 + */ + disconnect(): void; + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8\. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + // Events + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + } + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the `security warning` regarding the `host`parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + */ + function open(port?: number, host?: string, wait?: boolean): void; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help see https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help see https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; +} +declare module 'node:inspector' { + import EventEmitter = require('inspector'); + export = EventEmitter; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/module.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..d83aec9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/module.d.ts @@ -0,0 +1,114 @@ +/** + * @since v0.3.7 + */ +declare module 'module' { + import { URL } from 'node:url'; + namespace Module { + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * const fs = require('fs'); + * const assert = require('assert'); + * const { syncBuiltinESMExports } = require('module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + */ + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + /** + * Given a line number and column number in the generated source file, returns + * an object representing the position in the original file. The object returned + * consists of the following keys: + */ + findEntry(line: number, column: number): SourceMapping; + } + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static Module: typeof Module; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + url: string; + /** + * @experimental + * This feature is only available with the `--experimental-import-meta-resolve` + * command flag enabled. + * + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * @param specified The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. If none + * is specified, the value of `import.meta.url` is used as the default. + */ + resolve?(specified: string, parent?: string | URL): Promise; + } + } + export = Module; +} +declare module 'node:module' { + import module = require('module'); + export = module; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/net.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..f24b16c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/net.d.ts @@ -0,0 +1,784 @@ +/** + * > Stability: 2 - Stable + * + * The `net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * const net = require('net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/net.js) + */ +declare module 'net' { + import * as stream from 'node:stream'; + import { Abortable, EventEmitter } from 'node:events'; + import * as dns from 'node:dns'; + type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will_not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`,`socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: (hadError: boolean) => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'data', listener: (data: Buffer) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'timeout', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close', hadError: boolean): boolean; + emit(event: 'connect'): boolean; + emit(event: 'data', data: Buffer): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'lookup', err: Error, address: string, family: string | number, host: string): boolean; + emit(event: 'ready'): boolean; + emit(event: 'timeout'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: (hadError: boolean) => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'data', listener: (data: Buffer) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'timeout', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: (hadError: boolean) => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'data', listener: (data: Buffer) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'timeout', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: (hadError: boolean) => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'data', listener: (data: Buffer) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: (hadError: boolean) => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'data', listener: (data: Buffer) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + } + interface ListenOptions extends Abortable { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.log('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will_not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Socket) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Socket): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Socket) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Socket) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Socket) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + } + type IPVersion = 'ipv4' | 'ipv6'; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of an TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('net'); + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```console + * $ telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```console + * $ nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Tests if input is an IP address. Returns `0` for invalid strings, + * returns `4` for IP version 4 addresses, and returns `6` for IP version 6 + * addresses. + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if input is a version 4 IP address, otherwise returns `false`. + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if input is a version 6 IP address, otherwise returns `false`. + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + } +} +declare module 'node:net' { + export * from 'net'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/os.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..a618e91 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/os.d.ts @@ -0,0 +1,455 @@ +/** + * The `os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/os.js) + */ +declare module 'os' { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: 'IPv4'; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: 'IPv6'; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20 + * } + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a `SystemError` if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: 'buffer' }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. + * + * The return value is equivalent to `process.arch`. + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform. The value is set + * at compile time. Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): 'BE' | 'LE'; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module 'node:os' { + export * from 'os'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/package.json b/node_modules/mathjs/examples/node_modules/@types/node/package.json new file mode 100644 index 0000000..7662dff --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/package.json @@ -0,0 +1,220 @@ +{ + "name": "@types/node", + "version": "17.0.23", + "description": "TypeScript definitions for Node.js", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "url": "https://github.com/Microsoft", + "githubUsername": "Microsoft" + }, + { + "name": "DefinitelyTyped", + "url": "https://github.com/DefinitelyTyped", + "githubUsername": "DefinitelyTyped" + }, + { + "name": "Alberto Schiabel", + "url": "https://github.com/jkomyno", + "githubUsername": "jkomyno" + }, + { + "name": "Alvis HT Tang", + "url": "https://github.com/alvis", + "githubUsername": "alvis" + }, + { + "name": "Andrew Makarov", + "url": "https://github.com/r3nya", + "githubUsername": "r3nya" + }, + { + "name": "Benjamin Toueg", + "url": "https://github.com/btoueg", + "githubUsername": "btoueg" + }, + { + "name": "Chigozirim C.", + "url": "https://github.com/smac89", + "githubUsername": "smac89" + }, + { + "name": "David Junger", + "url": "https://github.com/touffy", + "githubUsername": "touffy" + }, + { + "name": "Deividas Bakanas", + "url": "https://github.com/DeividasBakanas", + "githubUsername": "DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "url": "https://github.com/eyqs", + "githubUsername": "eyqs" + }, + { + "name": "Hannes Magnusson", + "url": "https://github.com/Hannes-Magnusson-CK", + "githubUsername": "Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "url": "https://github.com/hoo29", + "githubUsername": "hoo29" + }, + { + "name": "Kelvin Jin", + "url": "https://github.com/kjin", + "githubUsername": "kjin" + }, + { + "name": "Klaus Meinhardt", + "url": "https://github.com/ajafff", + "githubUsername": "ajafff" + }, + { + "name": "Lishude", + "url": "https://github.com/islishude", + "githubUsername": "islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "url": "https://github.com/mwiktorczyk", + "githubUsername": "mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "url": "https://github.com/mohsen1", + "githubUsername": "mohsen1" + }, + { + "name": "Nicolas Even", + "url": "https://github.com/n-e", + "githubUsername": "n-e" + }, + { + "name": "Nikita Galkin", + "url": "https://github.com/galkin", + "githubUsername": "galkin" + }, + { + "name": "Parambir Singh", + "url": "https://github.com/parambirs", + "githubUsername": "parambirs" + }, + { + "name": "Sebastian Silbermann", + "url": "https://github.com/eps1lon", + "githubUsername": "eps1lon" + }, + { + "name": "Simon Schick", + "url": "https://github.com/SimonSchick", + "githubUsername": "SimonSchick" + }, + { + "name": "Thomas den Hollander", + "url": "https://github.com/ThomasdenH", + "githubUsername": "ThomasdenH" + }, + { + "name": "Wilco Bakker", + "url": "https://github.com/WilcoBakker", + "githubUsername": "WilcoBakker" + }, + { + "name": "wwwy3y3", + "url": "https://github.com/wwwy3y3", + "githubUsername": "wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "url": "https://github.com/samuela", + "githubUsername": "samuela" + }, + { + "name": "Kyle Uehlein", + "url": "https://github.com/kuehlein", + "githubUsername": "kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "url": "https://github.com/bhongy", + "githubUsername": "bhongy" + }, + { + "name": "Marcin Kopacz", + "url": "https://github.com/chyzwar", + "githubUsername": "chyzwar" + }, + { + "name": "Trivikram Kamat", + "url": "https://github.com/trivikr", + "githubUsername": "trivikr" + }, + { + "name": "Junxiao Shi", + "url": "https://github.com/yoursunny", + "githubUsername": "yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "url": "https://github.com/qwelias", + "githubUsername": "qwelias" + }, + { + "name": "ExE Boss", + "url": "https://github.com/ExE-Boss", + "githubUsername": "ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "url": "https://github.com/peterblazejewicz", + "githubUsername": "peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "url": "https://github.com/addaleax", + "githubUsername": "addaleax" + }, + { + "name": "Victor Perin", + "url": "https://github.com/victorperin", + "githubUsername": "victorperin" + }, + { + "name": "Yongsheng Zhang", + "url": "https://github.com/ZYSzys", + "githubUsername": "ZYSzys" + }, + { + "name": "NodeJS Contributors", + "url": "https://github.com/NodeJS", + "githubUsername": "NodeJS" + }, + { + "name": "Linus Unnebäck", + "url": "https://github.com/LinusU", + "githubUsername": "LinusU" + }, + { + "name": "wafuwafu13", + "url": "https://github.com/wafuwafu13", + "githubUsername": "wafuwafu13" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "31d9626c2d3ccc7c4b4e0d91e1ed56f52997cd7409e001330de7b00feb84ad8b", + "typeScriptVersion": "3.9" +} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/@types/node/path.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..c19dce8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/path.d.ts @@ -0,0 +1,180 @@ +declare module 'path/posix' { + import path = require('path'); + export = path; +} +declare module 'path/win32' { + import path = require('path'); + export = path; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * const path = require('path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/path.js) + */ +declare module 'path' { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + isAbsolute(p: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + parse(p: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + format(pP: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module 'node:path' { + import path = require('path'); + export = path; +} +declare module 'node:path/posix' { + import path = require('path/posix'); + export = path; +} +declare module 'node:path/win32' { + import path = require('path/win32'); + export = path; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/perf_hooks.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..7d1e0b3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,557 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * + * ```js + * const { PerformanceObserver, performance } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/perf_hooks.js) + */ +declare module 'perf_hooks' { + import { AsyncResource } from 'node:async_hooks'; + type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: EventLoopUtilization) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()`. + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using + * `perf_hooks.createHistogram()` that will record runtime durations in + * nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string, options?: MarkOptions): void; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark?: string, endMark?: string): void; + measure(name: string, options: MeasureOptions): void; + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + } + interface PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0 + * * } + * * ] + * + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0 + * * } + * * ] + * + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called three times synchronously. `list` contains one item. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: ReadonlyArray; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + } + ): void; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * + * ## Examples + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * const { monitorEventLoopDelay } = require('perf_hooks'); + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; +} +declare module 'node:perf_hooks' { + export * from 'perf_hooks'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/process.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..24bbfba --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/process.d.ts @@ -0,0 +1,1481 @@ +declare module 'process' { + import * as tty from 'node:tty'; + import { Worker } from 'node:worker_threads'; + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; + type Signals = + | 'SIGABRT' + | 'SIGALRM' + | 'SIGBUS' + | 'SIGCHLD' + | 'SIGCONT' + | 'SIGFPE' + | 'SIGHUP' + | 'SIGILL' + | 'SIGINT' + | 'SIGIO' + | 'SIGIOT' + | 'SIGKILL' + | 'SIGPIPE' + | 'SIGPOLL' + | 'SIGPROF' + | 'SIGPWR' + | 'SIGQUIT' + | 'SIGSEGV' + | 'SIGSTKFLT' + | 'SIGSTOP' + | 'SIGSYS' + | 'SIGTERM' + | 'SIGTRAP' + | 'SIGTSTP' + | 'SIGTTIN' + | 'SIGTTOU' + | 'SIGUNUSED' + | 'SIGURG' + | 'SIGUSR1' + | 'SIGUSR2' + | 'SIGVTALRM' + | 'SIGWINCH' + | 'SIGXCPU' + | 'SIGXFSZ' + | 'SIGBREAK' + | 'SIGLOST' + | 'SIGINFO'; + type UncaughtExceptionOrigin = 'uncaughtException' | 'unhandledRejection'; + type MultipleResolveType = 'resolve' | 'reject'; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume the the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: unknown) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + openStdin(): Socket; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```console + * $ node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```console + * $ node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information' + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, the `options` argument is ignored. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```console + * $ node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread’s `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and`process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit_before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. + */ + exit(code?: number): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @since v0.11.8 + */ + exitCode?: number | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid(): number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid(id: number | string): void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid(): number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid(id: number | string): void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid(): number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid(id: number | string): void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid(): number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid(id: number | string): void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups(): number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups(groups: ReadonlyArray): void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '11.13.0', + * v8: '7.0.276.38-node.18', + * uv: '1.27.0', + * zlib: '1.2.11', + * brotli: '1.0.7', + * ares: '1.15.0', + * modules: '67', + * nghttp2: '1.34.0', + * napi: '4', + * llhttp: '1.1.1', + * openssl: '1.1.1b', + * cldr: '34.0', + * icu: '63.1', + * tz: '2018e', + * unicode: '11.0' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns an `Object` containing the JavaScript + * representation of the configure options used to compile the current Node.js + * executable. This is the same as the `config.gypi` file that was produced when + * running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_dtrace: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * + * The `process.config` property is **not** read-only and there are existing + * modules in the ecosystem that are known to extend, modify, or entirely replace + * the value of `process.config`. + * + * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made + * read-only in a future release. + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. + * + * ```js + * import { arch } from 'process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: string; + /** + * The `process.platform` property returns a string identifying the operating + * system platform on which the Node.js process is running. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Erbium', + * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be`undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + swallowErrors?: boolean | undefined; + }, + callback?: (error: Error | null) => void + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC + * channel is connected and will return `false` after`process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic + * reports for the current process. Additional documentation is available in the `report documentation`. + * @since v11.8.0 + */ + report?: ProcessReport | undefined; + /** + * ```js + * import { resourceUsage } from 'process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /* EventEmitter */ + addListener(event: 'beforeExit', listener: BeforeExitListener): this; + addListener(event: 'disconnect', listener: DisconnectListener): this; + addListener(event: 'exit', listener: ExitListener): this; + addListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + addListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + addListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + addListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + addListener(event: 'warning', listener: WarningListener): this; + addListener(event: 'message', listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + addListener(event: 'worker', listener: WorkerListener): this; + emit(event: 'beforeExit', code: number): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'exit', code: number): boolean; + emit(event: 'rejectionHandled', promise: Promise): boolean; + emit(event: 'uncaughtException', error: Error): boolean; + emit(event: 'uncaughtExceptionMonitor', error: Error): boolean; + emit(event: 'unhandledRejection', reason: unknown, promise: Promise): boolean; + emit(event: 'warning', warning: Error): boolean; + emit(event: 'message', message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit(event: 'multipleResolves', type: MultipleResolveType, promise: Promise, value: unknown): this; + emit(event: 'worker', listener: WorkerListener): this; + on(event: 'beforeExit', listener: BeforeExitListener): this; + on(event: 'disconnect', listener: DisconnectListener): this; + on(event: 'exit', listener: ExitListener): this; + on(event: 'rejectionHandled', listener: RejectionHandledListener): this; + on(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + on(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + on(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + on(event: 'warning', listener: WarningListener): this; + on(event: 'message', listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: 'multipleResolves', listener: MultipleResolveListener): this; + on(event: 'worker', listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'beforeExit', listener: BeforeExitListener): this; + once(event: 'disconnect', listener: DisconnectListener): this; + once(event: 'exit', listener: ExitListener): this; + once(event: 'rejectionHandled', listener: RejectionHandledListener): this; + once(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + once(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + once(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + once(event: 'warning', listener: WarningListener): this; + once(event: 'message', listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: 'multipleResolves', listener: MultipleResolveListener): this; + once(event: 'worker', listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependListener(event: 'disconnect', listener: DisconnectListener): this; + prependListener(event: 'exit', listener: ExitListener): this; + prependListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependListener(event: 'warning', listener: WarningListener): this; + prependListener(event: 'message', listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependListener(event: 'worker', listener: WorkerListener): this; + prependOnceListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependOnceListener(event: 'disconnect', listener: DisconnectListener): this; + prependOnceListener(event: 'exit', listener: ExitListener): this; + prependOnceListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependOnceListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependOnceListener(event: 'warning', listener: WarningListener): this; + prependOnceListener(event: 'message', listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependOnceListener(event: 'worker', listener: WorkerListener): this; + listeners(event: 'beforeExit'): BeforeExitListener[]; + listeners(event: 'disconnect'): DisconnectListener[]; + listeners(event: 'exit'): ExitListener[]; + listeners(event: 'rejectionHandled'): RejectionHandledListener[]; + listeners(event: 'uncaughtException'): UncaughtExceptionListener[]; + listeners(event: 'uncaughtExceptionMonitor'): UncaughtExceptionListener[]; + listeners(event: 'unhandledRejection'): UnhandledRejectionListener[]; + listeners(event: 'warning'): WarningListener[]; + listeners(event: 'message'): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: 'multipleResolves'): MultipleResolveListener[]; + listeners(event: 'worker'): WorkerListener[]; + } + } + } + export = process; +} +declare module 'node:process' { + import process = require('process'); + export = process; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/punycode.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..81b3c63 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/punycode.js) + */ +declare module 'punycode' { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: ReadonlyArray): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module 'node:punycode' { + export * from 'punycode'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/querystring.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..572828a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,131 @@ +/** + * The `querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('querystring'); + * ``` + * + * The `querystring` API is considered Legacy. While it is still maintained, + * new code should use the `URLSearchParams` API instead. + * @deprecated Legacy + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/querystring.js) + */ +declare module 'querystring' { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends NodeJS.Dict | ReadonlyArray | ReadonlyArray | null> {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```js + * { + * foo: 'bar', + * abc: ['xyz', '123'] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module 'node:querystring' { + export * from 'querystring'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/readline.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..43ab1db --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/readline.d.ts @@ -0,0 +1,650 @@ +/** + * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/readline.js) + */ +declare module 'readline' { + import { Abortable, EventEmitter } from 'node:events'; + interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + class Interface extends EventEmitter { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' ') + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `readline.Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * + * If this method is invoked as it's util.promisify()ed version, it returns a + * Promise that fulfills with the answer. If the question is canceled using + * an `AbortController` it will reject with an `AbortError`. + * + * ```js + * const util = require('util'); + * const question = util.promisify(rl.question).bind(rl); + * + * async function questionExample() { + * try { + * const answer = await question('What is you favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * } catch (err) { + * console.error('Question rejected', err); + * } + * } + * questionExample(); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `readline.Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `readline.Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `readline.Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'line', listener: (input: string) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'SIGCONT', listener: () => void): this; + addListener(event: 'SIGINT', listener: () => void): this; + addListener(event: 'SIGTSTP', listener: () => void): this; + addListener(event: 'history', listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'line', input: string): boolean; + emit(event: 'pause'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'SIGCONT'): boolean; + emit(event: 'SIGINT'): boolean; + emit(event: 'SIGTSTP'): boolean; + emit(event: 'history', history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'line', listener: (input: string) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'SIGCONT', listener: () => void): this; + on(event: 'SIGINT', listener: () => void): this; + on(event: 'SIGTSTP', listener: () => void): this; + on(event: 'history', listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'line', listener: (input: string) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'SIGCONT', listener: () => void): this; + once(event: 'SIGINT', listener: () => void): this; + once(event: 'SIGTSTP', listener: () => void): this; + once(event: 'history', listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'line', listener: (input: string) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'SIGCONT', listener: () => void): this; + prependListener(event: 'SIGINT', listener: () => void): this; + prependListener(event: 'SIGTSTP', listener: () => void): this; + prependListener(event: 'history', listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'line', listener: (input: string) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'SIGCONT', listener: () => void): this; + prependOnceListener(event: 'SIGINT', listener: () => void): this; + prependOnceListener(event: 'SIGTSTP', listener: () => void): this; + prependOnceListener(event: 'history', listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + type ReadLine = Interface; // type forwarded for backwards compatibility + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => void; + type CompleterResult = [string[], string]; + interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + terminal?: boolean | undefined; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: number | undefined; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives `EOF` (Ctrl+D on + * Linux/macOS, Ctrl+Z followed by Return on + * Windows). + * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: + * + * ```js + * process.stdin.unref(); + * ``` + * @since v0.1.98 + */ + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ' + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + type Direction = -1 | 0 | 1; + interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given `TTY` stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given `TTY` stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given `TTY` `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given `TTY` `stream`. + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ' + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module 'node:readline' { + export * from 'readline'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/repl.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..e81fee5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/repl.d.ts @@ -0,0 +1,424 @@ +/** + * The `repl` module provides a Read-Eval-Print-Loop (REPL) implementation that + * is available both as a standalone program or includible in other applications. + * It can be accessed using: + * + * ```js + * const repl = require('repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/repl.js) + */ +declare module 'repl' { + import { Interface, Completer, AsyncCompleter } from 'node:readline'; + import { Context } from 'node:vm'; + import { InspectOptions } from 'node:util'; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('repl'); + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the`keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * const repl = require('repl'); + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * } + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (*without* a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output`and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'line', listener: (input: string) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'SIGCONT', listener: () => void): this; + addListener(event: 'SIGINT', listener: () => void): this; + addListener(event: 'SIGTSTP', listener: () => void): this; + addListener(event: 'exit', listener: () => void): this; + addListener(event: 'reset', listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'line', input: string): boolean; + emit(event: 'pause'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'SIGCONT'): boolean; + emit(event: 'SIGINT'): boolean; + emit(event: 'SIGTSTP'): boolean; + emit(event: 'exit'): boolean; + emit(event: 'reset', context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'line', listener: (input: string) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'SIGCONT', listener: () => void): this; + on(event: 'SIGINT', listener: () => void): this; + on(event: 'SIGTSTP', listener: () => void): this; + on(event: 'exit', listener: () => void): this; + on(event: 'reset', listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'line', listener: (input: string) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'SIGCONT', listener: () => void): this; + once(event: 'SIGINT', listener: () => void): this; + once(event: 'SIGTSTP', listener: () => void): this; + once(event: 'exit', listener: () => void): this; + once(event: 'reset', listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'line', listener: (input: string) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'SIGCONT', listener: () => void): this; + prependListener(event: 'SIGINT', listener: () => void): this; + prependListener(event: 'SIGTSTP', listener: () => void): this; + prependListener(event: 'exit', listener: () => void): this; + prependListener(event: 'reset', listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'line', listener: (input: string) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'SIGCONT', listener: () => void): this; + prependOnceListener(event: 'SIGINT', listener: () => void): this; + prependOnceListener(event: 'SIGTSTP', listener: () => void): this; + prependOnceListener(event: 'exit', listener: () => void): this; + prependOnceListener(event: 'reset', listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * const repl = require('repl'); + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module 'node:repl' { + export * from 'repl'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/stream.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..7edc7bf --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1249 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `stream` module: + * + * ```js + * const stream = require('stream'); + * ``` + * + * The `stream` module is useful for creating new types of stream instances. It is + * usually not necessary to use the `stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/stream.js) + */ +declare module 'stream' { + import { EventEmitter, Abortable } from 'node:events'; + import * as streamPromises from 'node:stream/promises'; + import * as streamConsumers from 'node:stream/consumers'; + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + } + ): T; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.read()`, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'end'` event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the `Three states` section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method pulls some data out of the internal buffer and + * returns it. If no data available to be read, `null` is returned. By default, + * the data will be returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which + * case all of the data remaining in the internal + * buffer will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the`size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most + * typical cases, there will be no reason to + * use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.match(/\n\n/)) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * } else { + * // Still reading the header. + * header += str; + * } + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode + * streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `stream` module API + * as it is currently defined. (See `Compatibility` for more information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()`will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: any) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: any): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'pause'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'resume'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: any) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: any) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: any) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: any) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'data', listener: (chunk: any) => void): this; + removeListener(event: 'end', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'pause', listener: () => void): this; + removeListener(event: 'readable', listener: () => void): this; + removeListener(event: 'resume', listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?(this: Writable, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * It is recommended that once `write()` returns false, no more chunks be written + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, it is recommended that calls to `writable.uncork()` be + * deferred using `process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: Readable) => void): this; + addListener(event: 'unpipe', listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: Readable): boolean; + emit(event: 'unpipe', src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: Readable) => void): this; + on(event: 'unpipe', listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: Readable) => void): this; + once(event: 'unpipe', listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'drain', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'finish', listener: () => void): this; + removeListener(event: 'pipe', listener: (src: Readable) => void): this; + removeListener(event: 'unpipe', listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Readable implements Writable { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `false`. + * + * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is + * emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from(src: Stream | Blob | ArrayBuffer | string | Iterable | AsyncIterable | AsyncGeneratorFunction | Promise | Object): Duplex; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; + cork(): void; + uncork(): void; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream. + * + * ```js + * const fs = require('fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream a stream to attach a signal to + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('stream'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + * + * The `finished` API provides promise version: + * + * ```js + * const { finished } = require('stream/promises'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @return A cleanup function which removes all registered listeners. + */ + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options: FinishedOptions, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + namespace finished { + function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | ((source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable : S) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

    ; + type PipelineDestination, P> = S extends PipelineTransformSource + ? NodeJS.WritableStream | PipelineDestinationIterableFunction | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends PipelineDestinationPromiseFunction + ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends PipelineDestinationPromiseFunction ? Promise

    : Promise; + interface PipelineOptions { + signal: AbortSignal; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('stream'); + * const fs = require('fs'); + * const zlib = require('zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * } + * ); + * ``` + * + * The `pipeline` API provides a promise version, which can also + * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with + * an`AbortError`. + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, + * as the last argument: + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * const ac = new AbortController(); + * const signal = ac.signal; + * + * setTimeout(() => ac.abort(), 1); + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * { signal }, + * ); + * } + * + * run().catch(console.error); // AbortError + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('lowercase.txt'), + * async function* (source, signal) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield await processChunk(chunk, { signal }); + * } + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * Remember to handle the `signal` argument passed into the async generator. + * Especially in the case where the async generator is the source for the + * pipeline (i.e. first argument) or the pipeline will never complete. + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * async function * (signal) { + * await someLongRunningfn({ signal }); + * yield 'asd'; + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback?: (err: NodeJS.ErrnoException | null) => void + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array void)> + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__(streams: ReadonlyArray, options?: PipelineOptions): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module 'node:stream' { + import stream = require('stream'); + export = stream; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/stream/consumers.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..ce6c9bb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,24 @@ +// Duplicates of interface in lib.dom.ts. +// Duplicated here rather than referencing lib.dom.ts because doing so causes lib.dom.ts to be loaded for "test-all" +// Which in turn causes tests to pass that shouldn't pass. +// +// This interface is not, and should not be, exported. +interface Blob { + readonly size: number; + readonly type: string; + arrayBuffer(): Promise; + slice(start?: number, end?: number, contentType?: string): Blob; + stream(): NodeJS.ReadableStream; + text(): Promise; +} +declare module 'stream/consumers' { + import { Readable } from 'node:stream'; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; +} +declare module 'node:stream/consumers' { + export * from 'stream/consumers'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/stream/promises.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..b427073 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,42 @@ +declare module 'stream/promises' { + import { FinishedOptions, PipelineSource, PipelineTransform, PipelineDestination, PipelinePromise, PipelineOptions } from 'node:stream'; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + function pipeline, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline(streams: ReadonlyArray, options?: PipelineOptions): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module 'node:stream/promises' { + export * from 'stream/promises'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/stream/web.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..f9ef057 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,330 @@ +declare module 'stream/web' { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + interface ReadableStreamDefaultReadValueResult { + done: false; + value: T; + } + interface ReadableStreamDefaultReadDoneResult { + done: true; + value?: undefined; + } + type ReadableStreamController = ReadableStreamDefaultController; + type ReadableStreamDefaultReadResult = ReadableStreamDefaultReadValueResult | ReadableStreamDefaultReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: 'bytes'; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(): ReadableStreamDefaultReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + const ReadableStream: { + prototype: ReadableStream; + new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new (stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: any; + const ReadableStreamBYOBRequest: any; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new (): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new (): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new (transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new (): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new (underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new (stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new (): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new (init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new (init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: 'utf-8'; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new (): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new (label?: string, options?: TextDecoderOptions): TextDecoderStream; + }; +} +declare module 'node:stream/web' { + export * from 'stream/web'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/string_decoder.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..da712b5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `string_decoder` module provides an API for decoding `Buffer` objects into + * strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/string_decoder.js) + */ +declare module 'string_decoder' { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + write(buffer: Buffer): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + end(buffer?: Buffer): string; + } +} +declare module 'node:string_decoder' { + export * from 'string_decoder'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/timers.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..59f44c1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/timers.d.ts @@ -0,0 +1,94 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/timers.js) + */ +declare module 'timers' { + import { Abortable } from 'node:events'; + import { setTimeout as setTimeoutPromise, setImmediate as setImmediatePromise, setInterval as setIntervalPromise } from 'node:timers/promises'; + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + interface Immediate extends RefCounted { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + } + interface Timeout extends Timer { + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + } + } + function setTimeout(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timeout; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + function clearTimeout(timeoutId: NodeJS.Timeout): void; + function setInterval(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timer; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timer; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + function clearInterval(intervalId: NodeJS.Timeout): void; + function setImmediate(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + function clearImmediate(immediateId: NodeJS.Immediate): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module 'node:timers' { + export * from 'timers'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/timers/promises.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..fd77888 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,68 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module 'timers/promises' { + import { TimerOptions } from 'node:timers'; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; +} +declare module 'node:timers/promises' { + export * from 'timers/promises'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/tls.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..661f0f0 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1020 @@ +/** + * The `tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * const tls = require('tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/tls.js) + */ +declare module 'tls' { + import { X509Certificate } from 'node:crypto'; + import * as net from 'node:net'; + import * as stream from 'stream'; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: NodeJS.Dict; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + fingerprint256: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: TLSSocketOptions); + /** + * Returns `true` if the peer certificate was signed by one of the CAs specified + * when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: boolean; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example: + * + * ```json + * { + * "name": "AES128-SHA256", + * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", + * "version": "TLSv1.2" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void + ): undefined | boolean; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * Note: The format of the output is identical to the output of `openssl s_client -trace` or `openssl s_server -trace`. While it is produced by OpenSSL's`SSL_trace()` function, the format is + * undocumented, can change without notice, + * and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + addListener(event: 'secureConnect', listener: () => void): this; + addListener(event: 'session', listener: (session: Buffer) => void): this; + addListener(event: 'keylog', listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'OCSPResponse', response: Buffer): boolean; + emit(event: 'secureConnect'): boolean; + emit(event: 'session', session: Buffer): boolean; + emit(event: 'keylog', line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + on(event: 'secureConnect', listener: () => void): this; + on(event: 'session', listener: (session: Buffer) => void): this; + on(event: 'keylog', listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + once(event: 'secureConnect', listener: () => void): this; + once(event: 'session', listener: (session: Buffer) => void): this; + once(event: 'keylog', listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependListener(event: 'secureConnect', listener: () => void): this; + prependListener(event: 'session', listener: (session: Buffer) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependOnceListener(event: 'secureConnect', listener: () => void): this; + prependOnceListener(event: 'session', listener: (session: Buffer) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + addContext(hostname: string, context: SecureContextOptions): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'tlsClientError', err: Error, tlsSocket: TLSSocket): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: 'secureConnection', tlsSocket: TLSSocket): boolean; + emit(event: 'keylog', line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + on(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + once(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; + interface SecureContextOptions { + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use + * openssl dhparam to create the parameters. The key length must be + * greater than or equal to 1024 bits or else an error will be thrown. + * Although 1024 bits is permissible, use 2048 bits or larger for + * stronger security. If omitted or invalid, the parameters are + * silently discarded and DHE ciphers will not be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function can be overwritten by providing alternative function as part of + * the `options.checkServerIdentity` option passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ] + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair(context?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + /** + * {@link createServer} sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * {@link createServer} uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods. + * + * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of {@link createSecureContext}. + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is 'auto'. See tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.createSecureContext(). It can be assigned any of the supported TLS + * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: + * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets + * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the highest maximum + * is used. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.createSecureContext(). + * It can be assigned any of the supported TLS protocol versions, + * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless + * changed using CLI options. Using --tls-min-v1.0 sets the default to + * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using + * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options + * are provided, the lowest minimum is used. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: ReadonlyArray; +} +declare module 'node:tls' { + export * from 'tls'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/trace_events.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..cb4e375 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,161 @@ +/** + * The `trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. + * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()`output. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.perf`: Enables capture of `Performance API` measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be + * used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `trace_events` module: + * + * ```js + * const trace_events = require('trace_events'); + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in `Worker` threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/trace_events.js) + */ +declare module 'trace_events' { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * const trace_events = require('trace_events'); + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + * @return . + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. + * + * ```js + * const trace_events = require('trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module 'node:trace_events' { + export * from 'trace_events'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/tty.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000..72fdf2e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/tty.d.ts @@ -0,0 +1,204 @@ +/** + * The `tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. + * In most cases, it will not be necessary or possible to use this module directly. + * However, it can be accessed using: + * + * ```js + * const tty = require('tty'); + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of`tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes. + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/tty.js) + */ +declare module 'tty' { + import * as net from 'node:net'; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. Defaults to `false`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input characters.Ctrl+C will no longer cause a `SIGINT` when in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances,`process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'resize', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'resize'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'resize', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'resize', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'resize', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'resize', listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and`NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type`[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module 'node:tty' { + export * from 'tty'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/url.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000..0ec6bd1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/url.d.ts @@ -0,0 +1,891 @@ +/** + * The `url` module provides utilities for URL resolution and parsing. It can be + * accessed using: + * + * ```js + * import url from 'url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/url.js) + */ +declare module 'url' { + import { Blob } from 'node:buffer'; + import { ClientRequestArgs } from 'node:http'; + import { ParsedUrlQuery, ParsedUrlQueryInput } from 'node:querystring'; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * Use of the legacy `url.parse()` method is discouraged. Users should + * use the WHATWG `URL` API. Because the `url.parse()` method uses a + * lenient, non-standard algorithm for parsing URL strings, security + * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and + * incorrect handling of usernames and passwords have been identified. + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json' + * } + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; + * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string + * and appended to `result`followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to`result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the + * `querystring` module's `stringify()`method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search`_does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json' + * } + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; + * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string + * and appended to `result`followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to`result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the + * `querystring` module's `stringify()`method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search`_does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a Web browser resolving an anchor tag HREF. + * + * ```js + * const url = require('url'); + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * You can achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param from The Base URL being resolved against. + * @param to The HREF URL being resolved. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL): string; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + auth?: boolean | undefined; + fragment?: boolean | undefined; + search?: boolean | undefined; + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject` s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * const { + * Blob, + * resolveObjectURL, + * } = require('buffer'); + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until`URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + * @experimental + */ + static createObjectURL(blob: Blob): string; + /** + * Removes the stored `Blob` identified by the given ID. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(objectUrl: string): void; + constructor(input: string, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL`object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError`will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname`property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range`0` to `65535` (inclusive). Setting the value to the default port of the`URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myUrl = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myUrl.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myUrl.searchParams.sort(); + * + * console.log(myUrl.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a`URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | Record> | Iterable<[string, string]> | ReadonlyArray<[string, string]>); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array`is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[@@iterator]()`. + */ + entries(): IterableIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach(callback: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, thisArg?: TThis): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to`value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } + + import { URL as _URL, URLSearchParams as _URLSearchParams } from 'url'; + global { + interface URLSearchParams extends _URLSearchParams {} + interface URL extends _URL {} + interface Global { + URL: typeof _URL; + URLSearchParams: typeof _URLSearchParams; + } + /** + * `URL` class is a global reference for `require('url').URL` + * https://nodejs.org/api/url.html#the-whatwg-url-api + * @since v10.0.0 + */ + var URL: + // For compatibility with "dom" and "webworker" URL declarations + typeof globalThis extends { onmessage: any, URL: infer URL } + ? URL + : typeof _URL; + /** + * `URLSearchParams` class is a global reference for `require('url').URLSearchParams` + * https://nodejs.org/api/url.html#class-urlsearchparams + * @since v10.0.0 + */ + var URLSearchParams: + // For compatibility with "dom" and "webworker" URLSearchParams declarations + typeof globalThis extends { onmessage: any, URLSearchParams: infer URLSearchParams } + ? URLSearchParams + : typeof _URLSearchParams; + } +} +declare module 'node:url' { + export * from 'url'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/util.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000..575391e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/util.d.ts @@ -0,0 +1,1594 @@ +/** + * The `util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/util.js) + */ +declare module 'util' { + import * as types from 'node:util/types'; + export interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean | undefined; + showHidden?: boolean | undefined; + /** + * @default 2 + */ + depth?: number | null | undefined; + colors?: boolean | undefined; + customInspect?: boolean | undefined; + showProxy?: boolean | undefined; + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number | undefined; + sorted?: boolean | ((a: string, b: string) => number) | undefined; + } + export type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`\-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using`util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()`returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result.`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]) + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('util'); + * const assert = require('assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]) + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1] + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }) + * ); + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. + * + * ```js + * const util = require('util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and`extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from`superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('util'); + * const EventEmitter = require('events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @deprecated Legacy: Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export const debug: typeof debuglog; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a`DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the`process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation`property take precedence over `--trace-deprecation` and`process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named`reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && err.hasOwnProperty('reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param original An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify`will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()`will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder('shift_jis'); + * let string = ''; + * let buffer; + * while (buffer = getNextChunkSomehow()) { + * string += decoder.decode(buffer, { stream: true }); + * } + * string += decoder.decode(); // end-of-stream + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + } + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + } + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } +} +declare module 'util/types' { + export * from 'util/types'; +} +declare module 'util/types' { + import { KeyObject, webcrypto } from 'node:crypto'; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap(object: T | {}): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value is an instance of a built-in `Error` type. + * + * ```js + * util.types.isNativeError(new Error()); // Returns true + * util.types.isNativeError(new TypeError()); // Returns true + * util.types.isNativeError(new RangeError()); // Returns true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet(object: T | {}): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module 'node:util' { + export * from 'util'; +} +declare module 'node:util/types' { + export * from 'util/types'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/v8.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..59c8302 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/v8.d.ts @@ -0,0 +1,378 @@ +/** + * The `v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * const v8 = require('v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/v8.js) + */ +declare module 'v8' { + import { Readable } from 'node:stream'; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the`--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8[`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running`node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * const v8 = require('v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable Stream containing the V8 heap snapshot + */ + function getHeapSnapshot(): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * ```js + * const { writeHeapSnapshot } = require('v8'); + * const { + * Worker, + * isMainThread, + * parentPort + * } = require('worker_threads'); + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string): string; + /** + * Returns an object with the following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794 + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer’s internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before`.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]`with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer’s internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.TypedArray): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; +} +declare module 'node:v8' { + export * from 'v8'; +} diff --git a/node_modules/mathjs/examples/node_modules/@types/node/vm.d.ts b/node_modules/mathjs/examples/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..860b7ac --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/@types/node/vm.d.ts @@ -0,0 +1,507 @@ +/** + * The `vm` module enables compiling and running code within V8 Virtual + * Machine contexts. **The `vm` module is not a security mechanism. Do** + * **not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * const vm = require('vm'); + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/vm.js) + */ +declare module 'vm' { + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + interface ScriptOptions extends BaseOptions { + displayErrors?: boolean | undefined; + timeout?: number | undefined; + cachedData?: Buffer | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * Default: `true`. + */ + displayErrors?: boolean | undefined; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number | undefined; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * Default: `false`. + */ + breakOnSigint?: boolean | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate' | undefined; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | undefined; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean | undefined; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context | undefined; + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[] | undefined; + } + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string | undefined; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string | undefined; + codeGeneration?: + | { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean | undefined; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean | undefined; + } + | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate' | undefined; + } + type MeasureMemoryMode = 'summary' | 'detailed'; + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode | undefined; + context?: Context | undefined; + } + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + /** + * Instances of the `vm.Script` class contain precompiled scripts that can be + * executed in specific contexts. + * @since v0.3.1 + */ + class Script { + constructor(code: string, options?: ScriptOptions); + /** + * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access + * to local scope. + * + * The following example compiles code that increments a global variable, sets + * the value of another global variable, then execute the code multiple times. + * The globals are contained in the `context` object. + * + * ```js + * const vm = require('vm'); + * + * const context = { + * animal: 'cat', + * count: 2 + * }; + * + * const script = new vm.Script('count += 1; name = "kitty";'); + * + * vm.createContext(context); + * for (let i = 0; i < 10; ++i) { + * script.runInContext(context); + * } + * + * console.log(context); + * // Prints: { animal: 'cat', count: 12, name: 'kitty' } + * ``` + * + * Using the `timeout` or `breakOnSigint` options will result in new event loops + * and corresponding threads being started, which have a non-zero performance + * overhead. + * @since v0.3.1 + * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. + * @return the result of the very last statement executed in the script. + */ + runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; + /** + * First contextifies the given `contextObject`, runs the compiled code contained + * by the `vm.Script` object within the created context, and returns the result. + * Running code does not have access to local scope. + * + * The following example compiles code that sets a global variable, then executes + * the code multiple times in different contexts. The globals are set on and + * contained within each individual `context`. + * + * ```js + * const vm = require('vm'); + * + * const script = new vm.Script('globalVar = "set"'); + * + * const contexts = [{}, {}, {}]; + * contexts.forEach((context) => { + * script.runInNewContext(context); + * }); + * + * console.log(contexts); + * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + * ``` + * @since v0.3.1 + * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. + * @return the result of the very last statement executed in the script. + */ + runInNewContext(contextObject?: Context, options?: RunningScriptOptions): any; + /** + * Runs the compiled code contained by the `vm.Script` within the context of the + * current `global` object. Running code does not have access to local scope, but_does_ have access to the current `global` object. + * + * The following example compiles code that increments a `global` variable then + * executes that code multiple times: + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 0; + * + * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * + * for (let i = 0; i < 1000; ++i) { + * script.runInThisContext(); + * } + * + * console.log(globalVar); + * + * // 1000 + * ``` + * @since v0.3.1 + * @return the result of the very last statement executed in the script. + */ + runInThisContext(options?: RunningScriptOptions): any; + /** + * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any + * time and any number of times. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutX = script.createCachedData(); + * + * script.runInThisContext(); + * + * const cacheWithX = script.createCachedData(); + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will `prepare + * that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. Inside such scripts, + * the `contextObject` will be the global object, retaining all of its existing + * properties but also having the built-in objects and functions any standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global variables + * will remain unchanged. + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 3; + * + * const context = { globalVar: 1 }; + * vm.createContext(context); + * + * vm.runInContext('globalVar *= 2;', context); + * + * console.log(context); + * // Prints: { globalVar: 2 } + * + * console.log(global.globalVar); + * // Prints: 3 + * ``` + * + * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, + * empty `contextified` object will be returned. + * + * The `vm.createContext()` method is primarily useful for creating a single + * context that can be used to run multiple scripts. For instance, if emulating a + * web browser, the method can be used to create a single context representing a + * window's global object, then run all ` +``` + +### In an AMD loader +```js +require(['async'], function(async) {}); +``` + +### Promise and async/await + +I recommend to use [`Aigle`](https://github.com/suguru03/aigle). + +It is optimized for Promise handling and has almost the same functionality as `neo-async`. + +### Node.js + +#### standard + +```bash +$ npm install neo-async +``` +```js +var async = require('neo-async'); +``` + +#### replacement +```bash +$ npm install neo-async +$ ln -s ./node_modules/neo-async ./node_modules/async +``` +```js +var async = require('async'); +``` + +### Bower + +```bash +bower install neo-async +``` + +## Feature + +[JSDoc](http://suguru03.github.io/neo-async/doc/async.html) + +\* not in Async + +### Collections + +- [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) +- [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) +- [`eachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) +- [`forEach`](http://suguru03.github.io/neo-async/doc/async.each.html) -> [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) +- [`forEachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) -> [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) +- [`forEachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) -> [`eachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) +- [`eachOf`](http://suguru03.github.io/neo-async/doc/async.each.html) -> [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) +- [`eachOfSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) -> [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) +- [`eachOfLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) -> [`eachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) +- [`forEachOf`](http://suguru03.github.io/neo-async/doc/async.each.html) -> [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) +- [`forEachOfSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) -> [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) +- [`eachOfLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) -> [`forEachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) +- [`map`](http://suguru03.github.io/neo-async/doc/async.map.html) +- [`mapSeries`](http://suguru03.github.io/neo-async/doc/async.mapSeries.html) +- [`mapLimit`](http://suguru03.github.io/neo-async/doc/async.mapLimit.html) +- [`mapValues`](http://suguru03.github.io/neo-async/doc/async.mapValues.html) +- [`mapValuesSeries`](http://suguru03.github.io/neo-async/doc/async.mapValuesSeries.html) +- [`mapValuesLimit`](http://suguru03.github.io/neo-async/doc/async.mapValuesLimit.html) +- [`filter`](http://suguru03.github.io/neo-async/doc/async.filter.html) +- [`filterSeries`](http://suguru03.github.io/neo-async/doc/async.filterSeries.html) +- [`filterLimit`](http://suguru03.github.io/neo-async/doc/async.filterLimit.html) +- [`select`](http://suguru03.github.io/neo-async/doc/async.filter.html) -> [`filter`](http://suguru03.github.io/neo-async/doc/async.filter.html) +- [`selectSeries`](http://suguru03.github.io/neo-async/doc/async.filterSeries.html) -> [`filterSeries`](http://suguru03.github.io/neo-async/doc/async.filterSeries.html) +- [`selectLimit`](http://suguru03.github.io/neo-async/doc/async.filterLimit.html) -> [`filterLimit`](http://suguru03.github.io/neo-async/doc/async.filterLimit.html) +- [`reject`](http://suguru03.github.io/neo-async/doc/async.reject.html) +- [`rejectSeries`](http://suguru03.github.io/neo-async/doc/async.rejectSeries.html) +- [`rejectLimit`](http://suguru03.github.io/neo-async/doc/async.rejectLimit.html) +- [`detect`](http://suguru03.github.io/neo-async/doc/async.detect.html) +- [`detectSeries`](http://suguru03.github.io/neo-async/doc/async.detectSeries.html) +- [`detectLimit`](http://suguru03.github.io/neo-async/doc/async.detectLimit.html) +- [`find`](http://suguru03.github.io/neo-async/doc/async.detect.html) -> [`detect`](http://suguru03.github.io/neo-async/doc/async.detect.html) +- [`findSeries`](http://suguru03.github.io/neo-async/doc/async.detectSeries.html) -> [`detectSeries`](http://suguru03.github.io/neo-async/doc/async.detectSeries.html) +- [`findLimit`](http://suguru03.github.io/neo-async/doc/async.detectLimit.html) -> [`detectLimit`](http://suguru03.github.io/neo-async/doc/async.detectLimit.html) +- [`pick`](http://suguru03.github.io/neo-async/doc/async.pick.html) * +- [`pickSeries`](http://suguru03.github.io/neo-async/doc/async.pickSeries.html) * +- [`pickLimit`](http://suguru03.github.io/neo-async/doc/async.pickLimit.html) * +- [`omit`](http://suguru03.github.io/neo-async/doc/async.omit.html) * +- [`omitSeries`](http://suguru03.github.io/neo-async/doc/async.omitSeries.html) * +- [`omitLimit`](http://suguru03.github.io/neo-async/doc/async.omitLimit.html) * +- [`reduce`](http://suguru03.github.io/neo-async/doc/async.reduce.html) +- [`inject`](http://suguru03.github.io/neo-async/doc/async.reduce.html) -> [`reduce`](http://suguru03.github.io/neo-async/doc/async.reduce.html) +- [`foldl`](http://suguru03.github.io/neo-async/doc/async.reduce.html) -> [`reduce`](http://suguru03.github.io/neo-async/doc/async.reduce.html) +- [`reduceRight`](http://suguru03.github.io/neo-async/doc/async.reduceRight.html) +- [`foldr`](http://suguru03.github.io/neo-async/doc/async.reduceRight.html) -> [`reduceRight`](http://suguru03.github.io/neo-async/doc/async.reduceRight.html) +- [`transform`](http://suguru03.github.io/neo-async/doc/async.transform.html) +- [`transformSeries`](http://suguru03.github.io/neo-async/doc/async.transformSeries.html) * +- [`transformLimit`](http://suguru03.github.io/neo-async/doc/async.transformLimit.html) * +- [`sortBy`](http://suguru03.github.io/neo-async/doc/async.sortBy.html) +- [`sortBySeries`](http://suguru03.github.io/neo-async/doc/async.sortBySeries.html) * +- [`sortByLimit`](http://suguru03.github.io/neo-async/doc/async.sortByLimit.html) * +- [`some`](http://suguru03.github.io/neo-async/doc/async.some.html) +- [`someSeries`](http://suguru03.github.io/neo-async/doc/async.someSeries.html) +- [`someLimit`](http://suguru03.github.io/neo-async/doc/async.someLimit.html) +- [`any`](http://suguru03.github.io/neo-async/doc/async.some.html) -> [`some`](http://suguru03.github.io/neo-async/doc/async.some.html) +- [`anySeries`](http://suguru03.github.io/neo-async/doc/async.someSeries.html) -> [`someSeries`](http://suguru03.github.io/neo-async/doc/async.someSeries.html) +- [`anyLimit`](http://suguru03.github.io/neo-async/doc/async.someLimit.html) -> [`someLimit`](http://suguru03.github.io/neo-async/doc/async.someLimit.html) +- [`every`](http://suguru03.github.io/neo-async/doc/async.every.html) +- [`everySeries`](http://suguru03.github.io/neo-async/doc/async.everySeries.html) +- [`everyLimit`](http://suguru03.github.io/neo-async/doc/async.everyLimit.html) +- [`all`](http://suguru03.github.io/neo-async/doc/async.every.html) -> [`every`](http://suguru03.github.io/neo-async/doc/async.every.html) +- [`allSeries`](http://suguru03.github.io/neo-async/doc/async.everySeries.html) -> [`every`](http://suguru03.github.io/neo-async/doc/async.everySeries.html) +- [`allLimit`](http://suguru03.github.io/neo-async/doc/async.everyLimit.html) -> [`every`](http://suguru03.github.io/neo-async/doc/async.everyLimit.html) +- [`concat`](http://suguru03.github.io/neo-async/doc/async.concat.html) +- [`concatSeries`](http://suguru03.github.io/neo-async/doc/async.concatSeries.html) +- [`concatLimit`](http://suguru03.github.io/neo-async/doc/async.concatLimit.html) * + +### Control Flow + +- [`parallel`](http://suguru03.github.io/neo-async/doc/async.parallel.html) +- [`series`](http://suguru03.github.io/neo-async/doc/async.series.html) +- [`parallelLimit`](http://suguru03.github.io/neo-async/doc/async.series.html) +- [`tryEach`](http://suguru03.github.io/neo-async/doc/async.tryEach.html) +- [`waterfall`](http://suguru03.github.io/neo-async/doc/async.waterfall.html) +- [`angelFall`](http://suguru03.github.io/neo-async/doc/async.angelFall.html) * +- [`angelfall`](http://suguru03.github.io/neo-async/doc/async.angelFall.html) -> [`angelFall`](http://suguru03.github.io/neo-async/doc/async.angelFall.html) * +- [`whilst`](#whilst) +- [`doWhilst`](#doWhilst) +- [`until`](#until) +- [`doUntil`](#doUntil) +- [`during`](#during) +- [`doDuring`](#doDuring) +- [`forever`](#forever) +- [`compose`](#compose) +- [`seq`](#seq) +- [`applyEach`](#applyEach) +- [`applyEachSeries`](#applyEachSeries) +- [`queue`](#queue) +- [`priorityQueue`](#priorityQueue) +- [`cargo`](#cargo) +- [`auto`](#auto) +- [`autoInject`](#autoInject) +- [`retry`](#retry) +- [`retryable`](#retryable) +- [`iterator`](#iterator) +- [`times`](http://suguru03.github.io/neo-async/doc/async.times.html) +- [`timesSeries`](http://suguru03.github.io/neo-async/doc/async.timesSeries.html) +- [`timesLimit`](http://suguru03.github.io/neo-async/doc/async.timesLimit.html) +- [`race`](#race) + +### Utils +- [`apply`](#apply) +- [`setImmediate`](#setImmediate) +- [`nextTick`](#nextTick) +- [`memoize`](#memoize) +- [`unmemoize`](#unmemoize) +- [`ensureAsync`](#ensureAsync) +- [`constant`](#constant) +- [`asyncify`](#asyncify) +- [`wrapSync`](#asyncify) -> [`asyncify`](#asyncify) +- [`log`](#log) +- [`dir`](#dir) +- [`timeout`](http://suguru03.github.io/neo-async/doc/async.timeout.html) +- [`reflect`](#reflect) +- [`reflectAll`](#reflectAll) +- [`createLogger`](#createLogger) + +## Mode +- [`safe`](#safe) * +- [`fast`](#fast) * + +## Benchmark + +[Benchmark: Async vs Neo-Async](http://suguru03.hatenablog.com/entry/2016/06/10/135559) + +### How to check + +```bash +$ node perf +``` + +### Environment + +* Darwin 17.3.0 x64 +* Node.js v8.9.4 +* async v2.6.0 +* neo-async v2.5.0 +* benchmark v2.1.4 + +### Result + +The value is the ratio (Neo-Async/Async) of the average speed. + +#### Collections +|function|benchmark| +|---|--:| +|each/forEach|2.43| +|eachSeries/forEachSeries|1.75| +|eachLimit/forEachLimit|1.68| +|eachOf|3.29| +|eachOfSeries|1.50| +|eachOfLimit|1.59| +|map|3.95| +|mapSeries|1.81| +|mapLimit|1.27| +|mapValues|2.73| +|mapValuesSeries|1.59| +|mapValuesLimit|1.23| +|filter|3.00| +|filterSeries|1.74| +|filterLimit|1.17| +|reject|4.59| +|rejectSeries|2.31| +|rejectLimit|1.58| +|detect|4.30| +|detectSeries|1.86| +|detectLimit|1.32| +|reduce|1.82| +|transform|2.46| +|sortBy|4.08| +|some|2.19| +|someSeries|1.83| +|someLimit|1.32| +|every|2.09| +|everySeries|1.84| +|everyLimit|1.35| +|concat|3.79| +|concatSeries|4.45| + +#### Control Flow +|funciton|benchmark| +|---|--:| +|parallel|2.93| +|series|1.96| +|waterfall|1.29| +|whilst|1.00| +|doWhilst|1.12| +|until|1.12| +|doUntil|1.12| +|during|1.18| +|doDuring|2.42| +|times|4.25| +|auto|1.97| + + +## License +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fsuguru03%2Fneo-async.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fsuguru03%2Fneo-async?ref=badge_large) diff --git a/node_modules/mathjs/examples/node_modules/neo-async/all.js b/node_modules/mathjs/examples/node_modules/neo-async/all.js new file mode 100644 index 0000000..dad54e7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/all.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').all; diff --git a/node_modules/mathjs/examples/node_modules/neo-async/allLimit.js b/node_modules/mathjs/examples/node_modules/neo-async/allLimit.js new file mode 100644 index 0000000..d9d7aaa --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/allLimit.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').allLimit; diff --git a/node_modules/mathjs/examples/node_modules/neo-async/allSeries.js b/node_modules/mathjs/examples/node_modules/neo-async/allSeries.js new file mode 100644 index 0000000..2a7a8ba --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/allSeries.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').allSeries; diff --git a/node_modules/mathjs/examples/node_modules/neo-async/angelFall.js b/node_modules/mathjs/examples/node_modules/neo-async/angelFall.js new file mode 100644 index 0000000..476c23e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/angelFall.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').angelfall; diff --git a/node_modules/mathjs/examples/node_modules/neo-async/any.js b/node_modules/mathjs/examples/node_modules/neo-async/any.js new file mode 100644 index 0000000..d6b07bb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/any.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').any; diff --git a/node_modules/mathjs/examples/node_modules/neo-async/anyLimit.js b/node_modules/mathjs/examples/node_modules/neo-async/anyLimit.js new file mode 100644 index 0000000..34114f8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/anyLimit.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').anyLimit; diff --git a/node_modules/mathjs/examples/node_modules/neo-async/anySeries.js b/node_modules/mathjs/examples/node_modules/neo-async/anySeries.js new file mode 100644 index 0000000..bb3781f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/anySeries.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').anySeries; diff --git a/node_modules/mathjs/examples/node_modules/neo-async/apply.js b/node_modules/mathjs/examples/node_modules/neo-async/apply.js new file mode 100644 index 0000000..41135e2 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/apply.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').apply; diff --git a/node_modules/mathjs/examples/node_modules/neo-async/applyEach.js b/node_modules/mathjs/examples/node_modules/neo-async/applyEach.js new file mode 100644 index 0000000..292bd1c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/applyEach.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').applyEach; diff --git a/node_modules/mathjs/examples/node_modules/neo-async/applyEachSeries.js b/node_modules/mathjs/examples/node_modules/neo-async/applyEachSeries.js new file mode 100644 index 0000000..0aece7c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/applyEachSeries.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').applyEachSeries; diff --git a/node_modules/mathjs/examples/node_modules/neo-async/async.js b/node_modules/mathjs/examples/node_modules/neo-async/async.js new file mode 100644 index 0000000..e78eb16 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/async.js @@ -0,0 +1,9184 @@ +(function(global, factory) { + /*jshint -W030 */ + 'use strict'; + typeof exports === 'object' && typeof module !== 'undefined' + ? factory(exports) + : typeof define === 'function' && define.amd + ? define(['exports'], factory) + : global.async + ? factory((global.neo_async = global.neo_async || {})) + : factory((global.async = global.async || {})); +})(this, function(exports) { + 'use strict'; + + var noop = function noop() {}; + var throwError = function throwError() { + throw new Error('Callback was already called.'); + }; + + var DEFAULT_TIMES = 5; + var DEFAULT_INTERVAL = 0; + + var obj = 'object'; + var func = 'function'; + var isArray = Array.isArray; + var nativeKeys = Object.keys; + var nativePush = Array.prototype.push; + var iteratorSymbol = typeof Symbol === func && Symbol.iterator; + + var nextTick, asyncNextTick, asyncSetImmediate; + createImmediate(); + + /** + * @memberof async + * @namespace each + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.each(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(); + * }, num * 10); + * }; + * async.each(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.each(object, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(); + * }, num * 10); + * }; + * async.each(object, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + * @example + * + * // break + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num !== 2); + * }, num * 10); + * }; + * async.each(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 2] + * }); + * + */ + var each = createEach(arrayEach, baseEach, symbolEach); + + /** + * @memberof async + * @namespace map + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.map(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.map(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.map(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.map(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var map = createMap(arrayEachIndex, baseEachIndex, symbolEachIndex, true); + + /** + * @memberof async + * @namespace mapValues + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValues(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2 } + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValues(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2 } + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValues(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2 } + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValues(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2 } + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var mapValues = createMap(arrayEachIndex, baseEachKey, symbolEachKey, false); + + /** + * @memberof async + * @namespace filter + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filter(array, iterator, function(err, res) { + * console.log(res); // [1, 3]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filter(array, iterator, function(err, res) { + * console.log(res); // [1, 3]; + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filter(object, iterator, function(err, res) { + * console.log(res); // [1, 3]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filter(object, iterator, function(err, res) { + * console.log(res); // [1, 3]; + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var filter = createFilter(arrayEachIndexValue, baseEachIndexValue, symbolEachIndexValue, true); + + /** + * @memberof async + * @namespace filterSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3] + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3] + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3] + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + var filterSeries = createFilterSeries(true); + + /** + * @memberof async + * @namespace filterLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3] + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3] + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + var filterLimit = createFilterLimit(true); + + /** + * @memberof async + * @namespace reject + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.reject(array, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.reject(array, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.reject(object, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.reject(object, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var reject = createFilter(arrayEachIndexValue, baseEachIndexValue, symbolEachIndexValue, false); + + /** + * @memberof async + * @namespace rejectSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectSeries(array, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectSeries(object, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectSeries(object, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + var rejectSeries = createFilterSeries(false); + + /** + * @memberof async + * @namespace rejectLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [4, 2] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [4, 2] + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [4, 2] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [4, 2] + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + var rejectLimit = createFilterLimit(false); + + /** + * @memberof async + * @namespace detect + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detect(array, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detect(array, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detect(object, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detect(object, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 'a']] + * }); + * + */ + var detect = createDetect(arrayEachValue, baseEachValue, symbolEachValue, true); + + /** + * @memberof async + * @namespace detectSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectSeries(array, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectSeries(array, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectSeries(object, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectSeries(object, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 'a']] + * }); + * + */ + var detectSeries = createDetectSeries(true); + + /** + * @memberof async + * @namespace detectLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectLimit(array, 2, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectLimit(array, 2, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectLimit(object, 2, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectLimit(object, 2, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 'a']] + * }); + * + */ + var detectLimit = createDetectLimit(true); + + /** + * @memberof async + * @namespace every + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.every(array, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.every(array, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 0], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.every(object, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.every(object, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 'a'], [2, 'c']] + * }); + * + */ + var every = createEvery(arrayEachValue, baseEachValue, symbolEachValue); + + /** + * @memberof async + * @namespace everySeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everySeries(array, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everySeries(array, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everySeries(object, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everySeries(object, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 'a'], [3, 'b'] [2, 'c']] + * }); + * + */ + var everySeries = createEverySeries(); + + /** + * @memberof async + * @namespace everyLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everyLimit(array, 2, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 3, 5, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everyLimit(array, 2, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everyLimit(object, 2, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 3, 5, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everyLimit(object, 2, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e']] + * }); + * + */ + var everyLimit = createEveryLimit(); + + /** + * @memberof async + * @namespace pick + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pick(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3 } + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pick(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3 } + * console.log(order); // [[0, 1], [2, 2], [3, 1], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pick(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3 } + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pick(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3 } + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b'], [4, 'd']] + * }); + * + */ + var pick = createPick(arrayEachIndexValue, baseEachKeyValue, symbolEachKeyValue, true); + + /** + * @memberof async + * @namespace pickSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickSeries(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3 } + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickSeries(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3 } + * console.log(order); // [[0, 1], [3, 1], [2, 2], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickSeries(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3 } + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickSeries(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3 } + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c'], [4, 'd']] + * }); + * + */ + var pickSeries = createPickSeries(true); + + /** + * @memberof async + * @namespace pickLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 5, '2': 3 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 5, '2': 3 } + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 5, c: 3 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 5, c: 3 } + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + var pickLimit = createPickLimit(true); + + /** + * @memberof async + * @namespace omit + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omit(array, iterator, function(err, res) { + * console.log(res); // { '2': 2, '3': 4 } + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omit(array, iterator, function(err, res) { + * console.log(res); // { '2': 2, '3': 4 } + * console.log(order); // [[0, 1], [2, 2], [3, 1], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omit(object, iterator, function(err, res) { + * console.log(res); // { c: 2, d: 4 } + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omit(object, iterator, function(err, res) { + * console.log(res); // { c: 2, d: 4 } + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b'], [4, 'd']] + * }); + * + */ + var omit = createPick(arrayEachIndexValue, baseEachKeyValue, symbolEachKeyValue, false); + + /** + * @memberof async + * @namespace omitSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitSeries(array, iterator, function(err, res) { + * console.log(res); // { '2': 2, '3': 4 } + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitSeries(array, iterator, function(err, res) { + * console.log(res); // { '2': 2, '3': 4 } + * console.log(order); // [[0, 1], [3, 1], [2, 2], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitSeries(object, iterator, function(err, res) { + * console.log(res); // { c: 2, d: 4 } + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitSeries(object, iterator, function(err, res) { + * console.log(res); // { c: 2, d: 4 } + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c'], [4, 'd']] + * }); + * + */ + var omitSeries = createPickSeries(false); + + /** + * @memberof async + * @namespace omitLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '3': 4, '4': 2 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '3': 4, '4': 2 } + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { d: 4, e: 2 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { d: 4, e: 2 } + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + var omitLimit = createPickLimit(false); + + /** + * @memberof async + * @namespace transform + * @param {Array|Object} collection + * @param {Array|Object|Function} [accumulator] + * @param {Function} [iterator] + * @param {Function} [callback] + * @example + * + * // array + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num) + * done(); + * }, num * 10); + * }; + * async.transform(collection, iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4] + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // array with index and accumulator + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * result[index] = num; + * done(); + * }, num * 10); + * }; + * async.transform(collection, {}, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2, '3': 4 } + * console.log(order); // [[1, 0], [2, 2], [3, 1], [4, 3]] + * }); + * + * @example + * + * // object with accumulator + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num); + * done(); + * }, num * 10); + * }; + * async.transform(collection, [], iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4] + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * result[key] = num; + * done(); + * }, num * 10); + * }; + * async.transform(collection, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2, d: 4 } + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b'], [4, 'd']] + * }); + * + */ + var transform = createTransform(arrayEachResult, baseEachResult, symbolEachResult); + + /** + * @memberof async + * @namespace sortBy + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortBy(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.sortBy(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortBy(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.sortBy(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var sortBy = createSortBy(arrayEachIndexValue, baseEachIndexValue, symbolEachIndexValue); + + /** + * @memberof async + * @namespace concat + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concat(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, [num]); + * }, num * 10); + * }; + * async.concat(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concat(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, [num]); + * }, num * 10); + * }; + * async.concat(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var concat = createConcat(arrayEachIndex, baseEachIndex, symbolEachIndex); + + /** + * @memberof async + * @namespace groupBy + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [4.2, 6.4, 6.1]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBy(array, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.1, 6.4] } + * console.log(order); // [4.2, 6.1, 6.4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [4.2, 6.4, 6.1]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBy(array, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.1, 6.4] } + * console.log(order); // [[4.2, 0], [6.1, 2], [6.4, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 4.2, b: 6.4, c: 6.1 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBy(object, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.1, 6.4] } + * console.log(order); // [4.2, 6.1, 6.4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 4.2, b: 6.4, c: 6.1 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBy(object, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.1, 6.4] } + * console.log(order); // [[4.2, 'a'], [6.1, 'c'], [6.4, 'b']] + * }); + * + */ + var groupBy = createGroupBy(arrayEachValue, baseEachValue, symbolEachValue); + + /** + * @memberof async + * @namespace parallel + * @param {Array|Object} tasks - functions + * @param {Function} callback + * @example + * + * var order = []; + * var tasks = [ + * function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 30); + * }, + * function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 40); + * }, + * function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 20); + * } + * ]; + * async.parallel(tasks, function(err, res) { + * console.log(res); // [1, 2, 3, 4]; + * console.log(order); // [1, 4, 2, 3] + * }); + * + * @example + * + * var order = []; + * var tasks = { + * 'a': function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * 'b': function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 30); + * }, + * 'c': function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 40); + * }, + * 'd': function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 20); + * } + * }; + * async.parallel(tasks, function(err, res) { + * console.log(res); // { a: 1, b: 2, c: 3, d:4 } + * console.log(order); // [1, 4, 2, 3] + * }); + * + */ + var parallel = createParallel(arrayEachFunc, baseEachFunc); + + /** + * @memberof async + * @namespace applyEach + */ + var applyEach = createApplyEach(map); + + /** + * @memberof async + * @namespace applyEachSeries + */ + var applyEachSeries = createApplyEach(mapSeries); + + /** + * @memberof async + * @namespace log + */ + var log = createLogger('log'); + + /** + * @memberof async + * @namespace dir + */ + var dir = createLogger('dir'); + + /** + * @version 2.6.2 + * @namespace async + */ + var index = { + VERSION: '2.6.2', + + // Collections + each: each, + eachSeries: eachSeries, + eachLimit: eachLimit, + forEach: each, + forEachSeries: eachSeries, + forEachLimit: eachLimit, + eachOf: each, + eachOfSeries: eachSeries, + eachOfLimit: eachLimit, + forEachOf: each, + forEachOfSeries: eachSeries, + forEachOfLimit: eachLimit, + map: map, + mapSeries: mapSeries, + mapLimit: mapLimit, + mapValues: mapValues, + mapValuesSeries: mapValuesSeries, + mapValuesLimit: mapValuesLimit, + filter: filter, + filterSeries: filterSeries, + filterLimit: filterLimit, + select: filter, + selectSeries: filterSeries, + selectLimit: filterLimit, + reject: reject, + rejectSeries: rejectSeries, + rejectLimit: rejectLimit, + detect: detect, + detectSeries: detectSeries, + detectLimit: detectLimit, + find: detect, + findSeries: detectSeries, + findLimit: detectLimit, + pick: pick, + pickSeries: pickSeries, + pickLimit: pickLimit, + omit: omit, + omitSeries: omitSeries, + omitLimit: omitLimit, + reduce: reduce, + inject: reduce, + foldl: reduce, + reduceRight: reduceRight, + foldr: reduceRight, + transform: transform, + transformSeries: transformSeries, + transformLimit: transformLimit, + sortBy: sortBy, + sortBySeries: sortBySeries, + sortByLimit: sortByLimit, + some: some, + someSeries: someSeries, + someLimit: someLimit, + any: some, + anySeries: someSeries, + anyLimit: someLimit, + every: every, + everySeries: everySeries, + everyLimit: everyLimit, + all: every, + allSeries: everySeries, + allLimit: everyLimit, + concat: concat, + concatSeries: concatSeries, + concatLimit: concatLimit, + groupBy: groupBy, + groupBySeries: groupBySeries, + groupByLimit: groupByLimit, + + // Control Flow + parallel: parallel, + series: series, + parallelLimit: parallelLimit, + tryEach: tryEach, + waterfall: waterfall, + angelFall: angelFall, + angelfall: angelFall, + whilst: whilst, + doWhilst: doWhilst, + until: until, + doUntil: doUntil, + during: during, + doDuring: doDuring, + forever: forever, + compose: compose, + seq: seq, + applyEach: applyEach, + applyEachSeries: applyEachSeries, + queue: queue, + priorityQueue: priorityQueue, + cargo: cargo, + auto: auto, + autoInject: autoInject, + retry: retry, + retryable: retryable, + iterator: iterator, + times: times, + timesSeries: timesSeries, + timesLimit: timesLimit, + race: race, + + // Utils + apply: apply, + nextTick: asyncNextTick, + setImmediate: asyncSetImmediate, + memoize: memoize, + unmemoize: unmemoize, + ensureAsync: ensureAsync, + constant: constant, + asyncify: asyncify, + wrapSync: asyncify, + log: log, + dir: dir, + reflect: reflect, + reflectAll: reflectAll, + timeout: timeout, + createLogger: createLogger, + + // Mode + safe: safe, + fast: fast + }; + + exports['default'] = index; + baseEachSync( + index, + function(func, key) { + exports[key] = func; + }, + nativeKeys(index) + ); + + /** + * @private + */ + function createImmediate(safeMode) { + var delay = function delay(fn) { + var args = slice(arguments, 1); + setTimeout(function() { + fn.apply(null, args); + }); + }; + asyncSetImmediate = typeof setImmediate === func ? setImmediate : delay; + if (typeof process === obj && typeof process.nextTick === func) { + nextTick = /^v0.10/.test(process.version) ? asyncSetImmediate : process.nextTick; + asyncNextTick = /^v0/.test(process.version) ? asyncSetImmediate : process.nextTick; + } else { + asyncNextTick = nextTick = asyncSetImmediate; + } + if (safeMode === false) { + nextTick = function(cb) { + cb(); + }; + } + } + + /* sync functions based on lodash */ + + /** + * Converts `arguments` to an array. + * + * @private + * @param {Array} array = The array to slice. + */ + function createArray(array) { + var index = -1; + var size = array.length; + var result = Array(size); + + while (++index < size) { + result[index] = array[index]; + } + return result; + } + + /** + * Create an array from `start` + * + * @private + * @param {Array} array - The array to slice. + * @param {number} start - The start position. + */ + function slice(array, start) { + var end = array.length; + var index = -1; + var size = end - start; + if (size <= 0) { + return []; + } + var result = Array(size); + + while (++index < size) { + result[index] = array[index + start]; + } + return result; + } + + /** + * @private + * @param {Object} object + */ + function objectClone(object) { + var keys = nativeKeys(object); + var size = keys.length; + var index = -1; + var result = {}; + + while (++index < size) { + var key = keys[index]; + result[key] = object[key]; + } + return result; + } + + /** + * Create an array with all falsey values removed. + * + * @private + * @param {Array} array - The array to compact. + */ + function compact(array) { + var index = -1; + var size = array.length; + var result = []; + + while (++index < size) { + var value = array[index]; + if (value) { + result[result.length] = value; + } + } + return result; + } + + /** + * Create an array of reverse sequence. + * + * @private + * @param {Array} array - The array to reverse. + */ + function reverse(array) { + var index = -1; + var size = array.length; + var result = Array(size); + var resIndex = size; + + while (++index < size) { + result[--resIndex] = array[index]; + } + return result; + } + + /** + * Checks if key exists in object property. + * + * @private + * @param {Object} object - The object to inspect. + * @param {string} key - The key to check. + */ + function has(object, key) { + return object.hasOwnProperty(key); + } + + /** + * Check if target exists in array. + * @private + * @param {Array} array + * @param {*} target + */ + function notInclude(array, target) { + var index = -1; + var size = array.length; + + while (++index < size) { + if (array[index] === target) { + return false; + } + } + return true; + } + + /** + * @private + * @param {Array} array - The array to iterate over. + * @param {Function} iterator - The function invoked per iteration. + */ + function arrayEachSync(array, iterator) { + var index = -1; + var size = array.length; + + while (++index < size) { + iterator(array[index], index); + } + return array; + } + + /** + * @private + * @param {Object} object - The object to iterate over. + * @param {Function} iterator - The function invoked per iteration. + * @param {Array} keys + */ + function baseEachSync(object, iterator, keys) { + var index = -1; + var size = keys.length; + + while (++index < size) { + var key = keys[index]; + iterator(object[key], key); + } + return object; + } + + /** + * @private + * @param {number} n + * @param {Function} iterator + */ + function timesSync(n, iterator) { + var index = -1; + while (++index < n) { + iterator(index); + } + } + + /** + * @private + * @param {Array} array + * @param {number[]} criteria + */ + function sortByCriteria(array, criteria) { + var l = array.length; + var indices = Array(l); + var i; + for (i = 0; i < l; i++) { + indices[i] = i; + } + quickSort(criteria, 0, l - 1, indices); + var result = Array(l); + for (var n = 0; n < l; n++) { + i = indices[n]; + result[n] = i === undefined ? array[n] : array[i]; + } + return result; + } + + function partition(array, i, j, mid, indices) { + var l = i; + var r = j; + while (l <= r) { + i = l; + while (l < r && array[l] < mid) { + l++; + } + while (r >= i && array[r] >= mid) { + r--; + } + if (l > r) { + break; + } + swap(array, indices, l++, r--); + } + return l; + } + + function swap(array, indices, l, r) { + var n = array[l]; + array[l] = array[r]; + array[r] = n; + var i = indices[l]; + indices[l] = indices[r]; + indices[r] = i; + } + + function quickSort(array, i, j, indices) { + if (i === j) { + return; + } + var k = i; + while (++k <= j && array[i] === array[k]) { + var l = k - 1; + if (indices[l] > indices[k]) { + var index = indices[l]; + indices[l] = indices[k]; + indices[k] = index; + } + } + if (k > j) { + return; + } + var p = array[i] > array[k] ? i : k; + k = partition(array, i, j, array[p], indices); + quickSort(array, i, k - 1, indices); + quickSort(array, k, j, indices); + } + + /** + * @Private + */ + function makeConcatResult(array) { + var result = []; + arrayEachSync(array, function(value) { + if (value === noop) { + return; + } + if (isArray(value)) { + nativePush.apply(result, value); + } else { + result.push(value); + } + }); + return result; + } + + /* async functions */ + + /** + * @private + */ + function arrayEach(array, iterator, callback) { + var index = -1; + var size = array.length; + + if (iterator.length === 3) { + while (++index < size) { + iterator(array[index], index, onlyOnce(callback)); + } + } else { + while (++index < size) { + iterator(array[index], onlyOnce(callback)); + } + } + } + + /** + * @private + */ + function baseEach(object, iterator, callback, keys) { + var key; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + iterator(object[key], key, onlyOnce(callback)); + } + } else { + while (++index < size) { + iterator(object[keys[index]], onlyOnce(callback)); + } + } + } + + /** + * @private + */ + function symbolEach(collection, iterator, callback) { + var iter = collection[iteratorSymbol](); + var index = 0; + var item; + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + iterator(item.value, index++, onlyOnce(callback)); + } + } else { + while ((item = iter.next()).done === false) { + index++; + iterator(item.value, onlyOnce(callback)); + } + } + return index; + } + + /** + * @private + */ + function arrayEachResult(array, result, iterator, callback) { + var index = -1; + var size = array.length; + + if (iterator.length === 4) { + while (++index < size) { + iterator(result, array[index], index, onlyOnce(callback)); + } + } else { + while (++index < size) { + iterator(result, array[index], onlyOnce(callback)); + } + } + } + + /** + * @private + */ + function baseEachResult(object, result, iterator, callback, keys) { + var key; + var index = -1; + var size = keys.length; + + if (iterator.length === 4) { + while (++index < size) { + key = keys[index]; + iterator(result, object[key], key, onlyOnce(callback)); + } + } else { + while (++index < size) { + iterator(result, object[keys[index]], onlyOnce(callback)); + } + } + } + + /** + * @private + */ + function symbolEachResult(collection, result, iterator, callback) { + var item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 4) { + while ((item = iter.next()).done === false) { + iterator(result, item.value, index++, onlyOnce(callback)); + } + } else { + while ((item = iter.next()).done === false) { + index++; + iterator(result, item.value, onlyOnce(callback)); + } + } + return index; + } + + /** + * @private + */ + function arrayEachFunc(array, createCallback) { + var index = -1; + var size = array.length; + + while (++index < size) { + array[index](createCallback(index)); + } + } + + /** + * @private + */ + function baseEachFunc(object, createCallback, keys) { + var key; + var index = -1; + var size = keys.length; + + while (++index < size) { + key = keys[index]; + object[key](createCallback(key)); + } + } + + /** + * @private + */ + function arrayEachIndex(array, iterator, createCallback) { + var index = -1; + var size = array.length; + + if (iterator.length === 3) { + while (++index < size) { + iterator(array[index], index, createCallback(index)); + } + } else { + while (++index < size) { + iterator(array[index], createCallback(index)); + } + } + } + + /** + * @private + */ + function baseEachIndex(object, iterator, createCallback, keys) { + var key; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + iterator(object[key], key, createCallback(index)); + } + } else { + while (++index < size) { + iterator(object[keys[index]], createCallback(index)); + } + } + } + + /** + * @private + */ + function symbolEachIndex(collection, iterator, createCallback) { + var item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + iterator(item.value, index, createCallback(index++)); + } + } else { + while ((item = iter.next()).done === false) { + iterator(item.value, createCallback(index++)); + } + } + return index; + } + + /** + * @private + */ + function baseEachKey(object, iterator, createCallback, keys) { + var key; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + iterator(object[key], key, createCallback(key)); + } + } else { + while (++index < size) { + key = keys[index]; + iterator(object[key], createCallback(key)); + } + } + } + + /** + * @private + */ + function symbolEachKey(collection, iterator, createCallback) { + var item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + iterator(item.value, index, createCallback(index++)); + } + } else { + while ((item = iter.next()).done === false) { + iterator(item.value, createCallback(index++)); + } + } + return index; + } + + /** + * @private + */ + function arrayEachValue(array, iterator, createCallback) { + var value; + var index = -1; + var size = array.length; + + if (iterator.length === 3) { + while (++index < size) { + value = array[index]; + iterator(value, index, createCallback(value)); + } + } else { + while (++index < size) { + value = array[index]; + iterator(value, createCallback(value)); + } + } + } + + /** + * @private + */ + function baseEachValue(object, iterator, createCallback, keys) { + var key, value; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + value = object[key]; + iterator(value, key, createCallback(value)); + } + } else { + while (++index < size) { + value = object[keys[index]]; + iterator(value, createCallback(value)); + } + } + } + + /** + * @private + */ + function symbolEachValue(collection, iterator, createCallback) { + var value, item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + value = item.value; + iterator(value, index++, createCallback(value)); + } + } else { + while ((item = iter.next()).done === false) { + index++; + value = item.value; + iterator(value, createCallback(value)); + } + } + return index; + } + + /** + * @private + */ + function arrayEachIndexValue(array, iterator, createCallback) { + var value; + var index = -1; + var size = array.length; + + if (iterator.length === 3) { + while (++index < size) { + value = array[index]; + iterator(value, index, createCallback(index, value)); + } + } else { + while (++index < size) { + value = array[index]; + iterator(value, createCallback(index, value)); + } + } + } + + /** + * @private + */ + function baseEachIndexValue(object, iterator, createCallback, keys) { + var key, value; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + value = object[key]; + iterator(value, key, createCallback(index, value)); + } + } else { + while (++index < size) { + value = object[keys[index]]; + iterator(value, createCallback(index, value)); + } + } + } + + /** + * @private + */ + function symbolEachIndexValue(collection, iterator, createCallback) { + var value, item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + value = item.value; + iterator(value, index, createCallback(index++, value)); + } + } else { + while ((item = iter.next()).done === false) { + value = item.value; + iterator(value, createCallback(index++, value)); + } + } + return index; + } + + /** + * @private + */ + function baseEachKeyValue(object, iterator, createCallback, keys) { + var key, value; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + value = object[key]; + iterator(value, key, createCallback(key, value)); + } + } else { + while (++index < size) { + key = keys[index]; + value = object[key]; + iterator(value, createCallback(key, value)); + } + } + } + + /** + * @private + */ + function symbolEachKeyValue(collection, iterator, createCallback) { + var value, item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + value = item.value; + iterator(value, index, createCallback(index++, value)); + } + } else { + while ((item = iter.next()).done === false) { + value = item.value; + iterator(value, createCallback(index++, value)); + } + } + return index; + } + + /** + * @private + * @param {Function} func + */ + function onlyOnce(func) { + return function(err, res) { + var fn = func; + func = throwError; + fn(err, res); + }; + } + + /** + * @private + * @param {Function} func + */ + function once(func) { + return function(err, res) { + var fn = func; + func = noop; + fn(err, res); + }; + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + */ + function createEach(arrayEach, baseEach, symbolEach) { + return function each(collection, iterator, callback) { + callback = once(callback || noop); + var size, keys; + var completed = 0; + if (isArray(collection)) { + size = collection.length; + arrayEach(collection, iterator, done); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = symbolEach(collection, iterator, done); + size && size === completed && callback(null); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + baseEach(collection, iterator, done, keys); + } + if (!size) { + callback(null); + } + + function done(err, bool) { + if (err) { + callback = once(callback); + callback(err); + } else if (++completed === size) { + callback(null); + } else if (bool === false) { + callback = once(callback); + callback(null); + } + } + }; + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + */ + function createMap(arrayEach, baseEach, symbolEach, useArray) { + var init, clone; + if (useArray) { + init = Array; + clone = createArray; + } else { + init = function() { + return {}; + }; + clone = objectClone; + } + + return function(collection, iterator, callback) { + callback = callback || noop; + var size, keys, result; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = init(size); + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + // TODO: size could be changed + result = init(0); + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, result); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + result = init(size); + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + callback(null, init()); + } + + function createCallback(key) { + return function done(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + callback = once(callback); + callback(err, clone(result)); + return; + } + result[key] = res; + key = null; + if (++completed === size) { + callback(null, result); + } + }; + } + }; + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + * @param {boolean} bool + */ + function createFilter(arrayEach, baseEach, symbolEach, bool) { + return function(collection, iterator, callback) { + callback = callback || noop; + var size, keys, result; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = Array(size); + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + result = []; + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, compact(result)); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + result = Array(size); + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + return callback(null, []); + } + + function createCallback(index, value) { + return function done(err, res) { + if (index === null) { + throwError(); + } + if (err) { + index = null; + callback = once(callback); + callback(err); + return; + } + if (!!res === bool) { + result[index] = value; + } + index = null; + if (++completed === size) { + callback(null, compact(result)); + } + }; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createFilterSeries(bool) { + return function(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, value, keys, iter, item, iterate; + var sync = false; + var completed = 0; + var result = []; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, []); + } + iterate(); + + function arrayIterator() { + value = collection[completed]; + iterator(value, done); + } + + function arrayIteratorWithIndex() { + value = collection[completed]; + iterator(value, completed, done); + } + + function symbolIterator() { + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, completed, done); + } + + function objectIterator() { + key = keys[completed]; + value = collection[key]; + iterator(value, done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + value = collection[key]; + iterator(value, key, done); + } + + function done(err, res) { + if (err) { + callback(err); + return; + } + if (!!res === bool) { + result[result.length] = value; + } + if (++completed === size) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createFilterLimit(bool) { + return function(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, value, keys, iter, item, iterate, result; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + result = []; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, []); + } + result = result || Array(size); + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, createCallback(value, index)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, index, createCallback(value, index)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, compact(result)); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, started, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, compact(result)); + } + } + + function objectIterator() { + index = started++; + if (index < size) { + value = collection[keys[index]]; + iterator(value, createCallback(value, index)); + } + } + + function objectIteratorWithKey() { + index = started++; + if (index < size) { + key = keys[index]; + value = collection[key]; + iterator(value, key, createCallback(value, index)); + } + } + + function createCallback(value, index) { + return function(err, res) { + if (index === null) { + throwError(); + } + if (err) { + index = null; + iterate = noop; + callback = once(callback); + callback(err); + return; + } + if (!!res === bool) { + result[index] = value; + } + index = null; + if (++completed === size) { + callback = onlyOnce(callback); + callback(null, compact(result)); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + }; + } + + /** + * @memberof async + * @namespace eachSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.eachSeries(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(); + * }, num * 10); + * }; + * async.eachSeries(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.eachSeries(object, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(); + * }, num * 10); + * }; + * async.eachSeries(object, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'b']] + * }); + * + * @example + * + * // break + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num !== 3); + * }, num * 10); + * }; + * async.eachSeries(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3] + * }); + */ + function eachSeries(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, keys, iter, item, iterate; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null); + } + iterate(); + + function arrayIterator() { + iterator(collection[completed], done); + } + + function arrayIteratorWithIndex() { + iterator(collection[completed], completed, done); + } + + function symbolIterator() { + item = iter.next(); + item.done ? callback(null) : iterator(item.value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + item.done ? callback(null) : iterator(item.value, completed, done); + } + + function objectIterator() { + iterator(collection[keys[completed]], done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + iterator(collection[key], key, done); + } + + function done(err, bool) { + if (err) { + callback(err); + } else if (++completed === size || bool === false) { + iterate = throwError; + callback(null); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace eachLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.eachLimit(array, 2, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(); + * }, num * 10); + * }; + * async.eachLimit(array, 2, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.eachLimit(object, 2, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(); + * }, num * 10); + * }; + * async.eachLimit(object, 2, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + * @example + * + * // break + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num !== 5); + * }, num * 10); + * }; + * async.eachLimit(array, 2, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3, 5] + * }); + * + */ + function eachLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, keys, iter, item, iterate; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } else { + return callback(null); + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + if (started < size) { + iterator(collection[started++], done); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + iterator(collection[index], index, done); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + started++; + iterator(item.value, done); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, started++, done); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null); + } + } + + function objectIterator() { + if (started < size) { + iterator(collection[keys[started++]], done); + } + } + + function objectIteratorWithKey() { + index = started++; + if (index < size) { + key = keys[index]; + iterator(collection[key], key, done); + } + } + + function done(err, bool) { + if (err || bool === false) { + iterate = noop; + callback = once(callback); + callback(err); + } else if (++completed === size) { + iterator = noop; + iterate = throwError; + callback = onlyOnce(callback); + callback(null); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace mapSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.mapSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.mapSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + function mapSeries(collection, iterator, callback) { + callback = callback || noop; + var size, key, keys, iter, item, result, iterate; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + result = []; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, []); + } + result = result || Array(size); + iterate(); + + function arrayIterator() { + iterator(collection[completed], done); + } + + function arrayIteratorWithIndex() { + iterator(collection[completed], completed, done); + } + + function symbolIterator() { + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, completed, done); + } + + function objectIterator() { + iterator(collection[keys[completed]], done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + iterator(collection[key], key, done); + } + + function done(err, res) { + if (err) { + iterate = throwError; + callback = onlyOnce(callback); + callback(err, createArray(result)); + return; + } + result[completed] = res; + if (++completed === size) { + iterate = throwError; + callback(null, result); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace mapLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3, 4, 2] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.mapLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3, 4, 2] + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3, 4, 2] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.mapLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3, 4, 2] + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + function mapLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, keys, iter, item, result, iterate; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + result = []; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, []); + } + result = result || Array(size); + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + iterator(collection[index], createCallback(index)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + iterator(collection[index], index, createCallback(index)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, started, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function objectIterator() { + index = started++; + if (index < size) { + iterator(collection[keys[index]], createCallback(index)); + } + } + + function objectIteratorWithKey() { + index = started++; + if (index < size) { + key = keys[index]; + iterator(collection[key], key, createCallback(index)); + } + } + + function createCallback(index) { + return function(err, res) { + if (index === null) { + throwError(); + } + if (err) { + index = null; + iterate = noop; + callback = once(callback); + callback(err, createArray(result)); + return; + } + result[index] = res; + index = null; + if (++completed === size) { + iterate = throwError; + callback(null, result); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @memberof async + * @namespace mapValuesSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesSeries(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2 } + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesSeries(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2 } + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesSeries(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2 } + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesSeries(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2 } + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + function mapValuesSeries(collection, iterator, callback) { + callback = callback || noop; + var size, key, keys, iter, item, iterate; + var sync = false; + var result = {}; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, result); + } + iterate(); + + function arrayIterator() { + key = completed; + iterator(collection[completed], done); + } + + function arrayIteratorWithIndex() { + key = completed; + iterator(collection[completed], completed, done); + } + + function symbolIterator() { + key = completed; + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, done); + } + + function symbolIteratorWithKey() { + key = completed; + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, completed, done); + } + + function objectIterator() { + key = keys[completed]; + iterator(collection[key], done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + iterator(collection[key], key, done); + } + + function done(err, res) { + if (err) { + iterate = throwError; + callback = onlyOnce(callback); + callback(err, objectClone(result)); + return; + } + result[key] = res; + if (++completed === size) { + iterate = throwError; + callback(null, result); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace mapValuesLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 5, '2': 3, '3': 4, '4': 2 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 5, '2': 3, '3': 4, '4': 2 } + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 5, c: 3, d: 4, e: 2 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 5, c: 3, d: 4, e: 2 } + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + function mapValuesLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, keys, iter, item, iterate; + var sync = false; + var result = {}; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, result); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + iterator(collection[index], createCallback(index)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + iterator(collection[index], index, createCallback(index)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, started, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function objectIterator() { + index = started++; + if (index < size) { + key = keys[index]; + iterator(collection[key], createCallback(key)); + } + } + + function objectIteratorWithKey() { + index = started++; + if (index < size) { + key = keys[index]; + iterator(collection[key], key, createCallback(key)); + } + } + + function createCallback(key) { + return function(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + iterate = noop; + callback = once(callback); + callback(err, objectClone(result)); + return; + } + result[key] = res; + key = null; + if (++completed === size) { + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + * @param {boolean} bool + */ + function createDetect(arrayEach, baseEach, symbolEach, bool) { + return function(collection, iterator, callback) { + callback = callback || noop; + var size, keys; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + callback(null); + } + + function createCallback(value) { + var called = false; + return function done(err, res) { + if (called) { + throwError(); + } + called = true; + if (err) { + callback = once(callback); + callback(err); + } else if (!!res === bool) { + callback = once(callback); + callback(null, value); + } else if (++completed === size) { + callback(null); + } + }; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createDetectSeries(bool) { + return function(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, value, keys, iter, item, iterate; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null); + } + iterate(); + + function arrayIterator() { + value = collection[completed]; + iterator(value, done); + } + + function arrayIteratorWithIndex() { + value = collection[completed]; + iterator(value, completed, done); + } + + function symbolIterator() { + item = iter.next(); + value = item.value; + item.done ? callback(null) : iterator(value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + value = item.value; + item.done ? callback(null) : iterator(value, completed, done); + } + + function objectIterator() { + value = collection[keys[completed]]; + iterator(value, done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + value = collection[key]; + iterator(value, key, done); + } + + function done(err, res) { + if (err) { + callback(err); + } else if (!!res === bool) { + iterate = throwError; + callback(null, value); + } else if (++completed === size) { + iterate = throwError; + callback(null); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createDetectLimit(bool) { + return function(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, value, keys, iter, item, iterate; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, createCallback(value)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, index, createCallback(value)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + started++; + value = item.value; + iterator(value, createCallback(value)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, started++, createCallback(value)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null); + } + } + + function objectIterator() { + index = started++; + if (index < size) { + value = collection[keys[index]]; + iterator(value, createCallback(value)); + } + } + + function objectIteratorWithKey() { + if (started < size) { + key = keys[started++]; + value = collection[key]; + iterator(value, key, createCallback(value)); + } + } + + function createCallback(value) { + var called = false; + return function(err, res) { + if (called) { + throwError(); + } + called = true; + if (err) { + iterate = noop; + callback = once(callback); + callback(err); + } else if (!!res === bool) { + iterate = noop; + callback = once(callback); + callback(null, value); + } else if (++completed === size) { + callback(null); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + }; + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + * @param {boolean} bool + */ + function createPick(arrayEach, baseEach, symbolEach, bool) { + return function(collection, iterator, callback) { + callback = callback || noop; + var size, keys; + var completed = 0; + var result = {}; + + if (isArray(collection)) { + size = collection.length; + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, result); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + return callback(null, {}); + } + + function createCallback(key, value) { + return function done(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + callback = once(callback); + callback(err, objectClone(result)); + return; + } + if (!!res === bool) { + result[key] = value; + } + key = null; + if (++completed === size) { + callback(null, result); + } + }; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createPickSeries(bool) { + return function(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, value, keys, iter, item, iterate; + var sync = false; + var result = {}; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, {}); + } + iterate(); + + function arrayIterator() { + key = completed; + value = collection[completed]; + iterator(value, done); + } + + function arrayIteratorWithIndex() { + key = completed; + value = collection[completed]; + iterator(value, completed, done); + } + + function symbolIterator() { + key = completed; + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, done); + } + + function symbolIteratorWithKey() { + key = completed; + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, key, done); + } + + function objectIterator() { + key = keys[completed]; + value = collection[key]; + iterator(value, done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + value = collection[key]; + iterator(value, key, done); + } + + function done(err, res) { + if (err) { + callback(err, result); + return; + } + if (!!res === bool) { + result[key] = value; + } + if (++completed === size) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createPickLimit(bool) { + return function(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, value, keys, iter, item, iterate; + var sync = false; + var result = {}; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, {}); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, createCallback(value, index)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, index, createCallback(value, index)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, started, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function objectIterator() { + if (started < size) { + key = keys[started++]; + value = collection[key]; + iterator(value, createCallback(value, key)); + } + } + + function objectIteratorWithKey() { + if (started < size) { + key = keys[started++]; + value = collection[key]; + iterator(value, key, createCallback(value, key)); + } + } + + function createCallback(value, key) { + return function(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + iterate = noop; + callback = once(callback); + callback(err, objectClone(result)); + return; + } + if (!!res === bool) { + result[key] = value; + } + key = null; + if (++completed === size) { + iterate = throwError; + callback = onlyOnce(callback); + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + }; + } + + /** + * @memberof async + * @namespace reduce + * @param {Array|Object} collection + * @param {*} result + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduce(collection, 0, iterator, function(err, res) { + * console.log(res); // 10 + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduce(collection, '', iterator, function(err, res) { + * console.log(res); // '1324' + * console.log(order); // [[1, 0], [3, 1], [2, 2], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduce(collection, '', iterator, function(err, res) { + * console.log(res); // '1324' + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduce(collection, 0, iterator, function(err, res) { + * console.log(res); // 10 + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'b'], [4, 'd']] + * }); + * + */ + function reduce(collection, result, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, keys, iter, item, iterate; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 4 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 4 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 4 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, result); + } + iterate(result); + + function arrayIterator(result) { + iterator(result, collection[completed], done); + } + + function arrayIteratorWithIndex(result) { + iterator(result, collection[completed], completed, done); + } + + function symbolIterator(result) { + item = iter.next(); + item.done ? callback(null, result) : iterator(result, item.value, done); + } + + function symbolIteratorWithKey(result) { + item = iter.next(); + item.done ? callback(null, result) : iterator(result, item.value, completed, done); + } + + function objectIterator(result) { + iterator(result, collection[keys[completed]], done); + } + + function objectIteratorWithKey(result) { + key = keys[completed]; + iterator(result, collection[key], key, done); + } + + function done(err, result) { + if (err) { + callback(err, result); + } else if (++completed === size) { + iterator = throwError; + callback(null, result); + } else if (sync) { + nextTick(function() { + iterate(result); + }); + } else { + sync = true; + iterate(result); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace reduceRight + * @param {Array|Object} collection + * @param {*} result + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduceRight(collection, 0, iterator, function(err, res) { + * console.log(res); // 10 + * console.log(order); // [4, 2, 3, 1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduceRight(collection, '', iterator, function(err, res) { + * console.log(res); // '4231' + * console.log(order); // [[4, 3], [2, 2], [3, 1], [1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduceRight(collection, '', iterator, function(err, res) { + * console.log(res); // '4231' + * console.log(order); // [4, 2, 3, 1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduceRight(collection, 0, iterator, function(err, res) { + * console.log(res); // 10 + * console.log(order); // [[4, 3], [2, 2], [3, 1], [1, 0]] + * }); + * + */ + function reduceRight(collection, result, iterator, callback) { + callback = onlyOnce(callback || noop); + var resIndex, index, key, keys, iter, item, col, iterate; + var sync = false; + + if (isArray(collection)) { + resIndex = collection.length; + iterate = iterator.length === 4 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + col = []; + iter = collection[iteratorSymbol](); + index = -1; + while ((item = iter.next()).done === false) { + col[++index] = item.value; + } + collection = col; + resIndex = col.length; + iterate = iterator.length === 4 ? arrayIteratorWithIndex : arrayIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + resIndex = keys.length; + iterate = iterator.length === 4 ? objectIteratorWithKey : objectIterator; + } + if (!resIndex) { + return callback(null, result); + } + iterate(result); + + function arrayIterator(result) { + iterator(result, collection[--resIndex], done); + } + + function arrayIteratorWithIndex(result) { + iterator(result, collection[--resIndex], resIndex, done); + } + + function objectIterator(result) { + iterator(result, collection[keys[--resIndex]], done); + } + + function objectIteratorWithKey(result) { + key = keys[--resIndex]; + iterator(result, collection[key], key, done); + } + + function done(err, result) { + if (err) { + callback(err, result); + } else if (resIndex === 0) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(function() { + iterate(result); + }); + } else { + sync = true; + iterate(result); + } + sync = false; + } + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + */ + function createTransform(arrayEach, baseEach, symbolEach) { + return function transform(collection, accumulator, iterator, callback) { + if (arguments.length === 3) { + callback = iterator; + iterator = accumulator; + accumulator = undefined; + } + callback = callback || noop; + var size, keys, result; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = accumulator !== undefined ? accumulator : []; + arrayEach(collection, result, iterator, done); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + result = accumulator !== undefined ? accumulator : {}; + size = symbolEach(collection, result, iterator, done); + size && size === completed && callback(null, result); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + result = accumulator !== undefined ? accumulator : {}; + baseEach(collection, result, iterator, done, keys); + } + if (!size) { + callback(null, accumulator !== undefined ? accumulator : result || {}); + } + + function done(err, bool) { + if (err) { + callback = once(callback); + callback(err, isArray(result) ? createArray(result) : objectClone(result)); + } else if (++completed === size) { + callback(null, result); + } else if (bool === false) { + callback = once(callback); + callback(null, isArray(result) ? createArray(result) : objectClone(result)); + } + } + }; + } + + /** + * @memberof async + * @namespace transformSeries + * @param {Array|Object} collection + * @param {Array|Object|Function} [accumulator] + * @param {Function} [iterator] + * @param {Function} [callback] + * @example + * + * // array + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num) + * done(); + * }, num * 10); + * }; + * async.transformSeries(collection, iterator, function(err, res) { + * console.log(res); // [1, 3, 2, 4] + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // array with index and accumulator + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * result[index] = num; + * done(); + * }, num * 10); + * }; + * async.transformSeries(collection, {}, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2, '3': 4 } + * console.log(order); // [[1, 0], [3, 1], [2, 2], [4, 3]] + * }); + * + * @example + * + * // object with accumulator + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num); + * done(); + * }, num * 10); + * }; + * async.transformSeries(collection, [], iterator, function(err, res) { + * console.log(res); // [1, 3, 2, 4] + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * result[key] = num; + * done(); + * }, num * 10); + * }; + * async.transformSeries(collection, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2, d: 4 } + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'b'], [4, 'd']] + * }); + * + */ + function transformSeries(collection, accumulator, iterator, callback) { + if (arguments.length === 3) { + callback = iterator; + iterator = accumulator; + accumulator = undefined; + } + callback = onlyOnce(callback || noop); + var size, key, keys, iter, item, iterate, result; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = accumulator !== undefined ? accumulator : []; + iterate = iterator.length === 4 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + result = accumulator !== undefined ? accumulator : {}; + iterate = iterator.length === 4 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + result = accumulator !== undefined ? accumulator : {}; + iterate = iterator.length === 4 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, accumulator !== undefined ? accumulator : result || {}); + } + iterate(); + + function arrayIterator() { + iterator(result, collection[completed], done); + } + + function arrayIteratorWithIndex() { + iterator(result, collection[completed], completed, done); + } + + function symbolIterator() { + item = iter.next(); + item.done ? callback(null, result) : iterator(result, item.value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + item.done ? callback(null, result) : iterator(result, item.value, completed, done); + } + + function objectIterator() { + iterator(result, collection[keys[completed]], done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + iterator(result, collection[key], key, done); + } + + function done(err, bool) { + if (err) { + callback(err, result); + } else if (++completed === size || bool === false) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace transformLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Array|Object|Function} [accumulator] + * @param {Function} [iterator] + * @param {Function} [callback] + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num); + * done(); + * }, num * 10); + * }; + * async.transformLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index and accumulator + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(result, num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * result[index] = key; + * done(); + * }, num * 10); + * }; + * async.transformLimit(array, 2, {}, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 5, '2': 3, '3': 4, '4': 2 } + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object with accumulator + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num); + * done(); + * }, num * 10); + * }; + * async.transformLimit(object, 2, [], iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(result, num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * result[key] = num; + * done(); + * }, num * 10); + * }; + * async.transformLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + function transformLimit(collection, limit, accumulator, iterator, callback) { + if (arguments.length === 4) { + callback = iterator; + iterator = accumulator; + accumulator = undefined; + } + callback = callback || noop; + var size, index, key, keys, iter, item, iterate, result; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = accumulator !== undefined ? accumulator : []; + iterate = iterator.length === 4 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + result = accumulator !== undefined ? accumulator : {}; + iterate = iterator.length === 4 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + result = accumulator !== undefined ? accumulator : {}; + iterate = iterator.length === 4 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, accumulator !== undefined ? accumulator : result || {}); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + iterator(result, collection[index], onlyOnce(done)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + iterator(result, collection[index], index, onlyOnce(done)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + started++; + iterator(result, item.value, onlyOnce(done)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + iterator(result, item.value, started++, onlyOnce(done)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function objectIterator() { + index = started++; + if (index < size) { + iterator(result, collection[keys[index]], onlyOnce(done)); + } + } + + function objectIteratorWithKey() { + index = started++; + if (index < size) { + key = keys[index]; + iterator(result, collection[key], key, onlyOnce(done)); + } + } + + function done(err, bool) { + if (err || bool === false) { + iterate = noop; + callback(err || null, isArray(result) ? createArray(result) : objectClone(result)); + callback = noop; + } else if (++completed === size) { + iterator = noop; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @private + * @param {function} arrayEach + * @param {function} baseEach + * @param {function} symbolEach + */ + function createSortBy(arrayEach, baseEach, symbolEach) { + return function sortBy(collection, iterator, callback) { + callback = callback || noop; + var size, array, criteria; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + array = Array(size); + criteria = Array(size); + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + array = []; + criteria = []; + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, sortByCriteria(array, criteria)); + } else if (typeof collection === obj) { + var keys = nativeKeys(collection); + size = keys.length; + array = Array(size); + criteria = Array(size); + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + callback(null, []); + } + + function createCallback(index, value) { + var called = false; + array[index] = value; + return function done(err, criterion) { + if (called) { + throwError(); + } + called = true; + criteria[index] = criterion; + if (err) { + callback = once(callback); + callback(err); + } else if (++completed === size) { + callback(null, sortByCriteria(array, criteria)); + } + }; + } + }; + } + + /** + * @memberof async + * @namespace sortBySeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortBySeries(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.sortBySeries(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortBySeries(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.sortBySeries(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + function sortBySeries(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, value, keys, iter, item, array, criteria, iterate; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + array = collection; + criteria = Array(size); + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + array = []; + criteria = []; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + array = Array(size); + criteria = Array(size); + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, []); + } + iterate(); + + function arrayIterator() { + value = collection[completed]; + iterator(value, done); + } + + function arrayIteratorWithIndex() { + value = collection[completed]; + iterator(value, completed, done); + } + + function symbolIterator() { + item = iter.next(); + if (item.done) { + return callback(null, sortByCriteria(array, criteria)); + } + value = item.value; + array[completed] = value; + iterator(value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done) { + return callback(null, sortByCriteria(array, criteria)); + } + value = item.value; + array[completed] = value; + iterator(value, completed, done); + } + + function objectIterator() { + value = collection[keys[completed]]; + array[completed] = value; + iterator(value, done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + value = collection[key]; + array[completed] = value; + iterator(value, key, done); + } + + function done(err, criterion) { + criteria[completed] = criterion; + if (err) { + callback(err); + } else if (++completed === size) { + iterate = throwError; + callback(null, sortByCriteria(array, criteria)); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace sortByLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortByLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4, 5] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.sortByLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4, 5] + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortByLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4, 5] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.sortByLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4, 5] + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + function sortByLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, value, array, keys, iter, item, criteria, iterate; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + array = collection; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + array = []; + criteria = []; + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + array = Array(size); + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, []); + } + criteria = criteria || Array(size); + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + if (started < size) { + value = collection[started]; + iterator(value, createCallback(value, started++)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, index, createCallback(value, index)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + value = item.value; + array[started] = value; + iterator(value, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, sortByCriteria(array, criteria)); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + value = item.value; + array[started] = value; + iterator(value, started, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, sortByCriteria(array, criteria)); + } + } + + function objectIterator() { + if (started < size) { + value = collection[keys[started]]; + array[started] = value; + iterator(value, createCallback(value, started++)); + } + } + + function objectIteratorWithKey() { + if (started < size) { + key = keys[started]; + value = collection[key]; + array[started] = value; + iterator(value, key, createCallback(value, started++)); + } + } + + function createCallback(value, index) { + var called = false; + return function(err, criterion) { + if (called) { + throwError(); + } + called = true; + criteria[index] = criterion; + if (err) { + iterate = noop; + callback(err); + callback = noop; + } else if (++completed === size) { + callback(null, sortByCriteria(array, criteria)); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @memberof async + * @namespace some + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.some(array, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.some(array, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.some(object, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.some(object, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 'a']] + * }); + * + */ + function some(collection, iterator, callback) { + callback = callback || noop; + detect(collection, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !!res); + } + } + + /** + * @memberof async + * @namespace someSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someSeries(array, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someSeries(array, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someSeries(object, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someSeries(object, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 'a']] + * }); + * + */ + function someSeries(collection, iterator, callback) { + callback = callback || noop; + detectSeries(collection, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !!res); + } + } + + /** + * @memberof async + * @namespace someLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someLimit(array, 2, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someLimit(array, 2, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someLimit(object, 2, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someLimit(object, 2, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 'a']] + * }); + * + */ + function someLimit(collection, limit, iterator, callback) { + callback = callback || noop; + detectLimit(collection, limit, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !!res); + } + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + */ + function createEvery(arrayEach, baseEach, symbolEach) { + var deny = createDetect(arrayEach, baseEach, symbolEach, false); + + return function every(collection, iterator, callback) { + callback = callback || noop; + deny(collection, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !res); + } + }; + } + + /** + * @private + */ + function createEverySeries() { + var denySeries = createDetectSeries(false); + + return function everySeries(collection, iterator, callback) { + callback = callback || noop; + denySeries(collection, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !res); + } + }; + } + + /** + * @private + */ + function createEveryLimit() { + var denyLimit = createDetectLimit(false); + + return function everyLimit(collection, limit, iterator, callback) { + callback = callback || noop; + denyLimit(collection, limit, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !res); + } + }; + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + */ + function createConcat(arrayEach, baseEach, symbolEach) { + return function concat(collection, iterator, callback) { + callback = callback || noop; + var size, result; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = Array(size); + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + result = []; + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, result); + } else if (typeof collection === obj) { + var keys = nativeKeys(collection); + size = keys.length; + result = Array(size); + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + callback(null, []); + } + + function createCallback(index) { + return function done(err, res) { + if (index === null) { + throwError(); + } + if (err) { + index = null; + callback = once(callback); + arrayEachSync(result, function(array, index) { + if (array === undefined) { + result[index] = noop; + } + }); + callback(err, makeConcatResult(result)); + return; + } + switch (arguments.length) { + case 0: + case 1: + result[index] = noop; + break; + case 2: + result[index] = res; + break; + default: + result[index] = slice(arguments, 1); + break; + } + index = null; + if (++completed === size) { + callback(null, makeConcatResult(result)); + } + }; + } + }; + } + + /** + * @memberof async + * @namespace concatSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + function concatSeries(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, keys, iter, item, iterate; + var sync = false; + var result = []; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, result); + } + iterate(); + + function arrayIterator() { + iterator(collection[completed], done); + } + + function arrayIteratorWithIndex() { + iterator(collection[completed], completed, done); + } + + function symbolIterator() { + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, completed, done); + } + + function objectIterator() { + iterator(collection[keys[completed]], done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + iterator(collection[key], key, done); + } + + function done(err, array) { + if (isArray(array)) { + nativePush.apply(result, array); + } else if (arguments.length >= 2) { + nativePush.apply(result, slice(arguments, 1)); + } + if (err) { + callback(err, result); + } else if (++completed === size) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace concatLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, [num]); + * }, num * 10); + * }; + * async.cocnatLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.cocnatLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + function concatLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, key, iter, item, iterate, result; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + result = []; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + var keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, []); + } + result = result || Array(size); + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + if (started < size) { + iterator(collection[started], createCallback(started++)); + } + } + + function arrayIteratorWithIndex() { + if (started < size) { + iterator(collection[started], started, createCallback(started++)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, makeConcatResult(result)); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, started, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, makeConcatResult(result)); + } + } + + function objectIterator() { + if (started < size) { + iterator(collection[keys[started]], createCallback(started++)); + } + } + + function objectIteratorWithKey() { + if (started < size) { + key = keys[started]; + iterator(collection[key], key, createCallback(started++)); + } + } + + function createCallback(index) { + return function(err, res) { + if (index === null) { + throwError(); + } + if (err) { + index = null; + iterate = noop; + callback = once(callback); + arrayEachSync(result, function(array, index) { + if (array === undefined) { + result[index] = noop; + } + }); + callback(err, makeConcatResult(result)); + return; + } + switch (arguments.length) { + case 0: + case 1: + result[index] = noop; + break; + case 2: + result[index] = res; + break; + default: + result[index] = slice(arguments, 1); + break; + } + index = null; + if (++completed === size) { + iterate = throwError; + callback(null, makeConcatResult(result)); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + */ + function createGroupBy(arrayEach, baseEach, symbolEach) { + return function groupBy(collection, iterator, callback) { + callback = callback || noop; + var size; + var completed = 0; + var result = {}; + + if (isArray(collection)) { + size = collection.length; + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, result); + } else if (typeof collection === obj) { + var keys = nativeKeys(collection); + size = keys.length; + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + callback(null, {}); + } + + function createCallback(value) { + var called = false; + return function done(err, key) { + if (called) { + throwError(); + } + called = true; + if (err) { + callback = once(callback); + callback(err, objectClone(result)); + return; + } + var array = result[key]; + if (!array) { + result[key] = [value]; + } else { + array.push(value); + } + if (++completed === size) { + callback(null, result); + } + }; + } + }; + } + + /** + * @memberof async + * @namespace groupBySeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [4.2, 6.4, 6.1]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBySeries(array, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.4, 6.1] } + * console.log(order); // [4.2, 6.4, 6.1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [4.2, 6.4, 6.1]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBySeries(array, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.4, 6.1] } + * console.log(order); // [[4.2, 0], [6.4, 1], [6.1, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 4.2, b: 6.4, c: 6.1 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBySeries(object, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.4, 6.1] } + * console.log(order); // [4.2, 6.4, 6.1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 4.2, b: 6.4, c: 6.1 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBySeries(object, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.4, 6.1] } + * console.log(order); // [[4.2, 'a'], [6.4, 'b'], [6.1, 'c']] + * }); + * + */ + function groupBySeries(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, value, keys, iter, item, iterate; + var sync = false; + var completed = 0; + var result = {}; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, result); + } + iterate(); + + function arrayIterator() { + value = collection[completed]; + iterator(value, done); + } + + function arrayIteratorWithIndex() { + value = collection[completed]; + iterator(value, completed, done); + } + + function symbolIterator() { + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, completed, done); + } + + function objectIterator() { + value = collection[keys[completed]]; + iterator(value, done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + value = collection[key]; + iterator(value, key, done); + } + + function done(err, key) { + if (err) { + iterate = throwError; + callback = onlyOnce(callback); + callback(err, objectClone(result)); + return; + } + var array = result[key]; + if (!array) { + result[key] = [value]; + } else { + array.push(value); + } + if (++completed === size) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace groupByLimit + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1.1, 5.9, 3.2, 3.9, 2.1]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupByLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '1': [1.1], '3': [3.2, 3.9], '5': [5.9], '2': [2.1] } + * console.log(order); // [1.1, 3.2, 5.9, 2.1, 3.9] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1.1, 5.9, 3.2, 3.9, 2.1]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupByLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '1': [1.1], '3': [3.2, 3.9], '5': [5.9], '2': [2.1] } + * console.log(order); // [[1.1, 0], [3.2, 2], [5.9, 1], [2.1, 4], [3.9, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1.1, b: 5.9, c: 3.2, d: 3.9, e: 2.1 } + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupByLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { '1': [1.1], '3': [3.2, 3.9], '5': [5.9], '2': [2.1] } + * console.log(order); // [1.1, 3.2, 5.9, 2.1, 3.9] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1.1, b: 5.9, c: 3.2, d: 3.9, e: 2.1 } + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupByLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { '1': [1.1], '3': [3.2, 3.9], '5': [5.9], '2': [2.1] } + * console.log(order); // [[1.1, 'a'], [3.2, 'c'], [5.9, 'b'], [2.1, 'e'], [3.9, 'd']] + * }); + * + */ + function groupByLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, value, keys, iter, item, iterate; + var sync = false; + var started = 0; + var completed = 0; + var result = {}; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, result); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + if (started < size) { + value = collection[started++]; + iterator(value, createCallback(value)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, index, createCallback(value)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + started++; + value = item.value; + iterator(value, createCallback(value)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, started++, createCallback(value)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function objectIterator() { + if (started < size) { + value = collection[keys[started++]]; + iterator(value, createCallback(value)); + } + } + + function objectIteratorWithKey() { + if (started < size) { + key = keys[started++]; + value = collection[key]; + iterator(value, key, createCallback(value)); + } + } + + function createCallback(value) { + var called = false; + return function(err, key) { + if (called) { + throwError(); + } + called = true; + if (err) { + iterate = noop; + callback = once(callback); + callback(err, objectClone(result)); + return; + } + var array = result[key]; + if (!array) { + result[key] = [value]; + } else { + array.push(value); + } + if (++completed === size) { + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + */ + function createParallel(arrayEach, baseEach) { + return function parallel(tasks, callback) { + callback = callback || noop; + var size, keys, result; + var completed = 0; + + if (isArray(tasks)) { + size = tasks.length; + result = Array(size); + arrayEach(tasks, createCallback); + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + size = keys.length; + result = {}; + baseEach(tasks, createCallback, keys); + } + if (!size) { + callback(null, result); + } + + function createCallback(key) { + return function(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + callback = once(callback); + callback(err, result); + return; + } + result[key] = arguments.length <= 2 ? res : slice(arguments, 1); + key = null; + if (++completed === size) { + callback(null, result); + } + }; + } + }; + } + + /** + * @memberof async + * @namespace series + * @param {Array|Object} tasks - functions + * @param {Function} callback + * @example + * + * var order = []; + * var tasks = [ + * function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 30); + * }, + * function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 40); + * }, + * function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 20); + * } + * ]; + * async.series(tasks, function(err, res) { + * console.log(res); // [1, 2, 3, 4]; + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * var order = []; + * var tasks = { + * 'a': function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * 'b': function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 30); + * }, + * 'c': function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 40); + * }, + * 'd': function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 20); + * } + * }; + * async.series(tasks, function(err, res) { + * console.log(res); // { a: 1, b: 2, c: 3, d:4 } + * console.log(order); // [1, 4, 2, 3] + * }); + * + */ + function series(tasks, callback) { + callback = callback || noop; + var size, key, keys, result, iterate; + var sync = false; + var completed = 0; + + if (isArray(tasks)) { + size = tasks.length; + result = Array(size); + iterate = arrayIterator; + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + size = keys.length; + result = {}; + iterate = objectIterator; + } else { + return callback(null); + } + if (!size) { + return callback(null, result); + } + iterate(); + + function arrayIterator() { + key = completed; + tasks[completed](done); + } + + function objectIterator() { + key = keys[completed]; + tasks[key](done); + } + + function done(err, res) { + if (err) { + iterate = throwError; + callback = onlyOnce(callback); + callback(err, result); + return; + } + result[key] = arguments.length <= 2 ? res : slice(arguments, 1); + if (++completed === size) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace parallelLimit + * @param {Array|Object} tasks - functions + * @param {number} limit - limit >= 1 + * @param {Function} callback + * @example + * + * var order = []; + * var tasks = [ + * function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 50); + * }, + * function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 30); + * }, + * function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 40); + * } + * ]; + * async.parallelLimit(tasks, 2, function(err, res) { + * console.log(res); // [1, 2, 3, 4]; + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * var order = []; + * var tasks = { + * 'a': function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * 'b': function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 50); + * }, + * 'c': function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 20); + * }, + * 'd': function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 40); + * } + * }; + * async.parallelLimit(tasks, 2, function(err, res) { + * console.log(res); // { a: 1, b: 2, c: 3, d:4 } + * console.log(order); // [1, 3, 2, 4] + * }); + * + */ + function parallelLimit(tasks, limit, callback) { + callback = callback || noop; + var size, index, key, keys, result, iterate; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(tasks)) { + size = tasks.length; + result = Array(size); + iterate = arrayIterator; + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + size = keys.length; + result = {}; + iterate = objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, result); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + tasks[index](createCallback(index)); + } + } + + function objectIterator() { + if (started < size) { + key = keys[started++]; + tasks[key](createCallback(key)); + } + } + + function createCallback(key) { + return function(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + iterate = noop; + callback = once(callback); + callback(err, result); + return; + } + result[key] = arguments.length <= 2 ? res : slice(arguments, 1); + key = null; + if (++completed === size) { + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @memberof async + * @namespace tryEach + * @param {Array|Object} tasks - functions + * @param {Function} callback + * @example + * + * var tasks = [ + * function(done) { + * setTimeout(function() { + * done(new Error('error')); + * }, 10); + * }, + * function(done) { + * setTimeout(function() { + * done(null, 2); + * }, 10); + * } + * ]; + * async.tryEach(tasks, function(err, res) { + * console.log(res); // 2 + * }); + * + * @example + * + * var tasks = [ + * function(done) { + * setTimeout(function() { + * done(new Error('error1')); + * }, 10); + * }, + * function(done) { + * setTimeout(function() { + * done(new Error('error2'); + * }, 10); + * } + * ]; + * async.tryEach(tasks, function(err, res) { + * console.log(err); // error2 + * console.log(res); // undefined + * }); + * + */ + function tryEach(tasks, callback) { + callback = callback || noop; + var size, keys, iterate; + var sync = false; + var completed = 0; + + if (isArray(tasks)) { + size = tasks.length; + iterate = arrayIterator; + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + size = keys.length; + iterate = objectIterator; + } + if (!size) { + return callback(null); + } + iterate(); + + function arrayIterator() { + tasks[completed](done); + } + + function objectIterator() { + tasks[keys[completed]](done); + } + + function done(err, res) { + if (!err) { + if (arguments.length <= 2) { + callback(null, res); + } else { + callback(null, slice(arguments, 1)); + } + } else if (++completed === size) { + callback(err); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * check for waterfall tasks + * @private + * @param {Array} tasks + * @param {Function} callback + * @return {boolean} + */ + function checkWaterfallTasks(tasks, callback) { + if (!isArray(tasks)) { + callback(new Error('First argument to waterfall must be an array of functions')); + return false; + } + if (tasks.length === 0) { + callback(null); + return false; + } + return true; + } + + /** + * check for waterfall tasks + * @private + * @param {function} func + * @param {Array|Object} args - arguments + * @return {function} next + */ + function waterfallIterator(func, args, next) { + switch (args.length) { + case 0: + case 1: + return func(next); + case 2: + return func(args[1], next); + case 3: + return func(args[1], args[2], next); + case 4: + return func(args[1], args[2], args[3], next); + case 5: + return func(args[1], args[2], args[3], args[4], next); + case 6: + return func(args[1], args[2], args[3], args[4], args[5], next); + default: + args = slice(args, 1); + args.push(next); + return func.apply(null, args); + } + } + + /** + * @memberof async + * @namespace waterfall + * @param {Array} tasks - functions + * @param {Function} callback + * @example + * + * var order = []; + * var tasks = [ + * function(next) { + * setTimeout(function() { + * order.push(1); + * next(null, 1); + * }, 10); + * }, + * function(arg1, next) { + * setTimeout(function() { + * order.push(2); + * next(null, 1, 2); + * }, 30); + * }, + * function(arg1, arg2, next) { + * setTimeout(function() { + * order.push(3); + * next(null, 3); + * }, 20); + * }, + * function(arg1, next) { + * setTimeout(function() { + * order.push(4); + * next(null, 1, 2, 3, 4); + * }, 40); + * } + * ]; + * async.waterfall(tasks, function(err, arg1, arg2, arg3, arg4) { + * console.log(arg1, arg2, arg3, arg4); // 1 2 3 4 + * }); + * + */ + function waterfall(tasks, callback) { + callback = callback || noop; + if (!checkWaterfallTasks(tasks, callback)) { + return; + } + var func, args, done, sync; + var completed = 0; + var size = tasks.length; + waterfallIterator(tasks[0], [], createCallback(0)); + + function iterate() { + waterfallIterator(func, args, createCallback(func)); + } + + function createCallback(index) { + return function next(err, res) { + if (index === undefined) { + callback = noop; + throwError(); + } + index = undefined; + if (err) { + done = callback; + callback = throwError; + done(err); + return; + } + if (++completed === size) { + done = callback; + callback = throwError; + if (arguments.length <= 2) { + done(err, res); + } else { + done.apply(null, createArray(arguments)); + } + return; + } + if (sync) { + args = arguments; + func = tasks[completed] || throwError; + nextTick(iterate); + } else { + sync = true; + waterfallIterator(tasks[completed] || throwError, arguments, createCallback(completed)); + } + sync = false; + }; + } + } + + /** + * `angelFall` is like `waterfall` and inject callback to last argument of next task. + * + * @memberof async + * @namespace angelFall + * @param {Array} tasks - functions + * @param {Function} callback + * @example + * + * var order = []; + * var tasks = [ + * function(next) { + * setTimeout(function() { + * order.push(1); + * next(null, 1); + * }, 10); + * }, + * function(arg1, empty, next) { + * setTimeout(function() { + * order.push(2); + * next(null, 1, 2); + * }, 30); + * }, + * function(next) { + * setTimeout(function() { + * order.push(3); + * next(null, 3); + * }, 20); + * }, + * function(arg1, empty1, empty2, empty3, next) { + * setTimeout(function() { + * order.push(4); + * next(null, 1, 2, 3, 4); + * }, 40); + * } + * ]; + * async.angelFall(tasks, function(err, arg1, arg2, arg3, arg4) { + * console.log(arg1, arg2, arg3, arg4); // 1 2 3 4 + * }); + * + */ + function angelFall(tasks, callback) { + callback = callback || noop; + if (!checkWaterfallTasks(tasks, callback)) { + return; + } + var completed = 0; + var sync = false; + var size = tasks.length; + var func = tasks[completed]; + var args = []; + var iterate = function() { + switch (func.length) { + case 0: + try { + next(null, func()); + } catch (e) { + next(e); + } + return; + case 1: + return func(next); + case 2: + return func(args[1], next); + case 3: + return func(args[1], args[2], next); + case 4: + return func(args[1], args[2], args[3], next); + case 5: + return func(args[1], args[2], args[3], args[4], next); + default: + args = slice(args, 1); + args[func.length - 1] = next; + return func.apply(null, args); + } + }; + iterate(); + + function next(err, res) { + if (err) { + iterate = throwError; + callback = onlyOnce(callback); + callback(err); + return; + } + if (++completed === size) { + iterate = throwError; + var done = callback; + callback = throwError; + if (arguments.length === 2) { + done(err, res); + } else { + done.apply(null, createArray(arguments)); + } + return; + } + func = tasks[completed]; + args = arguments; + if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace whilst + * @param {Function} test + * @param {Function} iterator + * @param {Function} callback + */ + function whilst(test, iterator, callback) { + callback = callback || noop; + var sync = false; + if (test()) { + iterate(); + } else { + callback(null); + } + + function iterate() { + if (sync) { + nextTick(next); + } else { + sync = true; + iterator(done); + } + sync = false; + } + + function next() { + iterator(done); + } + + function done(err, arg) { + if (err) { + return callback(err); + } + if (arguments.length <= 2) { + if (test(arg)) { + iterate(); + } else { + callback(null, arg); + } + return; + } + arg = slice(arguments, 1); + if (test.apply(null, arg)) { + iterate(); + } else { + callback.apply(null, [null].concat(arg)); + } + } + } + + /** + * @memberof async + * @namespace doWhilst + * @param {Function} iterator + * @param {Function} test + * @param {Function} callback + */ + function doWhilst(iterator, test, callback) { + callback = callback || noop; + var sync = false; + next(); + + function iterate() { + if (sync) { + nextTick(next); + } else { + sync = true; + iterator(done); + } + sync = false; + } + + function next() { + iterator(done); + } + + function done(err, arg) { + if (err) { + return callback(err); + } + if (arguments.length <= 2) { + if (test(arg)) { + iterate(); + } else { + callback(null, arg); + } + return; + } + arg = slice(arguments, 1); + if (test.apply(null, arg)) { + iterate(); + } else { + callback.apply(null, [null].concat(arg)); + } + } + } + + /** + * @memberof async + * @namespace until + * @param {Function} test + * @param {Function} iterator + * @param {Function} callback + */ + function until(test, iterator, callback) { + callback = callback || noop; + var sync = false; + if (!test()) { + iterate(); + } else { + callback(null); + } + + function iterate() { + if (sync) { + nextTick(next); + } else { + sync = true; + iterator(done); + } + sync = false; + } + + function next() { + iterator(done); + } + + function done(err, arg) { + if (err) { + return callback(err); + } + if (arguments.length <= 2) { + if (!test(arg)) { + iterate(); + } else { + callback(null, arg); + } + return; + } + arg = slice(arguments, 1); + if (!test.apply(null, arg)) { + iterate(); + } else { + callback.apply(null, [null].concat(arg)); + } + } + } + + /** + * @memberof async + * @namespace doUntil + * @param {Function} iterator + * @param {Function} test + * @param {Function} callback + */ + function doUntil(iterator, test, callback) { + callback = callback || noop; + var sync = false; + next(); + + function iterate() { + if (sync) { + nextTick(next); + } else { + sync = true; + iterator(done); + } + sync = false; + } + + function next() { + iterator(done); + } + + function done(err, arg) { + if (err) { + return callback(err); + } + if (arguments.length <= 2) { + if (!test(arg)) { + iterate(); + } else { + callback(null, arg); + } + return; + } + arg = slice(arguments, 1); + if (!test.apply(null, arg)) { + iterate(); + } else { + callback.apply(null, [null].concat(arg)); + } + } + } + + /** + * @memberof async + * @namespace during + * @param {Function} test + * @param {Function} iterator + * @param {Function} callback + */ + function during(test, iterator, callback) { + callback = callback || noop; + _test(); + + function _test() { + test(iterate); + } + + function iterate(err, truth) { + if (err) { + return callback(err); + } + if (truth) { + iterator(done); + } else { + callback(null); + } + } + + function done(err) { + if (err) { + return callback(err); + } + _test(); + } + } + + /** + * @memberof async + * @namespace doDuring + * @param {Function} test + * @param {Function} iterator + * @param {Function} callback + */ + function doDuring(iterator, test, callback) { + callback = callback || noop; + iterate(null, true); + + function iterate(err, truth) { + if (err) { + return callback(err); + } + if (truth) { + iterator(done); + } else { + callback(null); + } + } + + function done(err, res) { + if (err) { + return callback(err); + } + switch (arguments.length) { + case 0: + case 1: + test(iterate); + break; + case 2: + test(res, iterate); + break; + default: + var args = slice(arguments, 1); + args.push(iterate); + test.apply(null, args); + break; + } + } + } + + /** + * @memberof async + * @namespace forever + */ + function forever(iterator, callback) { + var sync = false; + iterate(); + + function iterate() { + iterator(next); + } + + function next(err) { + if (err) { + if (callback) { + return callback(err); + } + throw err; + } + if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace compose + */ + function compose() { + return seq.apply(null, reverse(arguments)); + } + + /** + * @memberof async + * @namespace seq + */ + function seq(/* functions... */) { + var fns = createArray(arguments); + + return function() { + var self = this; + var args = createArray(arguments); + var callback = args[args.length - 1]; + if (typeof callback === func) { + args.pop(); + } else { + callback = noop; + } + reduce(fns, args, iterator, done); + + function iterator(newargs, fn, callback) { + var func = function(err) { + var nextargs = slice(arguments, 1); + callback(err, nextargs); + }; + newargs.push(func); + fn.apply(self, newargs); + } + + function done(err, res) { + res = isArray(res) ? res : [res]; + res.unshift(err); + callback.apply(self, res); + } + }; + } + + function createApplyEach(func) { + return function applyEach(fns /* arguments */) { + var go = function() { + var self = this; + var args = createArray(arguments); + var callback = args.pop() || noop; + return func(fns, iterator, callback); + + function iterator(fn, done) { + fn.apply(self, args.concat([done])); + } + }; + if (arguments.length > 1) { + var args = slice(arguments, 1); + return go.apply(this, args); + } else { + return go; + } + }; + } + + /** + * @see https://github.com/caolan/async/blob/master/lib/internal/DoublyLinkedList.js + */ + function DLL() { + this.head = null; + this.tail = null; + this.length = 0; + } + + DLL.prototype._removeLink = function(node) { + var prev = node.prev; + var next = node.next; + if (prev) { + prev.next = next; + } else { + this.head = next; + } + if (next) { + next.prev = prev; + } else { + this.tail = prev; + } + node.prev = null; + node.next = null; + this.length--; + return node; + }; + + DLL.prototype.empty = DLL; + + DLL.prototype._setInitial = function(node) { + this.length = 1; + this.head = this.tail = node; + }; + + DLL.prototype.insertBefore = function(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) { + node.prev.next = newNode; + } else { + this.head = newNode; + } + node.prev = newNode; + this.length++; + }; + + DLL.prototype.unshift = function(node) { + if (this.head) { + this.insertBefore(this.head, node); + } else { + this._setInitial(node); + } + }; + + DLL.prototype.push = function(node) { + var tail = this.tail; + if (tail) { + node.prev = tail; + node.next = tail.next; + this.tail = node; + tail.next = node; + this.length++; + } else { + this._setInitial(node); + } + }; + + DLL.prototype.shift = function() { + return this.head && this._removeLink(this.head); + }; + + DLL.prototype.splice = function(end) { + var task; + var tasks = []; + while (end-- && (task = this.shift())) { + tasks.push(task); + } + return tasks; + }; + + DLL.prototype.remove = function(test) { + var node = this.head; + while (node) { + if (test(node)) { + this._removeLink(node); + } + node = node.next; + } + return this; + }; + + /** + * @private + */ + function baseQueue(isQueue, worker, concurrency, payload) { + if (concurrency === undefined) { + concurrency = 1; + } else if (isNaN(concurrency) || concurrency < 1) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var workersList = []; + var _callback, _unshift; + + var q = { + _tasks: new DLL(), + concurrency: concurrency, + payload: payload, + saturated: noop, + unsaturated: noop, + buffer: concurrency / 4, + empty: noop, + drain: noop, + error: noop, + started: false, + paused: false, + push: push, + kill: kill, + unshift: unshift, + remove: remove, + process: isQueue ? runQueue : runCargo, + length: getLength, + running: running, + workersList: getWorkersList, + idle: idle, + pause: pause, + resume: resume, + _worker: worker + }; + return q; + + function push(tasks, callback) { + _insert(tasks, callback); + } + + function unshift(tasks, callback) { + _insert(tasks, callback, true); + } + + function _exec(task) { + var item = { + data: task, + callback: _callback + }; + if (_unshift) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + nextTick(q.process); + } + + function _insert(tasks, callback, unshift) { + if (callback == null) { + callback = noop; + } else if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + var _tasks = isArray(tasks) ? tasks : [tasks]; + + if (tasks === undefined || !_tasks.length) { + if (q.idle()) { + nextTick(q.drain); + } + return; + } + + _unshift = unshift; + _callback = callback; + arrayEachSync(_tasks, _exec); + // Avoid leaking the callback + _callback = undefined; + } + + function kill() { + q.drain = noop; + q._tasks.empty(); + } + + function _next(q, tasks) { + var called = false; + return function done(err, res) { + if (called) { + throwError(); + } + called = true; + + workers--; + var task; + var index = -1; + var size = workersList.length; + var taskIndex = -1; + var taskSize = tasks.length; + var useApply = arguments.length > 2; + var args = useApply && createArray(arguments); + while (++taskIndex < taskSize) { + task = tasks[taskIndex]; + while (++index < size) { + if (workersList[index] === task) { + if (index === 0) { + workersList.shift(); + } else { + workersList.splice(index, 1); + } + index = size; + size--; + } + } + index = -1; + if (useApply) { + task.callback.apply(task, args); + } else { + task.callback(err, res); + } + if (err) { + q.error(err, task.data); + } + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q._tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + } + + function runQueue() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + workers++; + workersList.push(task); + if (q._tasks.length === 0) { + q.empty(); + } + if (workers === q.concurrency) { + q.saturated(); + } + var done = _next(q, [task]); + worker(task.data, done); + } + } + + function runCargo() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var tasks = q._tasks.splice(q.payload || q._tasks.length); + var index = -1; + var size = tasks.length; + var data = Array(size); + while (++index < size) { + data[index] = tasks[index].data; + } + workers++; + nativePush.apply(workersList, tasks); + if (q._tasks.length === 0) { + q.empty(); + } + if (workers === q.concurrency) { + q.saturated(); + } + var done = _next(q, tasks); + worker(data, done); + } + } + + function getLength() { + return q._tasks.length; + } + + function running() { + return workers; + } + + function getWorkersList() { + return workersList; + } + + function idle() { + return q.length() + workers === 0; + } + + function pause() { + q.paused = true; + } + + function _resume() { + nextTick(q.process); + } + + function resume() { + if (q.paused === false) { + return; + } + q.paused = false; + var count = q.concurrency < q._tasks.length ? q.concurrency : q._tasks.length; + timesSync(count, _resume); + } + + /** + * @param {Function} test + */ + function remove(test) { + q._tasks.remove(test); + } + } + + /** + * @memberof async + * @namespace queue + */ + function queue(worker, concurrency) { + return baseQueue(true, worker, concurrency); + } + + /** + * @memberof async + * @namespace priorityQueue + */ + function priorityQueue(worker, concurrency) { + var q = baseQueue(true, worker, concurrency); + q.push = push; + delete q.unshift; + return q; + + function push(tasks, priority, callback) { + q.started = true; + priority = priority || 0; + var _tasks = isArray(tasks) ? tasks : [tasks]; + var taskSize = _tasks.length; + + if (tasks === undefined || taskSize === 0) { + if (q.idle()) { + nextTick(q.drain); + } + return; + } + + callback = typeof callback === func ? callback : noop; + var nextNode = q._tasks.head; + while (nextNode && priority >= nextNode.priority) { + nextNode = nextNode.next; + } + while (taskSize--) { + var item = { + data: _tasks[taskSize], + priority: priority, + callback: callback + }; + if (nextNode) { + q._tasks.insertBefore(nextNode, item); + } else { + q._tasks.push(item); + } + nextTick(q.process); + } + } + } + + /** + * @memberof async + * @namespace cargo + */ + function cargo(worker, payload) { + return baseQueue(false, worker, 1, payload); + } + + /** + * @memberof async + * @namespace auto + * @param {Object} tasks + * @param {number} [concurrency] + * @param {Function} [callback] + */ + function auto(tasks, concurrency, callback) { + if (typeof concurrency === func) { + callback = concurrency; + concurrency = null; + } + var keys = nativeKeys(tasks); + var rest = keys.length; + var results = {}; + if (rest === 0) { + return callback(null, results); + } + var runningTasks = 0; + var readyTasks = new DLL(); + var listeners = Object.create(null); + callback = onlyOnce(callback || noop); + concurrency = concurrency || rest; + + baseEachSync(tasks, iterator, keys); + proceedQueue(); + + function iterator(task, key) { + // no dependencies + var _task, _taskSize; + if (!isArray(task)) { + _task = task; + _taskSize = 0; + readyTasks.push([_task, _taskSize, done]); + return; + } + var dependencySize = task.length - 1; + _task = task[dependencySize]; + _taskSize = dependencySize; + if (dependencySize === 0) { + readyTasks.push([_task, _taskSize, done]); + return; + } + // dependencies + var index = -1; + while (++index < dependencySize) { + var dependencyName = task[index]; + if (notInclude(keys, dependencyName)) { + var msg = + 'async.auto task `' + + key + + '` has non-existent dependency `' + + dependencyName + + '` in ' + + task.join(', '); + throw new Error(msg); + } + var taskListeners = listeners[dependencyName]; + if (!taskListeners) { + taskListeners = listeners[dependencyName] = []; + } + taskListeners.push(taskListener); + } + + function done(err, arg) { + if (key === null) { + throwError(); + } + arg = arguments.length <= 2 ? arg : slice(arguments, 1); + if (err) { + rest = 0; + runningTasks = 0; + readyTasks.length = 0; + var safeResults = objectClone(results); + safeResults[key] = arg; + key = null; + var _callback = callback; + callback = noop; + _callback(err, safeResults); + return; + } + runningTasks--; + rest--; + results[key] = arg; + taskComplete(key); + key = null; + } + + function taskListener() { + if (--dependencySize === 0) { + readyTasks.push([_task, _taskSize, done]); + } + } + } + + function proceedQueue() { + if (readyTasks.length === 0 && runningTasks === 0) { + if (rest !== 0) { + throw new Error('async.auto task has cyclic dependencies'); + } + return callback(null, results); + } + while (readyTasks.length && runningTasks < concurrency && callback !== noop) { + runningTasks++; + var array = readyTasks.shift(); + if (array[1] === 0) { + array[0](array[2]); + } else { + array[0](results, array[2]); + } + } + } + + function taskComplete(key) { + var taskListeners = listeners[key] || []; + arrayEachSync(taskListeners, function(task) { + task(); + }); + proceedQueue(); + } + } + + var FN_ARGS = /^(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; + var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm; + + /** + * parse function arguments for `autoInject` + * + * @private + */ + function parseParams(func) { + func = func.toString().replace(STRIP_COMMENTS, ''); + func = func.match(FN_ARGS)[2].replace(' ', ''); + func = func ? func.split(FN_ARG_SPLIT) : []; + func = func.map(function(arg) { + return arg.replace(FN_ARG, '').trim(); + }); + return func; + } + + /** + * @memberof async + * @namespace autoInject + * @param {Object} tasks + * @param {number} [concurrency] + * @param {Function} [callback] + */ + function autoInject(tasks, concurrency, callback) { + var newTasks = {}; + baseEachSync(tasks, iterator, nativeKeys(tasks)); + auto(newTasks, concurrency, callback); + + function iterator(task, key) { + var params; + var taskLength = task.length; + + if (isArray(task)) { + if (taskLength === 0) { + throw new Error('autoInject task functions require explicit parameters.'); + } + params = createArray(task); + taskLength = params.length - 1; + task = params[taskLength]; + if (taskLength === 0) { + newTasks[key] = task; + return; + } + } else if (taskLength === 1) { + newTasks[key] = task; + return; + } else { + params = parseParams(task); + if (taskLength === 0 && params.length === 0) { + throw new Error('autoInject task functions require explicit parameters.'); + } + taskLength = params.length - 1; + } + params[taskLength] = newTask; + newTasks[key] = params; + + function newTask(results, done) { + switch (taskLength) { + case 1: + task(results[params[0]], done); + break; + case 2: + task(results[params[0]], results[params[1]], done); + break; + case 3: + task(results[params[0]], results[params[1]], results[params[2]], done); + break; + default: + var i = -1; + while (++i < taskLength) { + params[i] = results[params[i]]; + } + params[i] = done; + task.apply(null, params); + break; + } + } + } + } + + /** + * @memberof async + * @namespace retry + * @param {integer|Object|Function} opts + * @param {Function} [task] + * @param {Function} [callback] + */ + function retry(opts, task, callback) { + var times, intervalFunc, errorFilter; + var count = 0; + if (arguments.length < 3 && typeof opts === func) { + callback = task || noop; + task = opts; + opts = null; + times = DEFAULT_TIMES; + } else { + callback = callback || noop; + switch (typeof opts) { + case 'object': + if (typeof opts.errorFilter === func) { + errorFilter = opts.errorFilter; + } + var interval = opts.interval; + switch (typeof interval) { + case func: + intervalFunc = interval; + break; + case 'string': + case 'number': + interval = +interval; + intervalFunc = interval + ? function() { + return interval; + } + : function() { + return DEFAULT_INTERVAL; + }; + break; + } + times = +opts.times || DEFAULT_TIMES; + break; + case 'number': + times = opts || DEFAULT_TIMES; + break; + case 'string': + times = +opts || DEFAULT_TIMES; + break; + default: + throw new Error('Invalid arguments for async.retry'); + } + } + if (typeof task !== 'function') { + throw new Error('Invalid arguments for async.retry'); + } + + if (intervalFunc) { + task(intervalCallback); + } else { + task(simpleCallback); + } + + function simpleIterator() { + task(simpleCallback); + } + + function simpleCallback(err, res) { + if (++count === times || !err || (errorFilter && !errorFilter(err))) { + if (arguments.length <= 2) { + return callback(err, res); + } + var args = createArray(arguments); + return callback.apply(null, args); + } + simpleIterator(); + } + + function intervalIterator() { + task(intervalCallback); + } + + function intervalCallback(err, res) { + if (++count === times || !err || (errorFilter && !errorFilter(err))) { + if (arguments.length <= 2) { + return callback(err, res); + } + var args = createArray(arguments); + return callback.apply(null, args); + } + setTimeout(intervalIterator, intervalFunc(count)); + } + } + + function retryable(opts, task) { + if (!task) { + task = opts; + opts = null; + } + return done; + + function done() { + var taskFn; + var args = createArray(arguments); + var lastIndex = args.length - 1; + var callback = args[lastIndex]; + switch (task.length) { + case 1: + taskFn = task1; + break; + case 2: + taskFn = task2; + break; + case 3: + taskFn = task3; + break; + default: + taskFn = task4; + } + if (opts) { + retry(opts, taskFn, callback); + } else { + retry(taskFn, callback); + } + + function task1(done) { + task(done); + } + + function task2(done) { + task(args[0], done); + } + + function task3(done) { + task(args[0], args[1], done); + } + + function task4(callback) { + args[lastIndex] = callback; + task.apply(null, args); + } + } + } + + /** + * @memberof async + * @namespace iterator + */ + function iterator(tasks) { + var size = 0; + var keys = []; + if (isArray(tasks)) { + size = tasks.length; + } else { + keys = nativeKeys(tasks); + size = keys.length; + } + return makeCallback(0); + + function makeCallback(index) { + var fn = function() { + if (size) { + var key = keys[index] || index; + tasks[key].apply(null, createArray(arguments)); + } + return fn.next(); + }; + fn.next = function() { + return index < size - 1 ? makeCallback(index + 1) : null; + }; + return fn; + } + } + + /** + * @memberof async + * @namespace apply + */ + function apply(func) { + switch (arguments.length) { + case 0: + case 1: + return func; + case 2: + return func.bind(null, arguments[1]); + case 3: + return func.bind(null, arguments[1], arguments[2]); + case 4: + return func.bind(null, arguments[1], arguments[2], arguments[3]); + case 5: + return func.bind(null, arguments[1], arguments[2], arguments[3], arguments[4]); + default: + var size = arguments.length; + var index = 0; + var args = Array(size); + args[index] = null; + while (++index < size) { + args[index] = arguments[index]; + } + return func.bind.apply(func, args); + } + } + + /** + * @memberof async + * @namespace timeout + * @param {Function} func + * @param {number} millisec + * @param {*} info + */ + function timeout(func, millisec, info) { + var callback, timer; + return wrappedFunc; + + function wrappedFunc() { + timer = setTimeout(timeoutCallback, millisec); + var args = createArray(arguments); + var lastIndex = args.length - 1; + callback = args[lastIndex]; + args[lastIndex] = injectedCallback; + simpleApply(func, args); + } + + function timeoutCallback() { + var name = func.name || 'anonymous'; + var err = new Error('Callback function "' + name + '" timed out.'); + err.code = 'ETIMEDOUT'; + if (info) { + err.info = info; + } + timer = null; + callback(err); + } + + function injectedCallback() { + if (timer !== null) { + simpleApply(callback, createArray(arguments)); + clearTimeout(timer); + } + } + + function simpleApply(func, args) { + switch (args.length) { + case 0: + func(); + break; + case 1: + func(args[0]); + break; + case 2: + func(args[0], args[1]); + break; + default: + func.apply(null, args); + break; + } + } + } + + /** + * @memberof async + * @namespace times + * @param {number} n - n >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * var iterator = function(n, done) { + * done(null, n); + * }; + * async.times(4, iterator, function(err, res) { + * console.log(res); // [0, 1, 2, 3]; + * }); + * + */ + function times(n, iterator, callback) { + callback = callback || noop; + n = +n; + if (isNaN(n) || n < 1) { + return callback(null, []); + } + var result = Array(n); + timesSync(n, iterate); + + function iterate(num) { + iterator(num, createCallback(num)); + } + + function createCallback(index) { + return function(err, res) { + if (index === null) { + throwError(); + } + result[index] = res; + index = null; + if (err) { + callback(err); + callback = noop; + } else if (--n === 0) { + callback(null, result); + } + }; + } + } + + /** + * @memberof async + * @namespace timesSeries + * @param {number} n - n >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * var iterator = function(n, done) { + * done(null, n); + * }; + * async.timesSeries(4, iterator, function(err, res) { + * console.log(res); // [0, 1, 2, 3]; + * }); + * + */ + function timesSeries(n, iterator, callback) { + callback = callback || noop; + n = +n; + if (isNaN(n) || n < 1) { + return callback(null, []); + } + var result = Array(n); + var sync = false; + var completed = 0; + iterate(); + + function iterate() { + iterator(completed, done); + } + + function done(err, res) { + result[completed] = res; + if (err) { + callback(err); + callback = throwError; + } else if (++completed >= n) { + callback(null, result); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace timesLimit + * @param {number} n - n >= 1 + * @param {number} limit - n >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * var iterator = function(n, done) { + * done(null, n); + * }; + * async.timesLimit(4, 2, iterator, function(err, res) { + * console.log(res); // [0, 1, 2, 3]; + * }); + * + */ + function timesLimit(n, limit, iterator, callback) { + callback = callback || noop; + n = +n; + if (isNaN(n) || n < 1 || isNaN(limit) || limit < 1) { + return callback(null, []); + } + var result = Array(n); + var sync = false; + var started = 0; + var completed = 0; + timesSync(limit > n ? n : limit, iterate); + + function iterate() { + var index = started++; + if (index < n) { + iterator(index, createCallback(index)); + } + } + + function createCallback(index) { + return function(err, res) { + if (index === null) { + throwError(); + } + result[index] = res; + index = null; + if (err) { + callback(err); + callback = noop; + } else if (++completed >= n) { + callback(null, result); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @memberof async + * @namespace race + * @param {Array|Object} tasks - functions + * @param {Function} callback + * @example + * + * // array + * var called = 0; + * var tasks = [ + * function(done) { + * setTimeout(function() { + * called++; + * done(null, '1'); + * }, 30); + * }, + * function(done) { + * setTimeout(function() { + * called++; + * done(null, '2'); + * }, 20); + * }, + * function(done) { + * setTimeout(function() { + * called++; + * done(null, '3'); + * }, 10); + * } + * ]; + * async.race(tasks, function(err, res) { + * console.log(res); // '3' + * console.log(called); // 1 + * setTimeout(function() { + * console.log(called); // 3 + * }, 50); + * }); + * + * @example + * + * // object + * var called = 0; + * var tasks = { + * 'test1': function(done) { + * setTimeout(function() { + * called++; + * done(null, '1'); + * }, 30); + * }, + * 'test2': function(done) { + * setTimeout(function() { + * called++; + * done(null, '2'); + * }, 20); + * }, + * 'test3': function(done) { + * setTimeout(function() { + * called++; + * done(null, '3'); + * }, 10); + * } + * }; + * async.race(tasks, function(err, res) { + * console.log(res); // '3' + * console.log(called); // 1 + * setTimeout(function() { + * console.log(called); // 3 + * done(); + * }, 50); + * }); + * + */ + function race(tasks, callback) { + callback = once(callback || noop); + var size, keys; + var index = -1; + if (isArray(tasks)) { + size = tasks.length; + while (++index < size) { + tasks[index](callback); + } + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + size = keys.length; + while (++index < size) { + tasks[keys[index]](callback); + } + } else { + return callback(new TypeError('First argument to race must be a collection of functions')); + } + if (!size) { + callback(null); + } + } + + /** + * @memberof async + * @namespace memoize + */ + function memoize(fn, hasher) { + hasher = + hasher || + function(hash) { + return hash; + }; + + var memo = {}; + var queues = {}; + var memoized = function() { + var args = createArray(arguments); + var callback = args.pop(); + var key = hasher.apply(null, args); + if (has(memo, key)) { + nextTick(function() { + callback.apply(null, memo[key]); + }); + return; + } + if (has(queues, key)) { + return queues[key].push(callback); + } + + queues[key] = [callback]; + args.push(done); + fn.apply(null, args); + + function done(err) { + var args = createArray(arguments); + if (!err) { + memo[key] = args; + } + var q = queues[key]; + delete queues[key]; + + var i = -1; + var size = q.length; + while (++i < size) { + q[i].apply(null, args); + } + } + }; + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + } + + /** + * @memberof async + * @namespace unmemoize + */ + function unmemoize(fn) { + return function() { + return (fn.unmemoized || fn).apply(null, arguments); + }; + } + + /** + * @memberof async + * @namespace ensureAsync + */ + function ensureAsync(fn) { + return function(/* ...args, callback */) { + var args = createArray(arguments); + var lastIndex = args.length - 1; + var callback = args[lastIndex]; + var sync = true; + args[lastIndex] = done; + fn.apply(this, args); + sync = false; + + function done() { + var innerArgs = createArray(arguments); + if (sync) { + nextTick(function() { + callback.apply(null, innerArgs); + }); + } else { + callback.apply(null, innerArgs); + } + } + }; + } + + /** + * @memberof async + * @namespace constant + */ + function constant(/* values... */) { + var args = [null].concat(createArray(arguments)); + return function(callback) { + callback = arguments[arguments.length - 1]; + callback.apply(this, args); + }; + } + + function asyncify(fn) { + return function(/* args..., callback */) { + var args = createArray(arguments); + var callback = args.pop(); + var result; + try { + result = fn.apply(this, args); + } catch (e) { + return callback(e); + } + if (result && typeof result.then === func) { + result.then( + function(value) { + invokeCallback(callback, null, value); + }, + function(err) { + invokeCallback(callback, err && err.message ? err : new Error(err)); + } + ); + } else { + callback(null, result); + } + }; + } + + function invokeCallback(callback, err, value) { + try { + callback(err, value); + } catch (e) { + nextTick(rethrow, e); + } + } + + function rethrow(error) { + throw error; + } + + /** + * @memberof async + * @namespace reflect + * @param {Function} func + * @return {Function} + */ + function reflect(func) { + return function(/* args..., callback */) { + var callback; + switch (arguments.length) { + case 1: + callback = arguments[0]; + return func(done); + case 2: + callback = arguments[1]; + return func(arguments[0], done); + default: + var args = createArray(arguments); + var lastIndex = args.length - 1; + callback = args[lastIndex]; + args[lastIndex] = done; + func.apply(this, args); + } + + function done(err, res) { + if (err) { + return callback(null, { + error: err + }); + } + if (arguments.length > 2) { + res = slice(arguments, 1); + } + callback(null, { + value: res + }); + } + }; + } + + /** + * @memberof async + * @namespace reflectAll + * @param {Array[]|Object} tasks + * @return {Function} + */ + function reflectAll(tasks) { + var newTasks, keys; + if (isArray(tasks)) { + newTasks = Array(tasks.length); + arrayEachSync(tasks, iterate); + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + newTasks = {}; + baseEachSync(tasks, iterate, keys); + } + return newTasks; + + function iterate(func, key) { + newTasks[key] = reflect(func); + } + } + + /** + * @memberof async + * @namespace createLogger + */ + function createLogger(name) { + return function(fn) { + var args = slice(arguments, 1); + args.push(done); + fn.apply(null, args); + }; + + function done(err) { + if (typeof console === obj) { + if (err) { + if (console.error) { + console.error(err); + } + return; + } + if (console[name]) { + var args = slice(arguments, 1); + arrayEachSync(args, function(arg) { + console[name](arg); + }); + } + } + } + } + + /** + * @memberof async + * @namespace safe + */ + function safe() { + createImmediate(); + return exports; + } + + /** + * @memberof async + * @namespace fast + */ + function fast() { + createImmediate(false); + return exports; + } +}); diff --git a/node_modules/mathjs/examples/node_modules/neo-async/async.min.js b/node_modules/mathjs/examples/node_modules/neo-async/async.min.js new file mode 100644 index 0000000..4161a3f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/neo-async/async.min.js @@ -0,0 +1,80 @@ +(function(N,O){"object"===typeof exports&&"undefined"!==typeof module?O(exports):"function"===typeof define&&define.amd?define(["exports"],O):N.async?O(N.neo_async=N.neo_async||{}):O(N.async=N.async||{})})(this,function(N){function O(a){var c=function(a){var d=J(arguments,1);setTimeout(function(){a.apply(null,d)})};T="function"===typeof setImmediate?setImmediate:c;"object"===typeof process&&"function"===typeof process.nextTick?(D=/^v0.10/.test(process.version)?T:process.nextTick,ba=/^v0/.test(process.version)? +T:process.nextTick):ba=D=T;!1===a&&(D=function(a){a()})}function H(a){for(var c=-1,b=a.length,d=Array(b);++c=d)return[];for(var e=Array(d);++bd[e]){var g=d[f]; +d[f]=d[e];d[e]=g}}if(!(e>b)){for(var l,e=a[a[c]>a[e]?c:e],f=c,g=b;f<=g;){for(l=f;f=l&&a[g]>=e;)g--;if(f>g)break;var q=a;l=d;var s=f++,h=g--,k=q[s];q[s]=q[h];q[h]=k;q=l[s];l[s]=l[h];l[h]=q}e=f;ca(a,c,e-1,d);ca(a,e,b,d)}}}function S(a){var c=[];Q(a,function(a){a!==w&&(C(a)?X.apply(c,a):c.push(a))});return c}function da(a,c,b){var d=-1,e=a.length;if(3===c.length)for(;++db)return e(null,[]);y=y||Array(m);K(b>m?m:b,x)}}function Y(a,c,b){function d(){c(a[v],s)}function e(){c(a[v],v,s)}function f(){n=r.next();n.done?b(null):c(n.value,s)}function g(){n=r.next();n.done?b(null):c(n.value,v,s)}function l(){c(a[m[v]],s)}function q(){k=m[v];c(a[k],k,s)}function s(a,d){a?b(a):++v===h||!1===d?(p=A,b(null)):u?D(p): +(u=!0,p());u=!1}b=E(b||w);var h,k,m,r,n,p,u=!1,v=0;C(a)?(h=a.length,p=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,r=a[z](),p=3===c.length?g:f):"object"===typeof a&&(m=F(a),h=m.length,p=3===c.length?q:l));if(!h)return b(null);p()}function Z(a,c,b,d){function e(){xc)return d(null);K(c>k?k:c,v)}function za(a,c,b){function d(){c(a[t],s)}function e(){c(a[t],t,s)}function f(){n=r.next(); +n.done?b(null,p):c(n.value,s)}function g(){n=r.next();n.done?b(null,p):c(n.value,t,s)}function l(){c(a[m[t]],s)}function q(){k=m[t];c(a[k],k,s)}function s(a,d){a?(u=A,b=E(b),b(a,H(p))):(p[t]=d,++t===h?(u=A,b(null,p),b=A):v?D(u):(v=!0,u()),v=!1)}b=b||w;var h,k,m,r,n,p,u,v=!1,t=0;C(a)?(h=a.length,u=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,p=[],r=a[z](),u=3===c.length?g:f):"object"===typeof a&&(m=F(a),h=m.length,u=3===c.length?q:l));if(!h)return b(null,[]);p=p||Array(h);u()}function Aa(a,c,b,d){return function(e, +f,g){function l(a){var b=!1;return function(c,e){b&&A();b=!0;c?(g=I(g),g(c)):!!e===d?(g=I(g),g(null,a)):++h===q&&g(null)}}g=g||w;var q,s,h=0;C(e)?(q=e.length,a(e,f,l)):e&&(z&&e[z]?(q=b(e,f,l))&&q===h&&g(null):"object"===typeof e&&(s=F(e),q=s.length,c(e,f,l,s)));q||g(null)}}function Ba(a){return function(c,b,d){function e(){r=c[x];b(r,h)}function f(){r=c[x];b(r,x,h)}function g(){u=p.next();r=u.value;u.done?d(null):b(r,h)}function l(){u=p.next();r=u.value;u.done?d(null):b(r,x,h)}function q(){r=c[n[x]]; +b(r,h)}function s(){m=n[x];r=c[m];b(r,m,h)}function h(b,c){b?d(b):!!c===a?(v=A,d(null,r)):++x===k?(v=A,d(null)):t?D(v):(t=!0,v());t=!1}d=E(d||w);var k,m,r,n,p,u,v,t=!1,x=0;C(c)?(k=c.length,v=3===b.length?f:e):c&&(z&&c[z]?(k=Infinity,p=c[z](),v=3===b.length?l:g):"object"===typeof c&&(n=F(c),k=n.length,v=3===b.length?s:q));if(!k)return d(null);v()}}function Ca(a){return function(c,b,d,e){function f(){r=G++;rb)return e(null);K(b>m?m:b,x)}}function Da(a,c,b,d){return function(e,f,g){function l(a,b){return function(c,e){null===a&&A();c?(a=null,g=I(g),g(c,L(k))):(!!e===d&&(k[a]=b),a=null,++h===q&&g(null,k))}}g=g||w;var q,s,h=0,k={};C(e)?(q=e.length,a(e,f,l)):e&&(z&&e[z]?(q=b(e,f,l))&&q===h&&g(null,k):"object"===typeof e&&(s=F(e),q=s.length,c(e,f,l,s)));if(!q)return g(null,{})}}function Ea(a){return function(c, +b,d){function e(){m=y;r=c[y];b(r,h)}function f(){m=y;r=c[y];b(r,y,h)}function g(){m=y;u=p.next();r=u.value;u.done?d(null,x):b(r,h)}function l(){m=y;u=p.next();r=u.value;u.done?d(null,x):b(r,m,h)}function q(){m=n[y];r=c[m];b(r,h)}function s(){m=n[y];r=c[m];b(r,m,h)}function h(b,c){b?d(b,x):(!!c===a&&(x[m]=r),++y===k?(v=A,d(null,x)):t?D(v):(t=!0,v()),t=!1)}d=E(d||w);var k,m,r,n,p,u,v,t=!1,x={},y=0;C(c)?(k=c.length,v=3===b.length?f:e):c&&(z&&c[z]?(k=Infinity,p=c[z](),v=3===b.length?l:g):"object"===typeof c&& +(n=F(c),k=n.length,v=3===b.length?s:q));if(!k)return d(null,{});v()}}function Fa(a){return function(c,b,d,e){function f(){r=B++;rb)return e(null,{});K(b>m?m:b,x)}}function $(a,c,b,d){function e(d){b(d,a[t],h)}function f(d){b(d,a[t],t,h)}function g(a){p=n.next();p.done?d(null,a):b(a,p.value, +h)}function l(a){p=n.next();p.done?d(null,a):b(a,p.value,t,h)}function q(d){b(d,a[r[t]],h)}function s(d){m=r[t];b(d,a[m],m,h)}function h(a,c){a?d(a,c):++t===k?(b=A,d(null,c)):v?D(function(){u(c)}):(v=!0,u(c));v=!1}d=E(d||w);var k,m,r,n,p,u,v=!1,t=0;C(a)?(k=a.length,u=4===b.length?f:e):a&&(z&&a[z]?(k=Infinity,n=a[z](),u=4===b.length?l:g):"object"===typeof a&&(r=F(a),k=r.length,u=4===b.length?s:q));if(!k)return d(null,c);u(c)}function Ga(a,c,b,d){function e(d){b(d,a[--s],q)}function f(d){b(d,a[--s], +s,q)}function g(d){b(d,a[m[--s]],q)}function l(d){k=m[--s];b(d,a[k],k,q)}function q(a,b){a?d(a,b):0===s?(u=A,d(null,b)):v?D(function(){u(b)}):(v=!0,u(b));v=!1}d=E(d||w);var s,h,k,m,r,n,p,u,v=!1;if(C(a))s=a.length,u=4===b.length?f:e;else if(a)if(z&&a[z]){p=[];r=a[z]();for(h=-1;!1===(n=r.next()).done;)p[++h]=n.value;a=p;s=p.length;u=4===b.length?f:e}else"object"===typeof a&&(m=F(a),s=m.length,u=4===b.length?l:g);if(!s)return d(null,c);u(c)}function Ha(a,c,b){b=b||w;ja(a,c,function(a,c){if(a)return b(a); +b(null,!!c)})}function Ia(a,c,b){b=b||w;ka(a,c,function(a,c){if(a)return b(a);b(null,!!c)})}function Ja(a,c,b,d){d=d||w;la(a,c,b,function(a,b){if(a)return d(a);d(null,!!b)})}function Ka(a,c){return C(a)?0===a.length?(c(null),!1):!0:(c(Error("First argument to waterfall must be an array of functions")),!1)}function ma(a,c,b){switch(c.length){case 0:case 1:return a(b);case 2:return a(c[1],b);case 3:return a(c[1],c[2],b);case 4:return a(c[1],c[2],c[3],b);case 5:return a(c[1],c[2],c[3],c[4],b);case 6:return a(c[1], +c[2],c[3],c[4],c[5],b);default:return c=J(c,1),c.push(b),a.apply(null,c)}}function La(a,c){function b(b,h){if(b)q=A,c=E(c),c(b);else if(++d===f){q=A;var k=c;c=A;2===arguments.length?k(b,h):k.apply(null,H(arguments))}else g=a[d],l=arguments,e?D(q):(e=!0,q()),e=!1}c=c||w;if(Ka(a,c)){var d=0,e=!1,f=a.length,g=a[d],l=[],q=function(){switch(g.length){case 0:try{b(null,g())}catch(a){b(a)}break;case 1:return g(b);case 2:return g(l[1],b);case 3:return g(l[1],l[2],b);case 4:return g(l[1],l[2],l[3],b);case 5:return g(l[1], +l[2],l[3],l[4],b);default:return l=J(l,1),l[g.length-1]=b,g.apply(null,l)}};q()}}function Ma(){var a=H(arguments);return function(){var c=this,b=H(arguments),d=b[b.length-1];"function"===typeof d?b.pop():d=w;$(a,b,function(a,b,d){a.push(function(a){var b=J(arguments,1);d(a,b)});b.apply(c,a)},function(a,b){b=C(b)?b:[b];b.unshift(a);d.apply(c,b)})}}function Na(a){return function(c){var b=function(){var b=this,d=H(arguments),g=d.pop()||w;return a(c,function(a,c){a.apply(b,d.concat([c]))},g)};if(1b)throw Error("Concurrency must not be zero");var h=0,k=[],m,r,n={_tasks:new M,concurrency:b,payload:d,saturated:w,unsaturated:w,buffer:b/4,empty:w,drain:w,error:w,started:!1,paused:!1,push:function(a, +b){f(a,b)},kill:function(){n.drain=w;n._tasks.empty()},unshift:function(a,b){f(a,b,!0)},remove:function(a){n._tasks.remove(a)},process:a?l:q,length:function(){return n._tasks.length},running:function(){return h},workersList:function(){return k},idle:function(){return 0===n.length()+h},pause:function(){n.paused=!0},resume:function(){!1!==n.paused&&(n.paused=!1,K(n.concurrency=arguments.length?f:J(arguments,1);if(a){q=g=0;s.length=0;var k=L(l);k[d]=f;d=null;var h= +b;b=w;h(a,k)}else q--,g--,l[d]=f,e(d),d=null}function n(){0===--v&&s.push([p,u,c])}var p,u;if(C(a)){var v=a.length-1;p=a[v];u=v;if(0===v)s.push([p,u,c]);else for(var t=-1;++t=arguments.length)return b(a,e);var f=H(arguments);return b.apply(null,f)}c(d)}function e(){c(f)}function f(a,d){if(++s===g||!a||q&&!q(a)){if(2>=arguments.length)return b(a,d);var c=H(arguments);return b.apply(null,c)}setTimeout(e,l(s))}var g,l,q,s=0;if(3>arguments.length&&"function"===typeof a)b=c||w,c=a,a=null,g=5;else switch(b=b||w,typeof a){case "object":"function"===typeof a.errorFilter&&(q=a.errorFilter);var h=a.interval; +switch(typeof h){case "function":l=h;break;case "string":case "number":l=(h=+h)?function(){return h}:function(){return 0}}g=+a.times||5;break;case "number":g=a||5;break;case "string":g=+a||5;break;default:throw Error("Invalid arguments for async.retry");}if("function"!==typeof c)throw Error("Invalid arguments for async.retry");l?c(f):c(d)}function Pa(a){return function(){var c=H(arguments),b=c.pop(),d;try{d=a.apply(this,c)}catch(e){return b(e)}d&&"function"===typeof d.then?d.then(function(a){try{b(null, +a)}catch(d){D(Qa,d)}},function(a){a=a&&a.message?a:Error(a);try{b(a,void 0)}catch(d){D(Qa,d)}}):b(null,d)}}function Qa(a){throw a;}function Ra(a){return function(){function c(a,d){if(a)return b(null,{error:a});2=arguments.length?c:J(arguments,1),a=null,++q===f&&d(null,l))}}d=d||w;var f,g,l,q=0;C(b)?(f=b.length,l=Array(f),a(b,e)):b&&"object"===typeof b&&(g=F(b),f=g.length,l={},c(b,e,g));f||d(null,l)}}(function(a,c){for(var b=-1,d=a.length;++bc)return d(null,[]);v=v||Array(k);K(c>k?k:c,t)},mapValues:fb,mapValuesSeries:function(a,c,b){function d(){k=t;c(a[t], +s)}function e(){k=t;c(a[t],t,s)}function f(){k=t;n=r.next();n.done?b(null,v):c(n.value,s)}function g(){k=t;n=r.next();n.done?b(null,v):c(n.value,t,s)}function l(){k=m[t];c(a[k],s)}function q(){k=m[t];c(a[k],k,s)}function s(a,d){a?(p=A,b=E(b),b(a,L(v))):(v[k]=d,++t===h?(p=A,b(null,v),b=A):u?D(p):(u=!0,p()),u=!1)}b=b||w;var h,k,m,r,n,p,u=!1,v={},t=0;C(a)?(h=a.length,p=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,r=a[z](),p=3===c.length?g:f):"object"===typeof a&&(m=F(a),h=m.length,p=3===c.length?q:l)); +if(!h)return b(null,v);p()},mapValuesLimit:function(a,c,b,d){function e(){m=y++;mc)return d(null,x);K(c>k?k:c,v)},filter:Ta,filterSeries:Ua,filterLimit:Va,select:Ta,selectSeries:Ua,selectLimit:Va,reject:gb,rejectSeries:hb,rejectLimit:ib,detect:ja,detectSeries:ka,detectLimit:la,find:ja,findSeries:ka,findLimit:la,pick:jb,pickSeries:kb, +pickLimit:lb,omit:mb,omitSeries:nb,omitLimit:ob,reduce:$,inject:$,foldl:$,reduceRight:Ga,foldr:Ga,transform:pb,transformSeries:function(a,c,b,d){function e(){b(v,a[x],h)}function f(){b(v,a[x],x,h)}function g(){p=n.next();p.done?d(null,v):b(v,p.value,h)}function l(){p=n.next();p.done?d(null,v):b(v,p.value,x,h)}function q(){b(v,a[r[x]],h)}function s(){m=r[x];b(v,a[m],m,h)}function h(a,b){a?d(a,v):++x===k||!1===b?(u=A,d(null,v)):t?D(u):(t=!0,u());t=!1}3===arguments.length&&(d=b,b=c,c=void 0);d=E(d|| +w);var k,m,r,n,p,u,v,t=!1,x=0;C(a)?(k=a.length,v=void 0!==c?c:[],u=4===b.length?f:e):a&&(z&&a[z]?(k=Infinity,n=a[z](),v=void 0!==c?c:{},u=4===b.length?l:g):"object"===typeof a&&(r=F(a),k=r.length,v=void 0!==c?c:{},u=4===b.length?s:q));if(!k)return d(null,void 0!==c?c:v||{});u()},transformLimit:function(a,c,b,d,e){function f(){r=A++;rc)return e(null,void 0!==b?b:x||{});K(c>m?m:c,t)},sortBy:qb,sortBySeries:function(a,c,b){function d(){m=a[y];c(m,s)}function e(){m=a[y];c(m,y,s)}function f(){p=n.next();if(p.done)return b(null,P(u,v));m=p.value;u[y]=m;c(m,s)}function g(){p=n.next();if(p.done)return b(null,P(u,v));m=p.value;u[y]=m;c(m,y,s)}function l(){m=a[r[y]];u[y]=m;c(m,s)}function q(){k=r[y];m=a[k];u[y]=m;c(m,k,s)}function s(a,d){v[y]=d;a?b(a):++y===h?(t=A,b(null, +P(u,v))):x?D(t):(x=!0,t());x=!1}b=E(b||w);var h,k,m,r,n,p,u,v,t,x=!1,y=0;C(a)?(h=a.length,u=a,v=Array(h),t=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,u=[],v=[],n=a[z](),t=3===c.length?g:f):"object"===typeof a&&(r=F(a),h=r.length,u=Array(h),v=Array(h),t=3===c.length?q:l));if(!h)return b(null,[]);t()},sortByLimit:function(a,c,b,d){function e(){Bc)return d(null,[]);x=x||Array(k);K(c>k?k:c,y)},some:Ha,someSeries:Ia,someLimit:Ja,any:Ha,anySeries:Ia,anyLimit:Ja,every:Wa,everySeries:Xa,everyLimit:Ya,all:Wa,allSeries:Xa,allLimit:Ya,concat:rb,concatSeries:function(a,c,b){function d(){c(a[t],s)}function e(){c(a[t],t,s)}function f(){n=r.next();n.done?b(null,v):c(n.value,s)}function g(){n=r.next();n.done?b(null,v):c(n.value,t,s)}function l(){c(a[m[t]], +s)}function q(){k=m[t];c(a[k],k,s)}function s(a,d){C(d)?X.apply(v,d):2<=arguments.length&&X.apply(v,J(arguments,1));a?b(a,v):++t===h?(p=A,b(null,v)):u?D(p):(u=!0,p());u=!1}b=E(b||w);var h,k,m,r,n,p,u=!1,v=[],t=0;C(a)?(h=a.length,p=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,r=a[z](),p=3===c.length?g:f):"object"===typeof a&&(m=F(a),h=m.length,p=3===c.length?q:l));if(!h)return b(null,v);p()},concatLimit:function(a,c,b,d){function e(){tc)return d(null,[]);u=u||Array(k);K(c>k?k:c,p)},groupBy:sb,groupBySeries:function(a,c,b){function d(){m=a[t];c(m,s)}function e(){m=a[t];c(m,t,s)}function f(){p=n.next();m=p.value;p.done?b(null,x):c(m,s)}function g(){p=n.next();m=p.value;p.done? +b(null,x):c(m,t,s)}function l(){m=a[r[t]];c(m,s)}function q(){k=r[t];m=a[k];c(m,k,s)}function s(a,d){if(a)u=A,b=E(b),b(a,L(x));else{var c=x[d];c?c.push(m):x[d]=[m];++t===h?(u=A,b(null,x)):v?D(u):(v=!0,u());v=!1}}b=E(b||w);var h,k,m,r,n,p,u,v=!1,t=0,x={};C(a)?(h=a.length,u=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,n=a[z](),u=3===c.length?g:f):"object"===typeof a&&(r=F(a),h=r.length,u=3===c.length?q:l));if(!h)return b(null,x);u()},groupByLimit:function(a,c,b,d){function e(){yc)return d(null,B);K(c>k?k:c,t)},parallel:tb,series:function(a,c){function b(){g=k;a[k](e)}function d(){g=l[k];a[g](e)}function e(a,b){a?(s=A,c=E(c),c(a,q)):(q[g]=2>=arguments.length?b:J(arguments,1),++k===f?(s=A,c(null,q)):h?D(s):(h=!0,s()),h=!1)}c=c||w;var f,g,l,q,s,h=!1,k=0;if(C(a))f=a.length,q=Array(f), +s=b;else if(a&&"object"===typeof a)l=F(a),f=l.length,q={},s=d;else return c(null);if(!f)return c(null,q);s()},parallelLimit:function(a,c,b){function d(){l=r++;if(l=arguments.length?c:J(arguments,1),a=null,++n===g?b(null,h):m?D(k):(m=!0,k()),m=!1)}}b=b||w;var g,l,q,s,h,k,m=!1,r=0,n=0;C(a)?(g=a.length,h=Array(g),k=d):a&&"object"===typeof a&&(s=F(a),g=s.length,h= +{},k=e);if(!g||isNaN(c)||1>c)return b(null,h);K(c>g?g:c,k)},tryEach:function(a,c){function b(){a[q](e)}function d(){a[g[q]](e)}function e(a,b){a?++q===f?c(a):l():2>=arguments.length?c(null,b):c(null,J(arguments,1))}c=c||w;var f,g,l,q=0;C(a)?(f=a.length,l=b):a&&"object"===typeof a&&(g=F(a),f=g.length,l=d);if(!f)return c(null);l()},waterfall:function(a,c){function b(){ma(e,f,d(e))}function d(h){return function(k,m){void 0===h&&(c=w,A());h=void 0;k?(g=c,c=A,g(k)):++q===s?(g=c,c=A,2>=arguments.length? +g(k,m):g.apply(null,H(arguments))):(l?(f=arguments,e=a[q]||A,D(b)):(l=!0,ma(a[q]||A,arguments,d(q))),l=!1)}}c=c||w;if(Ka(a,c)){var e,f,g,l,q=0,s=a.length;ma(a[0],[],d(0))}},angelFall:La,angelfall:La,whilst:function(a,c,b){function d(){g?D(e):(g=!0,c(f));g=!1}function e(){c(f)}function f(c,e){if(c)return b(c);2>=arguments.length?a(e)?d():b(null,e):(e=J(arguments,1),a.apply(null,e)?d():b.apply(null,[null].concat(e)))}b=b||w;var g=!1;a()?d():b(null)},doWhilst:function(a,c,b){function d(){g?D(e):(g=!0, +a(f));g=!1}function e(){a(f)}function f(a,e){if(a)return b(a);2>=arguments.length?c(e)?d():b(null,e):(e=J(arguments,1),c.apply(null,e)?d():b.apply(null,[null].concat(e)))}b=b||w;var g=!1;e()},until:function(a,c,b){function d(){g?D(e):(g=!0,c(f));g=!1}function e(){c(f)}function f(c,e){if(c)return b(c);2>=arguments.length?a(e)?b(null,e):d():(e=J(arguments,1),a.apply(null,e)?b.apply(null,[null].concat(e)):d())}b=b||w;var g=!1;a()?b(null):d()},doUntil:function(a,c,b){function d(){g?D(e):(g=!0,a(f));g= +!1}function e(){a(f)}function f(a,e){if(a)return b(a);2>=arguments.length?c(e)?b(null,e):d():(e=J(arguments,1),c.apply(null,e)?b.apply(null,[null].concat(e)):d())}b=b||w;var g=!1;e()},during:function(a,c,b){function d(a,d){if(a)return b(a);d?c(e):b(null)}function e(c){if(c)return b(c);a(d)}b=b||w;a(d)},doDuring:function(a,c,b){function d(d,c){if(d)return b(d);c?a(e):b(null)}function e(a,e){if(a)return b(a);switch(arguments.length){case 0:case 1:c(d);break;case 2:c(e,d);break;default:var l=J(arguments, +1);l.push(d);c.apply(null,l)}}b=b||w;d(null,!0)},forever:function(a,c){function b(){a(d)}function d(a){if(a){if(c)return c(a);throw a;}e?D(b):(e=!0,b());e=!1}var e=!1;b()},compose:function(){return Ma.apply(null,Za(arguments))},seq:Ma,applyEach:ub,applyEachSeries:vb,queue:function(a,c){return na(!0,a,c)},priorityQueue:function(a,c){var b=na(!0,a,c);b.push=function(a,c,f){b.started=!0;c=c||0;var g=C(a)?a:[a],l=g.length;if(void 0===a||0===l)b.idle()&&D(b.drain);else{f="function"===typeof f?f:w;for(a= +b._tasks.head;a&&c>=a.priority;)a=a.next;for(;l--;){var q={data:g[l],priority:c,callback:f};a?b._tasks.insertBefore(a,q):b._tasks.push(q);D(b.process)}}};delete b.unshift;return b},cargo:function(a,c){return na(!1,a,1,c)},auto:Oa,autoInject:function(a,c,b){var d={};W(a,function(a,b){var c,l=a.length;if(C(a)){if(0===l)throw Error("autoInject task functions require explicit parameters.");c=H(a);l=c.length-1;a=c[l];if(0===l){d[b]=a;return}}else{if(1===l){d[b]=a;return}c=ab(a);if(0===l&&0===c.length)throw Error("autoInject task functions require explicit parameters."); +l=c.length-1}c[l]=function(b,d){switch(l){case 1:a(b[c[0]],d);break;case 2:a(b[c[0]],b[c[1]],d);break;case 3:a(b[c[0]],b[c[1]],b[c[2]],d);break;default:for(var f=-1;++fa)return b(null,[]);var e=Array(a);K(a,function(a){c(a,d(a))})},timesSeries:function(a,c,b){function d(){c(l, +e)}function e(c,e){f[l]=e;c?(b(c),b=A):++l>=a?(b(null,f),b=A):g?D(d):(g=!0,d());g=!1}b=b||w;a=+a;if(isNaN(a)||1>a)return b(null,[]);var f=Array(a),g=!1,l=0;d()},timesLimit:function(a,c,b,d){function e(){var c=q++;c=a?(d(null,g),d=A):l?D(e):(l=!0,e());l=!1}}d=d||w;a=+a;if(isNaN(a)||1>a||isNaN(c)||1>c)return d(null,[]);var g=Array(a),l=!1,q=0,s=0;K(c>a?a:c,e)},race:function(a,c){c=I(c||w);var b,d,e=-1;if(C(a))for(b= +a.length;++e", + "license": "MIT", + "devDependencies": { + "semver": "^7.3.5" + } +} diff --git a/node_modules/mathjs/examples/node_modules/npm-run-path/index.d.ts b/node_modules/mathjs/examples/node_modules/npm-run-path/index.d.ts new file mode 100644 index 0000000..af10d41 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/npm-run-path/index.d.ts @@ -0,0 +1,89 @@ +declare namespace npmRunPath { + interface RunPathOptions { + /** + Working directory. + + @default process.cwd() + */ + readonly cwd?: string; + + /** + PATH to be appended. Default: [`PATH`](https://github.com/sindresorhus/path-key). + + Set it to an empty string to exclude the default PATH. + */ + readonly path?: string; + + /** + Path to the Node.js executable to use in child processes if that is different from the current one. Its directory is pushed to the front of PATH. + + This can be either an absolute path or a path relative to the `cwd` option. + + @default process.execPath + */ + readonly execPath?: string; + } + + interface ProcessEnv { + [key: string]: string | undefined; + } + + interface EnvOptions { + /** + Working directory. + + @default process.cwd() + */ + readonly cwd?: string; + + /** + Accepts an object of environment variables, like `process.env`, and modifies the PATH using the correct [PATH key](https://github.com/sindresorhus/path-key). Use this if you're modifying the PATH for use in the `child_process` options. + */ + readonly env?: ProcessEnv; + + /** + Path to the current Node.js executable. Its directory is pushed to the front of PATH. + + This can be either an absolute path or a path relative to the `cwd` option. + + @default process.execPath + */ + readonly execPath?: string; + } +} + +declare const npmRunPath: { + /** + Get your [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) prepended with locally installed binaries. + + @returns The augmented path string. + + @example + ``` + import * as childProcess from 'child_process'; + import npmRunPath = require('npm-run-path'); + + console.log(process.env.PATH); + //=> '/usr/local/bin' + + console.log(npmRunPath()); + //=> '/Users/sindresorhus/dev/foo/node_modules/.bin:/Users/sindresorhus/dev/node_modules/.bin:/Users/sindresorhus/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/usr/local/bin' + + // `foo` is a locally installed binary + childProcess.execFileSync('foo', { + env: npmRunPath.env() + }); + ``` + */ + (options?: npmRunPath.RunPathOptions): string; + + /** + @returns The augmented [`process.env`](https://nodejs.org/api/process.html#process_process_env) object. + */ + env(options?: npmRunPath.EnvOptions): npmRunPath.ProcessEnv; + + // TODO: Remove this for the next major release + default: typeof npmRunPath; +}; + +export = npmRunPath; diff --git a/node_modules/mathjs/examples/node_modules/npm-run-path/index.js b/node_modules/mathjs/examples/node_modules/npm-run-path/index.js new file mode 100644 index 0000000..8c94abc --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/npm-run-path/index.js @@ -0,0 +1,47 @@ +'use strict'; +const path = require('path'); +const pathKey = require('path-key'); + +const npmRunPath = options => { + options = { + cwd: process.cwd(), + path: process.env[pathKey()], + execPath: process.execPath, + ...options + }; + + let previous; + let cwdPath = path.resolve(options.cwd); + const result = []; + + while (previous !== cwdPath) { + result.push(path.join(cwdPath, 'node_modules/.bin')); + previous = cwdPath; + cwdPath = path.resolve(cwdPath, '..'); + } + + // Ensure the running `node` binary is used + const execPathDir = path.resolve(options.cwd, options.execPath, '..'); + result.push(execPathDir); + + return result.concat(options.path).join(path.delimiter); +}; + +module.exports = npmRunPath; +// TODO: Remove this for the next major release +module.exports.default = npmRunPath; + +module.exports.env = options => { + options = { + env: process.env, + ...options + }; + + const env = {...options.env}; + const path = pathKey({env}); + + options.path = env[path]; + env[path] = module.exports(options); + + return env; +}; diff --git a/node_modules/mathjs/examples/node_modules/npm-run-path/license b/node_modules/mathjs/examples/node_modules/npm-run-path/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/npm-run-path/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/npm-run-path/package.json b/node_modules/mathjs/examples/node_modules/npm-run-path/package.json new file mode 100644 index 0000000..feb8c00 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/npm-run-path/package.json @@ -0,0 +1,44 @@ +{ + "name": "npm-run-path", + "version": "4.0.1", + "description": "Get your PATH prepended with locally installed binaries", + "license": "MIT", + "repository": "sindresorhus/npm-run-path", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "npm", + "run", + "path", + "package", + "bin", + "binary", + "binaries", + "script", + "cli", + "command-line", + "execute", + "executable" + ], + "dependencies": { + "path-key": "^3.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/npm-run-path/readme.md b/node_modules/mathjs/examples/node_modules/npm-run-path/readme.md new file mode 100644 index 0000000..557fbeb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/npm-run-path/readme.md @@ -0,0 +1,115 @@ +# npm-run-path [![Build Status](https://travis-ci.org/sindresorhus/npm-run-path.svg?branch=master)](https://travis-ci.org/sindresorhus/npm-run-path) + +> Get your [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) prepended with locally installed binaries + +In [npm run scripts](https://docs.npmjs.com/cli/run-script) you can execute locally installed binaries by name. This enables the same outside npm. + + +## Install + +``` +$ npm install npm-run-path +``` + + +## Usage + +```js +const childProcess = require('child_process'); +const npmRunPath = require('npm-run-path'); + +console.log(process.env.PATH); +//=> '/usr/local/bin' + +console.log(npmRunPath()); +//=> '/Users/sindresorhus/dev/foo/node_modules/.bin:/Users/sindresorhus/dev/node_modules/.bin:/Users/sindresorhus/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/usr/local/bin' + +// `foo` is a locally installed binary +childProcess.execFileSync('foo', { + env: npmRunPath.env() +}); +``` + + +## API + +### npmRunPath(options?) + +Returns the augmented path string. + +#### options + +Type: `object` + +##### cwd + +Type: `string`
    +Default: `process.cwd()` + +Working directory. + +##### path + +Type: `string`
    +Default: [`PATH`](https://github.com/sindresorhus/path-key) + +PATH to be appended.
    +Set it to an empty string to exclude the default PATH. + +##### execPath + +Type: `string`
    +Default: `process.execPath` + +Path to the current Node.js executable. Its directory is pushed to the front of PATH. + +This can be either an absolute path or a path relative to the [`cwd` option](#cwd). + +### npmRunPath.env(options?) + +Returns the augmented [`process.env`](https://nodejs.org/api/process.html#process_process_env) object. + +#### options + +Type: `object` + +##### cwd + +Type: `string`
    +Default: `process.cwd()` + +Working directory. + +##### env + +Type: `Object` + +Accepts an object of environment variables, like `process.env`, and modifies the PATH using the correct [PATH key](https://github.com/sindresorhus/path-key). Use this if you're modifying the PATH for use in the `child_process` options. + +##### execPath + +Type: `string`
    +Default: `process.execPath` + +Path to the Node.js executable to use in child processes if that is different from the current one. Its directory is pushed to the front of PATH. + +This can be either an absolute path or a path relative to the [`cwd` option](#cwd). + + +## Related + +- [npm-run-path-cli](https://github.com/sindresorhus/npm-run-path-cli) - CLI for this module +- [execa](https://github.com/sindresorhus/execa) - Execute a locally installed binary + + +--- + +
    + + Get professional support for this package with a Tidelift subscription + +
    + + Tidelift helps make open source sustainable for maintainers while giving companies
    assurances about security, maintenance, and licensing for their dependencies. +
    +
    diff --git a/node_modules/mathjs/examples/node_modules/onetime/index.d.ts b/node_modules/mathjs/examples/node_modules/onetime/index.d.ts new file mode 100644 index 0000000..ea84cab --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/onetime/index.d.ts @@ -0,0 +1,64 @@ +declare namespace onetime { + interface Options { + /** + Throw an error when called more than once. + + @default false + */ + throw?: boolean; + } +} + +declare const onetime: { + /** + Ensure a function is only called once. When called multiple times it will return the return value from the first call. + + @param fn - Function that should only be called once. + @returns A function that only calls `fn` once. + + @example + ``` + import onetime = require('onetime'); + + let i = 0; + + const foo = onetime(() => ++i); + + foo(); //=> 1 + foo(); //=> 1 + foo(); //=> 1 + + onetime.callCount(foo); //=> 3 + ``` + */ + ( + fn: (...arguments: ArgumentsType) => ReturnType, + options?: onetime.Options + ): (...arguments: ArgumentsType) => ReturnType; + + /** + Get the number of times `fn` has been called. + + @param fn - Function to get call count from. + @returns A number representing how many times `fn` has been called. + + @example + ``` + import onetime = require('onetime'); + + const foo = onetime(() => {}); + foo(); + foo(); + foo(); + + console.log(onetime.callCount(foo)); + //=> 3 + ``` + */ + callCount(fn: (...arguments: any[]) => unknown): number; + + // TODO: Remove this for the next major release + default: typeof onetime; +}; + +export = onetime; diff --git a/node_modules/mathjs/examples/node_modules/onetime/index.js b/node_modules/mathjs/examples/node_modules/onetime/index.js new file mode 100644 index 0000000..99c5fc1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/onetime/index.js @@ -0,0 +1,44 @@ +'use strict'; +const mimicFn = require('mimic-fn'); + +const calledFunctions = new WeakMap(); + +const onetime = (function_, options = {}) => { + if (typeof function_ !== 'function') { + throw new TypeError('Expected a function'); + } + + let returnValue; + let callCount = 0; + const functionName = function_.displayName || function_.name || ''; + + const onetime = function (...arguments_) { + calledFunctions.set(onetime, ++callCount); + + if (callCount === 1) { + returnValue = function_.apply(this, arguments_); + function_ = null; + } else if (options.throw === true) { + throw new Error(`Function \`${functionName}\` can only be called once`); + } + + return returnValue; + }; + + mimicFn(onetime, function_); + calledFunctions.set(onetime, callCount); + + return onetime; +}; + +module.exports = onetime; +// TODO: Remove this for the next major release +module.exports.default = onetime; + +module.exports.callCount = function_ => { + if (!calledFunctions.has(function_)) { + throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); + } + + return calledFunctions.get(function_); +}; diff --git a/node_modules/mathjs/examples/node_modules/onetime/license b/node_modules/mathjs/examples/node_modules/onetime/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/onetime/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/onetime/package.json b/node_modules/mathjs/examples/node_modules/onetime/package.json new file mode 100644 index 0000000..54caea5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/onetime/package.json @@ -0,0 +1,43 @@ +{ + "name": "onetime", + "version": "5.1.2", + "description": "Ensure a function is only called once", + "license": "MIT", + "repository": "sindresorhus/onetime", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "once", + "function", + "one", + "onetime", + "func", + "fn", + "single", + "call", + "called", + "prevent" + ], + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/onetime/readme.md b/node_modules/mathjs/examples/node_modules/onetime/readme.md new file mode 100644 index 0000000..2d133d3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/onetime/readme.md @@ -0,0 +1,94 @@ +# onetime [![Build Status](https://travis-ci.com/sindresorhus/onetime.svg?branch=master)](https://travis-ci.com/github/sindresorhus/onetime) + +> Ensure a function is only called once + +When called multiple times it will return the return value from the first call. + +*Unlike the module [once](https://github.com/isaacs/once), this one isn't naughty and extending `Function.prototype`.* + +## Install + +``` +$ npm install onetime +``` + +## Usage + +```js +const onetime = require('onetime'); + +let i = 0; + +const foo = onetime(() => ++i); + +foo(); //=> 1 +foo(); //=> 1 +foo(); //=> 1 + +onetime.callCount(foo); //=> 3 +``` + +```js +const onetime = require('onetime'); + +const foo = onetime(() => {}, {throw: true}); + +foo(); + +foo(); +//=> Error: Function `foo` can only be called once +``` + +## API + +### onetime(fn, options?) + +Returns a function that only calls `fn` once. + +#### fn + +Type: `Function` + +Function that should only be called once. + +#### options + +Type: `object` + +##### throw + +Type: `boolean`\ +Default: `false` + +Throw an error when called more than once. + +### onetime.callCount(fn) + +Returns a number representing how many times `fn` has been called. + +Note: It throws an error if you pass in a function that is not wrapped by `onetime`. + +```js +const onetime = require('onetime'); + +const foo = onetime(() => {}); + +foo(); +foo(); +foo(); + +console.log(onetime.callCount(foo)); +//=> 3 +``` + +#### fn + +Type: `Function` + +Function to get call count from. + +## onetime for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of onetime and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-onetime?utm_source=npm-onetime&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/mathjs/examples/node_modules/p-limit/index.d.ts b/node_modules/mathjs/examples/node_modules/p-limit/index.d.ts new file mode 100644 index 0000000..6bbfad4 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-limit/index.d.ts @@ -0,0 +1,38 @@ +export interface Limit { + /** + @param fn - Promise-returning/async function. + @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. + @returns The promise returned by calling `fn(...arguments)`. + */ + ( + fn: (...arguments: Arguments) => PromiseLike | ReturnType, + ...arguments: Arguments + ): Promise; + + /** + The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + + /** + Discard pending promises that are waiting to run. + + This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + + Note: This does not cancel promises that are already running. + */ + clearQueue(): void; +} + +/** +Run multiple promise-returning & async functions with limited concurrency. + +@param concurrency - Concurrency limit. Minimum: `1`. +@returns A `limit` function. +*/ +export default function pLimit(concurrency: number): Limit; diff --git a/node_modules/mathjs/examples/node_modules/p-limit/index.js b/node_modules/mathjs/examples/node_modules/p-limit/index.js new file mode 100644 index 0000000..6a72a4c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-limit/index.js @@ -0,0 +1,57 @@ +'use strict'; +const pTry = require('p-try'); + +const pLimit = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up')); + } + + const queue = []; + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.length > 0) { + queue.shift()(); + } + }; + + const run = (fn, resolve, ...args) => { + activeCount++; + + const result = pTry(fn, ...args); + + resolve(result); + + result.then(next, next); + }; + + const enqueue = (fn, resolve, ...args) => { + if (activeCount < concurrency) { + run(fn, resolve, ...args); + } else { + queue.push(run.bind(null, fn, resolve, ...args)); + } + }; + + const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args)); + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.length + }, + clearQueue: { + value: () => { + queue.length = 0; + } + } + }); + + return generator; +}; + +module.exports = pLimit; +module.exports.default = pLimit; diff --git a/node_modules/mathjs/examples/node_modules/p-limit/license b/node_modules/mathjs/examples/node_modules/p-limit/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-limit/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/p-limit/package.json b/node_modules/mathjs/examples/node_modules/p-limit/package.json new file mode 100644 index 0000000..99a814f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-limit/package.json @@ -0,0 +1,52 @@ +{ + "name": "p-limit", + "version": "2.3.0", + "description": "Run multiple promise-returning & async functions with limited concurrency", + "license": "MIT", + "repository": "sindresorhus/p-limit", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd-check" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "limit", + "limited", + "concurrency", + "throttle", + "throat", + "rate", + "batch", + "ratelimit", + "task", + "queue", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "p-try": "^2.0.0" + }, + "devDependencies": { + "ava": "^1.2.1", + "delay": "^4.1.0", + "in-range": "^1.0.0", + "random-int": "^1.0.0", + "time-span": "^2.0.0", + "tsd-check": "^0.3.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/p-limit/readme.md b/node_modules/mathjs/examples/node_modules/p-limit/readme.md new file mode 100644 index 0000000..64aa476 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-limit/readme.md @@ -0,0 +1,101 @@ +# p-limit [![Build Status](https://travis-ci.org/sindresorhus/p-limit.svg?branch=master)](https://travis-ci.org/sindresorhus/p-limit) + +> Run multiple promise-returning & async functions with limited concurrency + +## Install + +``` +$ npm install p-limit +``` + +## Usage + +```js +const pLimit = require('p-limit'); + +const limit = pLimit(1); + +const input = [ + limit(() => fetchSomething('foo')), + limit(() => fetchSomething('bar')), + limit(() => doSomething()) +]; + +(async () => { + // Only one promise is run at once + const result = await Promise.all(input); + console.log(result); +})(); +``` + +## API + +### pLimit(concurrency) + +Returns a `limit` function. + +#### concurrency + +Type: `number`\ +Minimum: `1`\ +Default: `Infinity` + +Concurrency limit. + +### limit(fn, ...args) + +Returns the promise returned by calling `fn(...args)`. + +#### fn + +Type: `Function` + +Promise-returning/async function. + +#### args + +Any arguments to pass through to `fn`. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +### limit.activeCount + +The number of promises that are currently running. + +### limit.pendingCount + +The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + +### limit.clearQueue() + +Discard pending promises that are waiting to run. + +This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + +Note: This does not cancel promises that are already running. + +## FAQ + +### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? + +This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. + +## Related + +- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control +- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions +- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions +- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
    + + Get professional support for this package with a Tidelift subscription + +
    + + Tidelift helps make open source sustainable for maintainers while giving companies
    assurances about security, maintenance, and licensing for their dependencies. +
    +
    diff --git a/node_modules/mathjs/examples/node_modules/p-locate/index.d.ts b/node_modules/mathjs/examples/node_modules/p-locate/index.d.ts new file mode 100644 index 0000000..14115e1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-locate/index.d.ts @@ -0,0 +1,64 @@ +declare namespace pLocate { + interface Options { + /** + Number of concurrently pending promises returned by `tester`. Minimum: `1`. + + @default Infinity + */ + readonly concurrency?: number; + + /** + Preserve `input` order when searching. + + Disable this to improve performance if you don't care about the order. + + @default true + */ + readonly preserveOrder?: boolean; + } +} + +declare const pLocate: { + /** + Get the first fulfilled promise that satisfies the provided testing function. + + @param input - An iterable of promises/values to test. + @param tester - This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. + @returns A `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + + @example + ``` + import pathExists = require('path-exists'); + import pLocate = require('p-locate'); + + const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' + ]; + + (async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' + })(); + ``` + */ + ( + input: Iterable | ValueType>, + tester: (element: ValueType) => PromiseLike | boolean, + options?: pLocate.Options + ): Promise; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function pLocate( + // input: Iterable | ValueType>, + // tester: (element: ValueType) => PromiseLike | boolean, + // options?: pLocate.Options + // ): Promise; + // export = pLocate; + default: typeof pLocate; +}; + +export = pLocate; diff --git a/node_modules/mathjs/examples/node_modules/p-locate/index.js b/node_modules/mathjs/examples/node_modules/p-locate/index.js new file mode 100644 index 0000000..e13ce15 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-locate/index.js @@ -0,0 +1,52 @@ +'use strict'; +const pLimit = require('p-limit'); + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we await it +const testElement = async (element, tester) => tester(await element); + +// The input can also be a promise, so we `Promise.all()` them both +const finder = async element => { + const values = await Promise.all(element); + if (values[1] === true) { + throw new EndError(values[0]); + } + + return false; +}; + +const pLocate = async (iterable, tester, options) => { + options = { + concurrency: Infinity, + preserveOrder: true, + ...options + }; + + const limit = pLimit(options.concurrency); + + // Start all the promises concurrently with optional limit + const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); + + // Check the promises either serially or concurrently + const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity); + + try { + await Promise.all(items.map(element => checkLimit(finder, element))); + } catch (error) { + if (error instanceof EndError) { + return error.value; + } + + throw error; + } +}; + +module.exports = pLocate; +// TODO: Remove this for the next major release +module.exports.default = pLocate; diff --git a/node_modules/mathjs/examples/node_modules/p-locate/license b/node_modules/mathjs/examples/node_modules/p-locate/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-locate/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/p-locate/package.json b/node_modules/mathjs/examples/node_modules/p-locate/package.json new file mode 100644 index 0000000..e3de275 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-locate/package.json @@ -0,0 +1,53 @@ +{ + "name": "p-locate", + "version": "4.1.0", + "description": "Get the first fulfilled promise that satisfies the provided testing function", + "license": "MIT", + "repository": "sindresorhus/p-locate", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "locate", + "find", + "finder", + "search", + "searcher", + "test", + "array", + "collection", + "iterable", + "iterator", + "race", + "fulfilled", + "fastest", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "p-limit": "^2.2.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "delay": "^4.1.0", + "in-range": "^1.0.0", + "time-span": "^3.0.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/p-locate/readme.md b/node_modules/mathjs/examples/node_modules/p-locate/readme.md new file mode 100644 index 0000000..f8e2c2e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-locate/readme.md @@ -0,0 +1,90 @@ +# p-locate [![Build Status](https://travis-ci.org/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.org/sindresorhus/p-locate) + +> Get the first fulfilled promise that satisfies the provided testing function + +Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find). + + +## Install + +``` +$ npm install p-locate +``` + + +## Usage + +Here we find the first file that exists on disk, in array order. + +```js +const pathExists = require('path-exists'); +const pLocate = require('p-locate'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' +})(); +``` + +*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.* + + +## API + +### pLocate(input, tester, [options]) + +Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +#### input + +Type: `Iterable` + +An iterable of promises/values to test. + +#### tester(element) + +Type: `Function` + +This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. + +#### options + +Type: `Object` + +##### concurrency + +Type: `number`
    +Default: `Infinity`
    +Minimum: `1` + +Number of concurrently pending promises returned by `tester`. + +##### preserveOrder + +Type: `boolean`
    +Default: `true` + +Preserve `input` order when searching. + +Disable this to improve performance if you don't care about the order. + + +## Related + +- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently +- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently +- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled +- [More…](https://github.com/sindresorhus/promise-fun) + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/mathjs/examples/node_modules/p-try/index.d.ts b/node_modules/mathjs/examples/node_modules/p-try/index.d.ts new file mode 100644 index 0000000..2a7319e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-try/index.d.ts @@ -0,0 +1,39 @@ +declare const pTry: { + /** + Start a promise chain. + + @param fn - The function to run to start the promise chain. + @param arguments - Arguments to pass to `fn`. + @returns The value of calling `fn(...arguments)`. If the function throws an error, the returned `Promise` will be rejected with that error. + + @example + ``` + import pTry = require('p-try'); + + (async () => { + try { + const value = await pTry(() => { + return synchronousFunctionThatMightThrow(); + }); + console.log(value); + } catch (error) { + console.error(error); + } + })(); + ``` + */ + ( + fn: (...arguments: ArgumentsType) => PromiseLike | ValueType, + ...arguments: ArgumentsType + ): Promise; + + // TODO: remove this in the next major version, refactor the whole definition to: + // declare function pTry( + // fn: (...arguments: ArgumentsType) => PromiseLike | ValueType, + // ...arguments: ArgumentsType + // ): Promise; + // export = pTry; + default: typeof pTry; +}; + +export = pTry; diff --git a/node_modules/mathjs/examples/node_modules/p-try/index.js b/node_modules/mathjs/examples/node_modules/p-try/index.js new file mode 100644 index 0000000..db858da --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-try/index.js @@ -0,0 +1,9 @@ +'use strict'; + +const pTry = (fn, ...arguments_) => new Promise(resolve => { + resolve(fn(...arguments_)); +}); + +module.exports = pTry; +// TODO: remove this in the next major version +module.exports.default = pTry; diff --git a/node_modules/mathjs/examples/node_modules/p-try/license b/node_modules/mathjs/examples/node_modules/p-try/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-try/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/p-try/package.json b/node_modules/mathjs/examples/node_modules/p-try/package.json new file mode 100644 index 0000000..81c4d32 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-try/package.json @@ -0,0 +1,42 @@ +{ + "name": "p-try", + "version": "2.2.0", + "description": "`Start a promise chain", + "license": "MIT", + "repository": "sindresorhus/p-try", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "try", + "resolve", + "function", + "catch", + "async", + "await", + "promises", + "settled", + "ponyfill", + "polyfill", + "shim", + "bluebird" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/p-try/readme.md b/node_modules/mathjs/examples/node_modules/p-try/readme.md new file mode 100644 index 0000000..4d7bd64 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/p-try/readme.md @@ -0,0 +1,58 @@ +# p-try [![Build Status](https://travis-ci.org/sindresorhus/p-try.svg?branch=master)](https://travis-ci.org/sindresorhus/p-try) + +> Start a promise chain + +[How is it useful?](http://cryto.net/~joepie91/blog/2016/05/11/what-is-promise-try-and-why-does-it-matter/) + + +## Install + +``` +$ npm install p-try +``` + + +## Usage + +```js +const pTry = require('p-try'); + +(async () => { + try { + const value = await pTry(() => { + return synchronousFunctionThatMightThrow(); + }); + console.log(value); + } catch (error) { + console.error(error); + } +})(); +``` + + +## API + +### pTry(fn, ...arguments) + +Returns a `Promise` resolved with the value of calling `fn(...arguments)`. If the function throws an error, the returned `Promise` will be rejected with that error. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +#### fn + +The function to run to start the promise chain. + +#### arguments + +Arguments to pass to `fn`. + + +## Related + +- [p-finally](https://github.com/sindresorhus/p-finally) - `Promise#finally()` ponyfill - Invoked when the promise is settled regardless of outcome +- [More…](https://github.com/sindresorhus/promise-fun) + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/mathjs/examples/node_modules/path-exists/index.d.ts b/node_modules/mathjs/examples/node_modules/path-exists/index.d.ts new file mode 100644 index 0000000..54b7ab8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-exists/index.d.ts @@ -0,0 +1,28 @@ +declare const pathExists: { + /** + Check if a path exists. + + @returns Whether the path exists. + + @example + ``` + // foo.ts + import pathExists = require('path-exists'); + + (async () => { + console.log(await pathExists('foo.ts')); + //=> true + })(); + ``` + */ + (path: string): Promise; + + /** + Synchronously check if a path exists. + + @returns Whether the path exists. + */ + sync(path: string): boolean; +}; + +export = pathExists; diff --git a/node_modules/mathjs/examples/node_modules/path-exists/index.js b/node_modules/mathjs/examples/node_modules/path-exists/index.js new file mode 100644 index 0000000..1943921 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-exists/index.js @@ -0,0 +1,23 @@ +'use strict'; +const fs = require('fs'); +const {promisify} = require('util'); + +const pAccess = promisify(fs.access); + +module.exports = async path => { + try { + await pAccess(path); + return true; + } catch (_) { + return false; + } +}; + +module.exports.sync = path => { + try { + fs.accessSync(path); + return true; + } catch (_) { + return false; + } +}; diff --git a/node_modules/mathjs/examples/node_modules/path-exists/license b/node_modules/mathjs/examples/node_modules/path-exists/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-exists/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/path-exists/package.json b/node_modules/mathjs/examples/node_modules/path-exists/package.json new file mode 100644 index 0000000..0755256 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-exists/package.json @@ -0,0 +1,39 @@ +{ + "name": "path-exists", + "version": "4.0.0", + "description": "Check if a path exists", + "license": "MIT", + "repository": "sindresorhus/path-exists", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "path", + "exists", + "exist", + "file", + "filepath", + "fs", + "filesystem", + "file-system", + "access", + "stat" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/path-exists/readme.md b/node_modules/mathjs/examples/node_modules/path-exists/readme.md new file mode 100644 index 0000000..81f9845 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-exists/readme.md @@ -0,0 +1,52 @@ +# path-exists [![Build Status](https://travis-ci.org/sindresorhus/path-exists.svg?branch=master)](https://travis-ci.org/sindresorhus/path-exists) + +> Check if a path exists + +NOTE: `fs.existsSync` has been un-deprecated in Node.js since 6.8.0. If you only need to check synchronously, this module is not needed. + +While [`fs.exists()`](https://nodejs.org/api/fs.html#fs_fs_exists_path_callback) is being [deprecated](https://github.com/iojs/io.js/issues/103), there's still a genuine use-case of being able to check if a path exists for other purposes than doing IO with it. + +Never use this before handling a file though: + +> In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to `fs.exists()` and `fs.open()`. Just open the file and handle the error when it's not there. + + +## Install + +``` +$ npm install path-exists +``` + + +## Usage + +```js +// foo.js +const pathExists = require('path-exists'); + +(async () => { + console.log(await pathExists('foo.js')); + //=> true +})(); +``` + + +## API + +### pathExists(path) + +Returns a `Promise` of whether the path exists. + +### pathExists.sync(path) + +Returns a `boolean` of whether the path exists. + + +## Related + +- [path-exists-cli](https://github.com/sindresorhus/path-exists-cli) - CLI for this module + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/mathjs/examples/node_modules/path-key/index.d.ts b/node_modules/mathjs/examples/node_modules/path-key/index.d.ts new file mode 100644 index 0000000..7c575d1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-key/index.d.ts @@ -0,0 +1,40 @@ +/// + +declare namespace pathKey { + interface Options { + /** + Use a custom environment variables object. Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env). + */ + readonly env?: {[key: string]: string | undefined}; + + /** + Get the PATH key for a specific platform. Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform). + */ + readonly platform?: NodeJS.Platform; + } +} + +declare const pathKey: { + /** + Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform. + + @example + ``` + import pathKey = require('path-key'); + + const key = pathKey(); + //=> 'PATH' + + const PATH = process.env[key]; + //=> '/usr/local/bin:/usr/bin:/bin' + ``` + */ + (options?: pathKey.Options): string; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function pathKey(options?: pathKey.Options): string; + // export = pathKey; + default: typeof pathKey; +}; + +export = pathKey; diff --git a/node_modules/mathjs/examples/node_modules/path-key/index.js b/node_modules/mathjs/examples/node_modules/path-key/index.js new file mode 100644 index 0000000..0cf6415 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-key/index.js @@ -0,0 +1,16 @@ +'use strict'; + +const pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; + +module.exports = pathKey; +// TODO: Remove this for the next major release +module.exports.default = pathKey; diff --git a/node_modules/mathjs/examples/node_modules/path-key/license b/node_modules/mathjs/examples/node_modules/path-key/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-key/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/path-key/package.json b/node_modules/mathjs/examples/node_modules/path-key/package.json new file mode 100644 index 0000000..c8cbd38 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-key/package.json @@ -0,0 +1,39 @@ +{ + "name": "path-key", + "version": "3.1.1", + "description": "Get the PATH environment variable key cross-platform", + "license": "MIT", + "repository": "sindresorhus/path-key", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "path", + "key", + "environment", + "env", + "variable", + "var", + "get", + "cross-platform", + "windows" + ], + "devDependencies": { + "@types/node": "^11.13.0", + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/path-key/readme.md b/node_modules/mathjs/examples/node_modules/path-key/readme.md new file mode 100644 index 0000000..a9052d7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-key/readme.md @@ -0,0 +1,61 @@ +# path-key [![Build Status](https://travis-ci.org/sindresorhus/path-key.svg?branch=master)](https://travis-ci.org/sindresorhus/path-key) + +> Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform + +It's usually `PATH`, but on Windows it can be any casing like `Path`... + + +## Install + +``` +$ npm install path-key +``` + + +## Usage + +```js +const pathKey = require('path-key'); + +const key = pathKey(); +//=> 'PATH' + +const PATH = process.env[key]; +//=> '/usr/local/bin:/usr/bin:/bin' +``` + + +## API + +### pathKey(options?) + +#### options + +Type: `object` + +##### env + +Type: `object`
    +Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env) + +Use a custom environment variables object. + +#### platform + +Type: `string`
    +Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform) + +Get the PATH key for a specific platform. + + +--- + +
    + + Get professional support for this package with a Tidelift subscription + +
    + + Tidelift helps make open source sustainable for maintainers while giving companies
    assurances about security, maintenance, and licensing for their dependencies. +
    +
    diff --git a/node_modules/mathjs/examples/node_modules/path-parse/LICENSE b/node_modules/mathjs/examples/node_modules/path-parse/LICENSE new file mode 100644 index 0000000..810f3db --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-parse/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Javier Blanco + +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. diff --git a/node_modules/mathjs/examples/node_modules/path-parse/README.md b/node_modules/mathjs/examples/node_modules/path-parse/README.md new file mode 100644 index 0000000..05097f8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-parse/README.md @@ -0,0 +1,42 @@ +# path-parse [![Build Status](https://travis-ci.org/jbgutierrez/path-parse.svg?branch=master)](https://travis-ci.org/jbgutierrez/path-parse) + +> Node.js [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) [ponyfill](https://ponyfill.com). + +## Install + +``` +$ npm install --save path-parse +``` + +## Usage + +```js +var pathParse = require('path-parse'); + +pathParse('/home/user/dir/file.txt'); +//=> { +// root : "/", +// dir : "/home/user/dir", +// base : "file.txt", +// ext : ".txt", +// name : "file" +// } +``` + +## API + +See [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) docs. + +### pathParse(path) + +### pathParse.posix(path) + +The Posix specific version. + +### pathParse.win32(path) + +The Windows specific version. + +## License + +MIT © [Javier Blanco](http://jbgutierrez.info) diff --git a/node_modules/mathjs/examples/node_modules/path-parse/index.js b/node_modules/mathjs/examples/node_modules/path-parse/index.js new file mode 100644 index 0000000..f062d0a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-parse/index.js @@ -0,0 +1,75 @@ +'use strict'; + +var isWindows = process.platform === 'win32'; + +// Regex to split a windows path into into [dir, root, basename, name, ext] +var splitWindowsRe = + /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/; + +var win32 = {}; + +function win32SplitPath(filename) { + return splitWindowsRe.exec(filename).slice(1); +} + +win32.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = win32SplitPath(pathString); + if (!allParts || allParts.length !== 5) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + return { + root: allParts[1], + dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1), + base: allParts[2], + ext: allParts[4], + name: allParts[3] + }; +}; + + + +// Split a filename into [dir, root, basename, name, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/; +var posix = {}; + + +function posixSplitPath(filename) { + return splitPathRe.exec(filename).slice(1); +} + + +posix.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = posixSplitPath(pathString); + if (!allParts || allParts.length !== 5) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + + return { + root: allParts[1], + dir: allParts[0].slice(0, -1), + base: allParts[2], + ext: allParts[4], + name: allParts[3], + }; +}; + + +if (isWindows) + module.exports = win32.parse; +else /* posix */ + module.exports = posix.parse; + +module.exports.posix = posix.parse; +module.exports.win32 = win32.parse; diff --git a/node_modules/mathjs/examples/node_modules/path-parse/package.json b/node_modules/mathjs/examples/node_modules/path-parse/package.json new file mode 100644 index 0000000..36c23f8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/path-parse/package.json @@ -0,0 +1,33 @@ +{ + "name": "path-parse", + "version": "1.0.7", + "description": "Node.js path.parse() ponyfill", + "main": "index.js", + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/jbgutierrez/path-parse.git" + }, + "keywords": [ + "path", + "paths", + "file", + "dir", + "parse", + "built-in", + "util", + "utils", + "core", + "ponyfill", + "polyfill", + "shim" + ], + "author": "Javier Blanco ", + "license": "MIT", + "bugs": { + "url": "https://github.com/jbgutierrez/path-parse/issues" + }, + "homepage": "https://github.com/jbgutierrez/path-parse#readme" +} diff --git a/node_modules/mathjs/examples/node_modules/picocolors/LICENSE b/node_modules/mathjs/examples/node_modules/picocolors/LICENSE new file mode 100644 index 0000000..496098c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/picocolors/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2021 Alexey Raspopov, Kostiantyn Denysov, Anton Verinov + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mathjs/examples/node_modules/picocolors/README.md b/node_modules/mathjs/examples/node_modules/picocolors/README.md new file mode 100644 index 0000000..8e47aa8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/picocolors/README.md @@ -0,0 +1,21 @@ +# picocolors + +The tiniest and the fastest library for terminal output formatting with ANSI colors. + +```javascript +import pc from "picocolors" + +console.log( + pc.green(`How are ${pc.italic(`you`)} doing?`) +) +``` + +- **No dependencies.** +- **14 times** smaller and **2 times** faster than chalk. +- Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist. +- Node.js v6+ & browsers support. Support for both CJS and ESM projects. +- TypeScript type declarations included. +- [`NO_COLOR`](https://no-color.org/) friendly. + +## Docs +Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub. diff --git a/node_modules/mathjs/examples/node_modules/picocolors/package.json b/node_modules/mathjs/examples/node_modules/picocolors/package.json new file mode 100644 index 0000000..85a12d5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/picocolors/package.json @@ -0,0 +1,25 @@ +{ + "name": "picocolors", + "version": "1.0.0", + "main": "./picocolors.js", + "types": "./picocolors.d.ts", + "browser": { + "./picocolors.js": "./picocolors.browser.js" + }, + "sideEffects": false, + "description": "The tiniest and the fastest library for terminal output formatting with ANSI colors", + "files": [ + "picocolors.*", + "types.ts" + ], + "keywords": [ + "terminal", + "colors", + "formatting", + "cli", + "console" + ], + "author": "Alexey Raspopov", + "repository": "alexeyraspopov/picocolors", + "license": "ISC" +} diff --git a/node_modules/mathjs/examples/node_modules/picocolors/picocolors.browser.js b/node_modules/mathjs/examples/node_modules/picocolors/picocolors.browser.js new file mode 100644 index 0000000..5eb9fbe --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/picocolors/picocolors.browser.js @@ -0,0 +1,4 @@ +var x=String; +var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x}}; +module.exports=create(); +module.exports.createColors = create; diff --git a/node_modules/mathjs/examples/node_modules/picocolors/picocolors.d.ts b/node_modules/mathjs/examples/node_modules/picocolors/picocolors.d.ts new file mode 100644 index 0000000..94e146a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/picocolors/picocolors.d.ts @@ -0,0 +1,5 @@ +import { Colors } from "./types" + +declare const picocolors: Colors & { createColors: (enabled?: boolean) => Colors } + +export = picocolors diff --git a/node_modules/mathjs/examples/node_modules/picocolors/picocolors.js b/node_modules/mathjs/examples/node_modules/picocolors/picocolors.js new file mode 100644 index 0000000..fdb6304 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/picocolors/picocolors.js @@ -0,0 +1,58 @@ +let tty = require("tty") + +let isColorSupported = + !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && + ("FORCE_COLOR" in process.env || + process.argv.includes("--color") || + process.platform === "win32" || + (tty.isatty(1) && process.env.TERM !== "dumb") || + "CI" in process.env) + +let formatter = + (open, close, replace = open) => + input => { + let string = "" + input + let index = string.indexOf(close, open.length) + return ~index + ? open + replaceClose(string, close, replace, index) + close + : open + string + close + } + +let replaceClose = (string, close, replace, index) => { + let start = string.substring(0, index) + replace + let end = string.substring(index + close.length) + let nextIndex = end.indexOf(close) + return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end +} + +let createColors = (enabled = isColorSupported) => ({ + isColorSupported: enabled, + reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, + bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, + dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, + italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, + underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, + inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, + hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, + strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, + black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, + red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, + green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, + yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, + blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, + magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, + cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, + white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, + gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, + bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, + bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, + bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, + bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, + bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, + bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, + bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, + bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, +}) + +module.exports = createColors() +module.exports.createColors = createColors diff --git a/node_modules/mathjs/examples/node_modules/picocolors/types.ts b/node_modules/mathjs/examples/node_modules/picocolors/types.ts new file mode 100644 index 0000000..b4bacee --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/picocolors/types.ts @@ -0,0 +1,30 @@ +export type Formatter = (input: string | number | null | undefined) => string + +export interface Colors { + isColorSupported: boolean + reset: Formatter + bold: Formatter + dim: Formatter + italic: Formatter + underline: Formatter + inverse: Formatter + hidden: Formatter + strikethrough: Formatter + black: Formatter + red: Formatter + green: Formatter + yellow: Formatter + blue: Formatter + magenta: Formatter + cyan: Formatter + white: Formatter + gray: Formatter + bgBlack: Formatter + bgRed: Formatter + bgGreen: Formatter + bgYellow: Formatter + bgBlue: Formatter + bgMagenta: Formatter + bgCyan: Formatter + bgWhite: Formatter +} diff --git a/node_modules/mathjs/examples/node_modules/pkg-dir/index.d.ts b/node_modules/mathjs/examples/node_modules/pkg-dir/index.d.ts new file mode 100644 index 0000000..e339404 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/pkg-dir/index.d.ts @@ -0,0 +1,44 @@ +declare const pkgDir: { + /** + Find the root directory of a Node.js project or npm package. + + @param cwd - Directory to start from. Default: `process.cwd()`. + @returns The project root path or `undefined` if it couldn't be found. + + @example + ``` + // / + // └── Users + // └── sindresorhus + // └── foo + // ├── package.json + // └── bar + // ├── baz + // └── example.js + + // example.js + import pkgDir = require('pkg-dir'); + + (async () => { + const rootDir = await pkgDir(__dirname); + + console.log(rootDir); + //=> '/Users/sindresorhus/foo' + })(); + ``` + */ + (cwd?: string): Promise; + + /** + Synchronously find the root directory of a Node.js project or npm package. + + @param cwd - Directory to start from. Default: `process.cwd()`. + @returns The project root path or `undefined` if it couldn't be found. + */ + sync(cwd?: string): string | undefined; + + // TODO: Remove this for the next major release + default: typeof pkgDir; +}; + +export = pkgDir; diff --git a/node_modules/mathjs/examples/node_modules/pkg-dir/index.js b/node_modules/mathjs/examples/node_modules/pkg-dir/index.js new file mode 100644 index 0000000..83e683d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/pkg-dir/index.js @@ -0,0 +1,17 @@ +'use strict'; +const path = require('path'); +const findUp = require('find-up'); + +const pkgDir = async cwd => { + const filePath = await findUp('package.json', {cwd}); + return filePath && path.dirname(filePath); +}; + +module.exports = pkgDir; +// TODO: Remove this for the next major release +module.exports.default = pkgDir; + +module.exports.sync = cwd => { + const filePath = findUp.sync('package.json', {cwd}); + return filePath && path.dirname(filePath); +}; diff --git a/node_modules/mathjs/examples/node_modules/pkg-dir/license b/node_modules/mathjs/examples/node_modules/pkg-dir/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/pkg-dir/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/pkg-dir/package.json b/node_modules/mathjs/examples/node_modules/pkg-dir/package.json new file mode 100644 index 0000000..aad11e8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/pkg-dir/package.json @@ -0,0 +1,56 @@ +{ + "name": "pkg-dir", + "version": "4.2.0", + "description": "Find the root directory of a Node.js project or npm package", + "license": "MIT", + "repository": "sindresorhus/pkg-dir", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "package", + "json", + "root", + "npm", + "entry", + "find", + "up", + "find-up", + "findup", + "look-up", + "look", + "file", + "search", + "match", + "resolve", + "parent", + "parents", + "folder", + "directory", + "dir", + "walk", + "walking", + "path" + ], + "dependencies": { + "find-up": "^4.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "tempy": "^0.3.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/pkg-dir/readme.md b/node_modules/mathjs/examples/node_modules/pkg-dir/readme.md new file mode 100644 index 0000000..92a77f4 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/pkg-dir/readme.md @@ -0,0 +1,66 @@ +# pkg-dir [![Build Status](https://travis-ci.org/sindresorhus/pkg-dir.svg?branch=master)](https://travis-ci.org/sindresorhus/pkg-dir) + +> Find the root directory of a Node.js project or npm package + + +## Install + +``` +$ npm install pkg-dir +``` + + +## Usage + +``` +/ +└── Users + └── sindresorhus + └── foo + ├── package.json + └── bar + ├── baz + └── example.js +``` + +```js +// example.js +const pkgDir = require('pkg-dir'); + +(async () => { + const rootDir = await pkgDir(__dirname); + + console.log(rootDir); + //=> '/Users/sindresorhus/foo' +})(); +``` + + +## API + +### pkgDir([cwd]) + +Returns a `Promise` for either the project root path or `undefined` if it couldn't be found. + +### pkgDir.sync([cwd]) + +Returns the project root path or `undefined` if it couldn't be found. + +#### cwd + +Type: `string`
    +Default: `process.cwd()` + +Directory to start from. + + +## Related + +- [pkg-dir-cli](https://github.com/sindresorhus/pkg-dir-cli) - CLI for this module +- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file +- [find-up](https://github.com/sindresorhus/find-up) - Find a file by walking up parent directories + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/mathjs/examples/node_modules/punycode/LICENSE-MIT.txt b/node_modules/mathjs/examples/node_modules/punycode/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/punycode/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +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. diff --git a/node_modules/mathjs/examples/node_modules/punycode/README.md b/node_modules/mathjs/examples/node_modules/punycode/README.md new file mode 100644 index 0000000..ee2f9d6 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/punycode/README.md @@ -0,0 +1,122 @@ +# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) + +Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). + +This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: + +* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) +* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) +* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) +* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) +* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) + +This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). + +The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install punycode --save +``` + +In [Node.js](https://nodejs.org/): + +```js +const punycode = require('punycode'); +``` + +## API + +### `punycode.decode(string)` + +Converts a Punycode string of ASCII symbols to a string of Unicode symbols. + +```js +// decode domain name parts +punycode.decode('maana-pta'); // 'mañana' +punycode.decode('--dqo34k'); // '☃-⌘' +``` + +### `punycode.encode(string)` + +Converts a string of Unicode symbols to a Punycode string of ASCII symbols. + +```js +// encode domain name parts +punycode.encode('mañana'); // 'maana-pta' +punycode.encode('☃-⌘'); // '--dqo34k' +``` + +### `punycode.toUnicode(input)` + +Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. + +```js +// decode domain names +punycode.toUnicode('xn--maana-pta.com'); +// → 'mañana.com' +punycode.toUnicode('xn----dqo34k.com'); +// → '☃-⌘.com' + +// decode email addresses +punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); +// → 'джумла@джpумлатест.bрфa' +``` + +### `punycode.toASCII(input)` + +Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. + +```js +// encode domain names +punycode.toASCII('mañana.com'); +// → 'xn--maana-pta.com' +punycode.toASCII('☃-⌘.com'); +// → 'xn----dqo34k.com' + +// encode email addresses +punycode.toASCII('джумла@джpумлатест.bрфa'); +// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' +``` + +### `punycode.ucs2` + +#### `punycode.ucs2.decode(string)` + +Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. + +```js +punycode.ucs2.decode('abc'); +// → [0x61, 0x62, 0x63] +// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: +punycode.ucs2.decode('\uD834\uDF06'); +// → [0x1D306] +``` + +#### `punycode.ucs2.encode(codePoints)` + +Creates a string based on an array of numeric code point values. + +```js +punycode.ucs2.encode([0x61, 0x62, 0x63]); +// → 'abc' +punycode.ucs2.encode([0x1D306]); +// → '\uD834\uDF06' +``` + +### `punycode.version` + +A string representing the current Punycode.js version number. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +Punycode.js is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/mathjs/examples/node_modules/punycode/package.json b/node_modules/mathjs/examples/node_modules/punycode/package.json new file mode 100644 index 0000000..9202ccf --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/punycode/package.json @@ -0,0 +1,58 @@ +{ + "name": "punycode", + "version": "2.1.1", + "description": "A robust Punycode converter that fully complies to RFC 3492 and RFC 5891, and works on nearly all JavaScript platforms.", + "homepage": "https://mths.be/punycode", + "main": "punycode.js", + "jsnext:main": "punycode.es6.js", + "module": "punycode.es6.js", + "engines": { + "node": ">=6" + }, + "keywords": [ + "punycode", + "unicode", + "idn", + "idna", + "dns", + "url", + "domain" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "contributors": [ + { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/bestiejs/punycode.js.git" + }, + "bugs": "https://github.com/bestiejs/punycode.js/issues", + "files": [ + "LICENSE-MIT.txt", + "punycode.js", + "punycode.es6.js" + ], + "scripts": { + "test": "mocha tests", + "prepublish": "node scripts/prepublish.js" + }, + "devDependencies": { + "codecov": "^1.0.1", + "istanbul": "^0.4.1", + "mocha": "^2.5.3" + }, + "jspm": { + "map": { + "./punycode.js": { + "node": "@node/punycode" + } + } + } +} diff --git a/node_modules/mathjs/examples/node_modules/punycode/punycode.es6.js b/node_modules/mathjs/examples/node_modules/punycode/punycode.es6.js new file mode 100644 index 0000000..4610bc9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/punycode/punycode.es6.js @@ -0,0 +1,441 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + const result = []; + let length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + const parts = string.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + const labels = string.split('.'); + const encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = array => String.fromCodePoint(...array); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + let oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + let inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + let basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +export { ucs2decode, ucs2encode, decode, encode, toASCII, toUnicode }; +export default punycode; diff --git a/node_modules/mathjs/examples/node_modules/punycode/punycode.js b/node_modules/mathjs/examples/node_modules/punycode/punycode.js new file mode 100644 index 0000000..ea61fd0 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/punycode/punycode.js @@ -0,0 +1,440 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + const result = []; + let length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + const parts = string.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + const labels = string.split('.'); + const encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = array => String.fromCodePoint(...array); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + let oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + let inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + let basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +module.exports = punycode; diff --git a/node_modules/mathjs/examples/node_modules/randombytes/.travis.yml b/node_modules/mathjs/examples/node_modules/randombytes/.travis.yml new file mode 100644 index 0000000..69fdf71 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/randombytes/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +matrix: + include: + - node_js: '7' + env: TEST_SUITE=test + - node_js: '6' + env: TEST_SUITE=test + - node_js: '5' + env: TEST_SUITE=test + - node_js: '4' + env: TEST_SUITE=test + - node_js: '4' + env: TEST_SUITE=phantom +script: "npm run-script $TEST_SUITE" diff --git a/node_modules/mathjs/examples/node_modules/randombytes/.zuul.yml b/node_modules/mathjs/examples/node_modules/randombytes/.zuul.yml new file mode 100644 index 0000000..96d9cfb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/randombytes/.zuul.yml @@ -0,0 +1 @@ +ui: tape diff --git a/node_modules/mathjs/examples/node_modules/randombytes/LICENSE b/node_modules/mathjs/examples/node_modules/randombytes/LICENSE new file mode 100644 index 0000000..fea9d48 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/randombytes/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 crypto-browserify + +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. diff --git a/node_modules/mathjs/examples/node_modules/randombytes/README.md b/node_modules/mathjs/examples/node_modules/randombytes/README.md new file mode 100644 index 0000000..3bacba4 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/randombytes/README.md @@ -0,0 +1,14 @@ +randombytes +=== + +[![Version](http://img.shields.io/npm/v/randombytes.svg)](https://www.npmjs.org/package/randombytes) [![Build Status](https://travis-ci.org/crypto-browserify/randombytes.svg?branch=master)](https://travis-ci.org/crypto-browserify/randombytes) + +randombytes from node that works in the browser. In node you just get crypto.randomBytes, but in the browser it uses .crypto/msCrypto.getRandomValues + +```js +var randomBytes = require('randombytes'); +randomBytes(16);//get 16 random bytes +randomBytes(16, function (err, resp) { + // resp is 16 random bytes +}); +``` diff --git a/node_modules/mathjs/examples/node_modules/randombytes/browser.js b/node_modules/mathjs/examples/node_modules/randombytes/browser.js new file mode 100644 index 0000000..0fb0b71 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/randombytes/browser.js @@ -0,0 +1,50 @@ +'use strict' + +// limit of Crypto.getRandomValues() +// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues +var MAX_BYTES = 65536 + +// Node supports requesting up to this number of bytes +// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 +var MAX_UINT32 = 4294967295 + +function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') +} + +var Buffer = require('safe-buffer').Buffer +var crypto = global.crypto || global.msCrypto + +if (crypto && crypto.getRandomValues) { + module.exports = randomBytes +} else { + module.exports = oldBrowser +} + +function randomBytes (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + + var bytes = Buffer.allocUnsafe(size) + + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)) + } + } else { + crypto.getRandomValues(bytes) + } + } + + if (typeof cb === 'function') { + return process.nextTick(function () { + cb(null, bytes) + }) + } + + return bytes +} diff --git a/node_modules/mathjs/examples/node_modules/randombytes/index.js b/node_modules/mathjs/examples/node_modules/randombytes/index.js new file mode 100644 index 0000000..a2d9e39 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/randombytes/index.js @@ -0,0 +1 @@ +module.exports = require('crypto').randomBytes diff --git a/node_modules/mathjs/examples/node_modules/randombytes/package.json b/node_modules/mathjs/examples/node_modules/randombytes/package.json new file mode 100644 index 0000000..3623652 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/randombytes/package.json @@ -0,0 +1,36 @@ +{ + "name": "randombytes", + "version": "2.1.0", + "description": "random bytes from browserify stand alone", + "main": "index.js", + "scripts": { + "test": "standard && node test.js | tspec", + "phantom": "zuul --phantom -- test.js", + "local": "zuul --local --no-coverage -- test.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:crypto-browserify/randombytes.git" + }, + "keywords": [ + "crypto", + "random" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/randombytes/issues" + }, + "homepage": "https://github.com/crypto-browserify/randombytes", + "browser": "browser.js", + "devDependencies": { + "phantomjs": "^1.9.9", + "standard": "^10.0.2", + "tap-spec": "^2.1.2", + "tape": "^4.6.3", + "zuul": "^3.7.2" + }, + "dependencies": { + "safe-buffer": "^5.1.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/randombytes/test.js b/node_modules/mathjs/examples/node_modules/randombytes/test.js new file mode 100644 index 0000000..f266976 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/randombytes/test.js @@ -0,0 +1,81 @@ +var test = require('tape') +var randomBytes = require('./') +var MAX_BYTES = 65536 +var MAX_UINT32 = 4294967295 + +test('sync', function (t) { + t.plan(9) + t.equals(randomBytes(0).length, 0, 'len: ' + 0) + t.equals(randomBytes(3).length, 3, 'len: ' + 3) + t.equals(randomBytes(30).length, 30, 'len: ' + 30) + t.equals(randomBytes(300).length, 300, 'len: ' + 300) + t.equals(randomBytes(17 + MAX_BYTES).length, 17 + MAX_BYTES, 'len: ' + 17 + MAX_BYTES) + t.equals(randomBytes(MAX_BYTES * 100).length, MAX_BYTES * 100, 'len: ' + MAX_BYTES * 100) + t.throws(function () { + randomBytes(MAX_UINT32 + 1) + }) + t.throws(function () { + t.equals(randomBytes(-1)) + }) + t.throws(function () { + t.equals(randomBytes('hello')) + }) +}) + +test('async', function (t) { + t.plan(9) + + randomBytes(0, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 0, 'len: ' + 0) + }) + + randomBytes(3, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 3, 'len: ' + 3) + }) + + randomBytes(30, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 30, 'len: ' + 30) + }) + + randomBytes(300, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 300, 'len: ' + 300) + }) + + randomBytes(17 + MAX_BYTES, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 17 + MAX_BYTES, 'len: ' + 17 + MAX_BYTES) + }) + + randomBytes(MAX_BYTES * 100, function (err, resp) { + if (err) throw err + + t.equals(resp.length, MAX_BYTES * 100, 'len: ' + MAX_BYTES * 100) + }) + + t.throws(function () { + randomBytes(MAX_UINT32 + 1, function () { + t.ok(false, 'should not get here') + }) + }) + + t.throws(function () { + randomBytes(-1, function () { + t.ok(false, 'should not get here') + }) + }) + + t.throws(function () { + randomBytes('hello', function () { + t.ok(false, 'should not get here') + }) + }) +}) diff --git a/node_modules/mathjs/examples/node_modules/rechoir/LICENSE b/node_modules/mathjs/examples/node_modules/rechoir/LICENSE new file mode 100644 index 0000000..41ed300 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/rechoir/LICENSE @@ -0,0 +1,24 @@ +The MIT License (MIT) + +Copyright (c) 2014-2019 Tyler Kellen , Blaine Bublitz , and Eric Schoffstall + +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. diff --git a/node_modules/mathjs/examples/node_modules/rechoir/README.md b/node_modules/mathjs/examples/node_modules/rechoir/README.md new file mode 100644 index 0000000..cf96e4f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/rechoir/README.md @@ -0,0 +1,83 @@ +

    + + + +

    + +# rechoir + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] + +Prepare a node environment to require files with different extensions. + +## What is it? + +This module, in conjunction with [interpret]-like objects, can register any filetype the npm ecosystem has a module loader for. This library is a dependency of [Liftoff]. + +**Note:** While `rechoir` will automatically load and register transpilers like `coffee-script`, you must provide a local installation. The transpilers are **not** bundled with this module. + + +## rechoir for enterprise + +Available as part of the Tidelift Subscription + +The maintainers of rechoir and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-rechoir?utm_source=npm-rechoir&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + + +## Usage + +```js +const config = require('interpret').extensions; +const rechoir = require('rechoir'); +rechoir.prepare(config, './test/fixtures/test.coffee'); +rechoir.prepare(config, './test/fixtures/test.csv'); +rechoir.prepare(config, './test/fixtures/test.toml'); + +console.log(require('./test/fixtures/test.coffee')); +console.log(require('./test/fixtures/test.csv')); +console.log(require('./test/fixtures/test.toml')); +``` + +## API + +### `prepare(config, filepath, [cwd], [noThrow])` + +Look for a module loader associated with the provided file and attempt require it. If necessary, run any setup required to inject it into [require.extensions](http://nodejs.org/api/globals.html#globals_require_extensions). + +`config` An [interpret]-like configuration object. + +`filepath` A file whose type you'd like to register a module loader for. + +`cwd` An optional path to start searching for the module required to load the requested file. Defaults to the directory of `filepath`. + +`noThrow` An optional boolean indicating if the method should avoid throwing. + +If calling this method is successful (e.g. it doesn't throw), you can now require files of the type you requested natively. + +An error with a `failures` property will be thrown if the module loader(s) configured for a given extension cannot be registered. + +If a loader is already registered, this will simply return `true`. + +## License + +MIT + +[interpret]: http://github.com/gulpjs/interpret +[Liftoff]: http://github.com/gulpjs/liftoff + +[downloads-image]: http://img.shields.io/npm/dm/rechoir.svg +[npm-url]: https://www.npmjs.com/package/rechoir +[npm-image]: http://img.shields.io/npm/v/rechoir.svg + +[travis-url]: https://travis-ci.org/gulpjs/rechoir +[travis-image]: http://img.shields.io/travis/gulpjs/rechoir.svg?label=travis-ci + +[appveyor-url]: https://ci.appveyor.com/project/gulpjs/rechoir +[appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/rechoir.svg?label=appveyor + +[coveralls-url]: https://coveralls.io/r/gulpjs/rechoir +[coveralls-image]: http://img.shields.io/coveralls/gulpjs/rechoir/master.svg + +[gitter-url]: https://gitter.im/gulpjs/gulp +[gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg + diff --git a/node_modules/mathjs/examples/node_modules/rechoir/index.js b/node_modules/mathjs/examples/node_modules/rechoir/index.js new file mode 100644 index 0000000..eb9ec70 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/rechoir/index.js @@ -0,0 +1,67 @@ +var path = require('path'); + +var extension = require('./lib/extension'); +var normalize = require('./lib/normalize'); +var register = require('./lib/register'); + +exports.prepare = function(extensions, filepath, cwd, nothrow) { + var config, usedExtension, err, option, attempt, error; + var attempts = []; + var onlyErrors = true; + var exts = extension(filepath); + + if (exts) { + exts.some(function(ext) { + usedExtension = ext; + config = normalize(extensions[ext]); + return !!config; + }); + } + + if (Object.keys(require.extensions).indexOf(usedExtension) !== -1) { + return true; + } + + if (!config) { + if (nothrow) { + return; + } + + throw new Error('No module loader found for "' + usedExtension + '".'); + } + + if (!cwd) { + cwd = path.dirname(path.resolve(filepath)); + } + if (!Array.isArray(config)) { + config = [config]; + } + + for (var i in config) { + option = config[i]; + attempt = register(cwd, option.module, option.register); + error = (attempt instanceof Error) ? attempt : null; + if (error) { + attempt = null; + } + attempts.push({ + moduleName: option.module, + module: attempt, + error: error, + }); + if (!error) { + onlyErrors = false; + break; + } + } + if (onlyErrors) { + err = new Error('Unable to use specified module loaders for "' + usedExtension + '".'); + err.failures = attempts; + if (nothrow) { + return err; + } + + throw err; + } + return attempts; +}; diff --git a/node_modules/mathjs/examples/node_modules/rechoir/lib/extension.js b/node_modules/mathjs/examples/node_modules/rechoir/lib/extension.js new file mode 100644 index 0000000..cc8070d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/rechoir/lib/extension.js @@ -0,0 +1,44 @@ +'use strict'; + +var path = require('path'); + +function getLongExtension(basename) { + if (basename[basename.length - 1] === '.') { + return null; + } + + var startIndex = (basename[0] === '.') ? 1 : 0; + + var dotIndex = basename.indexOf('.', startIndex); + if (dotIndex <= startIndex) { + return null; + } + + return basename.slice(dotIndex); +} + +function getPossibleExtensions(longExtension) { + var arr = [longExtension]; + var len = longExtension.length; + var startIndex = 1; + + while (startIndex < len) { + var dotIndex = longExtension.indexOf('.', startIndex); + if (dotIndex < 0) { + break; + } + arr.push(longExtension.slice(dotIndex)); + startIndex = dotIndex + 1; + } + + return arr; +} + +module.exports = function(input) { + var basename = path.basename(input); + var longExtension = getLongExtension(basename); + if (!longExtension) { + return; + } + return getPossibleExtensions(longExtension); +}; diff --git a/node_modules/mathjs/examples/node_modules/rechoir/lib/normalize.js b/node_modules/mathjs/examples/node_modules/rechoir/lib/normalize.js new file mode 100644 index 0000000..7e974f6 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/rechoir/lib/normalize.js @@ -0,0 +1,13 @@ +function normalizer(config) { + if (typeof config === 'string') { + return { module: config }; + } + return config; +} + +module.exports = function(config) { + if (Array.isArray(config)) { + return config.map(normalizer); + } + return normalizer(config); +}; diff --git a/node_modules/mathjs/examples/node_modules/rechoir/lib/register.js b/node_modules/mathjs/examples/node_modules/rechoir/lib/register.js new file mode 100644 index 0000000..f5d2336 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/rechoir/lib/register.js @@ -0,0 +1,15 @@ +var resolve = require('resolve'); + +module.exports = function(cwd, moduleName, register) { + var result; + try { + var modulePath = resolve.sync(moduleName, { basedir: cwd }); + result = require(modulePath); + if (typeof register === 'function') { + register(result); + } + } catch (e) { + result = e; + } + return result; +}; diff --git a/node_modules/mathjs/examples/node_modules/rechoir/package.json b/node_modules/mathjs/examples/node_modules/rechoir/package.json new file mode 100644 index 0000000..00d125c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/rechoir/package.json @@ -0,0 +1,46 @@ +{ + "name": "rechoir", + "version": "0.7.1", + "description": "Prepare a node environment to require files with different extensions.", + "author": "Gulp Team (http://gulpjs.com/)", + "contributors": [ + "Blaine Bublitz ", + "Tyler Kellen (http://goingslowly.com/)" + ], + "repository": "gulpjs/rechoir", + "license": "MIT", + "engines": { + "node": ">= 0.10" + }, + "main": "index.js", + "files": [ + "LICENSE", + "index.js", + "lib/" + ], + "scripts": { + "lint": "eslint .", + "pretest": "rm -rf tmp/ && npm run lint", + "test": "mocha --async-only test test/lib", + "cover": "istanbul cover _mocha --report lcovonly test test/lib", + "coveralls": "npm run cover && istanbul-coveralls" + }, + "dependencies": { + "resolve": "^1.9.0" + }, + "devDependencies": { + "eslint": "^2.13.0", + "eslint-config-gulp": "^3.0.1", + "expect": "^1.20.2", + "istanbul": "^0.4.3", + "istanbul-coveralls": "^1.0.3", + "mocha": "^3.5.3" + }, + "keywords": [ + "require", + "loader", + "extension", + "extensions", + "prepare" + ] +} diff --git a/node_modules/mathjs/examples/node_modules/resolve-cwd/index.d.ts b/node_modules/mathjs/examples/node_modules/resolve-cwd/index.d.ts new file mode 100644 index 0000000..4cc6003 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve-cwd/index.d.ts @@ -0,0 +1,48 @@ +declare const resolveCwd: { + /** + Resolve the path of a module like [`require.resolve()`](https://nodejs.org/api/globals.html#globals_require_resolve) but from the current working directory. + + @param moduleId - What you would use in `require()`. + @returns The resolved module path. + @throws When the module can't be found. + + @example + ``` + import resolveCwd = require('resolve-cwd'); + + console.log(__dirname); + //=> '/Users/sindresorhus/rainbow' + + console.log(process.cwd()); + //=> '/Users/sindresorhus/unicorn' + + console.log(resolveCwd('./foo')); + //=> '/Users/sindresorhus/unicorn/foo.js' + ``` + */ + (moduleId: string): string; + + /** + Resolve the path of a module like [`require.resolve()`](https://nodejs.org/api/globals.html#globals_require_resolve) but from the current working directory. + + @param moduleId - What you would use in `require()`. + @returns The resolved module path. Returns `undefined` instead of throwing when the module can't be found. + + @example + ``` + import resolveCwd = require('resolve-cwd'); + + console.log(__dirname); + //=> '/Users/sindresorhus/rainbow' + + console.log(process.cwd()); + //=> '/Users/sindresorhus/unicorn' + + console.log(resolveCwd.silent('./foo')); + //=> '/Users/sindresorhus/unicorn/foo.js' + ``` + */ + silent(moduleId: string): string | undefined; +}; + +export = resolveCwd; diff --git a/node_modules/mathjs/examples/node_modules/resolve-cwd/index.js b/node_modules/mathjs/examples/node_modules/resolve-cwd/index.js new file mode 100644 index 0000000..82dd33c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve-cwd/index.js @@ -0,0 +1,5 @@ +'use strict'; +const resolveFrom = require('resolve-from'); + +module.exports = moduleId => resolveFrom(process.cwd(), moduleId); +module.exports.silent = moduleId => resolveFrom.silent(process.cwd(), moduleId); diff --git a/node_modules/mathjs/examples/node_modules/resolve-cwd/license b/node_modules/mathjs/examples/node_modules/resolve-cwd/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve-cwd/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/resolve-cwd/package.json b/node_modules/mathjs/examples/node_modules/resolve-cwd/package.json new file mode 100644 index 0000000..70dface --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve-cwd/package.json @@ -0,0 +1,43 @@ +{ + "name": "resolve-cwd", + "version": "3.0.0", + "description": "Resolve the path of a module like `require.resolve()` but from the current working directory", + "license": "MIT", + "repository": "sindresorhus/resolve-cwd", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "require", + "resolve", + "path", + "module", + "from", + "like", + "cwd", + "current", + "working", + "directory", + "import" + ], + "dependencies": { + "resolve-from": "^5.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/resolve-cwd/readme.md b/node_modules/mathjs/examples/node_modules/resolve-cwd/readme.md new file mode 100644 index 0000000..d9f3129 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve-cwd/readme.md @@ -0,0 +1,58 @@ +# resolve-cwd [![Build Status](https://travis-ci.org/sindresorhus/resolve-cwd.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-cwd) + +> Resolve the path of a module like [`require.resolve()`](https://nodejs.org/api/globals.html#globals_require_resolve) but from the current working directory + + +## Install + +``` +$ npm install resolve-cwd +``` + + +## Usage + +```js +const resolveCwd = require('resolve-cwd'); + +console.log(__dirname); +//=> '/Users/sindresorhus/rainbow' + +console.log(process.cwd()); +//=> '/Users/sindresorhus/unicorn' + +console.log(resolveCwd('./foo')); +//=> '/Users/sindresorhus/unicorn/foo.js' +``` + + +## API + +### resolveCwd(moduleId) + +Like `require()`, throws when the module can't be found. + +### resolveCwd.silent(moduleId) + +Returns `undefined` instead of throwing when the module can't be found. + +#### moduleId + +Type: `string` + +What you would use in `require()`. + + +## Related + +- [resolve-from](https://github.com/sindresorhus/resolve-from) - Resolve the path of a module from a given path +- [import-from](https://github.com/sindresorhus/import-from) - Import a module from a given path +- [import-cwd](https://github.com/sindresorhus/import-cwd) - Import a module from the current working directory +- [resolve-pkg](https://github.com/sindresorhus/resolve-pkg) - Resolve the path of a package regardless of it having an entry point +- [import-lazy](https://github.com/sindresorhus/import-lazy) - Import a module lazily +- [resolve-global](https://github.com/sindresorhus/resolve-global) - Resolve the path of a globally installed module + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/mathjs/examples/node_modules/resolve-from/index.d.ts b/node_modules/mathjs/examples/node_modules/resolve-from/index.d.ts new file mode 100644 index 0000000..dd5f5ef --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve-from/index.d.ts @@ -0,0 +1,31 @@ +declare const resolveFrom: { + /** + Resolve the path of a module like [`require.resolve()`](https://nodejs.org/api/globals.html#globals_require_resolve) but from a given path. + + @param fromDirectory - Directory to resolve from. + @param moduleId - What you would use in `require()`. + @returns Resolved module path. Throws when the module can't be found. + + @example + ``` + import resolveFrom = require('resolve-from'); + + // There is a file at `./foo/bar.js` + + resolveFrom('foo', './bar'); + //=> '/Users/sindresorhus/dev/test/foo/bar.js' + ``` + */ + (fromDirectory: string, moduleId: string): string; + + /** + Resolve the path of a module like [`require.resolve()`](https://nodejs.org/api/globals.html#globals_require_resolve) but from a given path. + + @param fromDirectory - Directory to resolve from. + @param moduleId - What you would use in `require()`. + @returns Resolved module path or `undefined` when the module can't be found. + */ + silent(fromDirectory: string, moduleId: string): string | undefined; +}; + +export = resolveFrom; diff --git a/node_modules/mathjs/examples/node_modules/resolve-from/index.js b/node_modules/mathjs/examples/node_modules/resolve-from/index.js new file mode 100644 index 0000000..44f291c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve-from/index.js @@ -0,0 +1,47 @@ +'use strict'; +const path = require('path'); +const Module = require('module'); +const fs = require('fs'); + +const resolveFrom = (fromDirectory, moduleId, silent) => { + if (typeof fromDirectory !== 'string') { + throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``); + } + + if (typeof moduleId !== 'string') { + throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``); + } + + try { + fromDirectory = fs.realpathSync(fromDirectory); + } catch (error) { + if (error.code === 'ENOENT') { + fromDirectory = path.resolve(fromDirectory); + } else if (silent) { + return; + } else { + throw error; + } + } + + const fromFile = path.join(fromDirectory, 'noop.js'); + + const resolveFileName = () => Module._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: Module._nodeModulePaths(fromDirectory) + }); + + if (silent) { + try { + return resolveFileName(); + } catch (error) { + return; + } + } + + return resolveFileName(); +}; + +module.exports = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId); +module.exports.silent = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId, true); diff --git a/node_modules/mathjs/examples/node_modules/resolve-from/license b/node_modules/mathjs/examples/node_modules/resolve-from/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve-from/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/resolve-from/package.json b/node_modules/mathjs/examples/node_modules/resolve-from/package.json new file mode 100644 index 0000000..733df16 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve-from/package.json @@ -0,0 +1,36 @@ +{ + "name": "resolve-from", + "version": "5.0.0", + "description": "Resolve the path of a module like `require.resolve()` but from a given path", + "license": "MIT", + "repository": "sindresorhus/resolve-from", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "require", + "resolve", + "path", + "module", + "from", + "like", + "import" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/resolve-from/readme.md b/node_modules/mathjs/examples/node_modules/resolve-from/readme.md new file mode 100644 index 0000000..fd4f46f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve-from/readme.md @@ -0,0 +1,72 @@ +# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from) + +> Resolve the path of a module like [`require.resolve()`](https://nodejs.org/api/globals.html#globals_require_resolve) but from a given path + + +## Install + +``` +$ npm install resolve-from +``` + + +## Usage + +```js +const resolveFrom = require('resolve-from'); + +// There is a file at `./foo/bar.js` + +resolveFrom('foo', './bar'); +//=> '/Users/sindresorhus/dev/test/foo/bar.js' +``` + + +## API + +### resolveFrom(fromDirectory, moduleId) + +Like `require()`, throws when the module can't be found. + +### resolveFrom.silent(fromDirectory, moduleId) + +Returns `undefined` instead of throwing when the module can't be found. + +#### fromDirectory + +Type: `string` + +Directory to resolve from. + +#### moduleId + +Type: `string` + +What you would use in `require()`. + + +## Tip + +Create a partial using a bound function if you want to resolve from the same `fromDirectory` multiple times: + +```js +const resolveFromFoo = resolveFrom.bind(null, 'foo'); + +resolveFromFoo('./bar'); +resolveFromFoo('./baz'); +``` + + +## Related + +- [resolve-cwd](https://github.com/sindresorhus/resolve-cwd) - Resolve the path of a module from the current working directory +- [import-from](https://github.com/sindresorhus/import-from) - Import a module from a given path +- [import-cwd](https://github.com/sindresorhus/import-cwd) - Import a module from the current working directory +- [resolve-pkg](https://github.com/sindresorhus/resolve-pkg) - Resolve the path of a package regardless of it having an entry point +- [import-lazy](https://github.com/sindresorhus/import-lazy) - Import a module lazily +- [resolve-global](https://github.com/sindresorhus/resolve-global) - Resolve the path of a globally installed module + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/mathjs/examples/node_modules/resolve/.editorconfig b/node_modules/mathjs/examples/node_modules/resolve/.editorconfig new file mode 100644 index 0000000..d63f0bb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/.editorconfig @@ -0,0 +1,37 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 200 + +[*.js] +block_comment_start = /* +block_comment = * +block_comment_end = */ + +[*.yml] +indent_size = 1 + +[package.json] +indent_style = tab + +[lib/core.json] +indent_style = tab + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[{*.json,Makefile}] +max_line_length = off + +[test/{dotdot,resolver,module_dir,multirepo,node_path,pathfilter,precedence}/**/*] +indent_style = off +indent_size = off +max_line_length = off +insert_final_newline = off diff --git a/node_modules/mathjs/examples/node_modules/resolve/.eslintrc b/node_modules/mathjs/examples/node_modules/resolve/.eslintrc new file mode 100644 index 0000000..ce1be6e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/.eslintrc @@ -0,0 +1,65 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "indent": [2, 4], + "strict": 0, + "complexity": 0, + "consistent-return": 0, + "curly": 0, + "dot-notation": [2, { "allowKeywords": true }], + "func-name-matching": 0, + "func-style": 0, + "global-require": 1, + "id-length": [2, { "min": 1, "max": 30 }], + "max-lines": [2, 350], + "max-lines-per-function": 0, + "max-nested-callbacks": 0, + "max-params": 0, + "max-statements-per-line": [2, { "max": 2 }], + "max-statements": 0, + "no-magic-numbers": 0, + "no-shadow": 0, + "no-use-before-define": 0, + "sort-keys": 0, + }, + "overrides": [ + { + "files": "bin/**", + "rules": { + "no-process-exit": "off", + }, + }, + { + "files": "example/**", + "rules": { + "no-console": 0, + }, + }, + { + "files": "test/resolver/nested_symlinks/mylib/*.js", + "rules": { + "no-throw-literal": 0, + }, + }, + { + "files": "test/**", + "parserOptions": { + "ecmaVersion": 5, + "allowReserved": false, + }, + "rules": { + "dot-notation": [2, { "allowPattern": "throws" }], + "max-lines": 0, + "max-lines-per-function": 0, + "no-unused-vars": [2, { "vars": "all", "args": "none" }], + }, + }, + ], + + "ignorePatterns": [ + "./test/resolver/malformed_package_json/package.json", + ], +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/.github/FUNDING.yml b/node_modules/mathjs/examples/node_modules/resolve/.github/FUNDING.yml new file mode 100644 index 0000000..d9c0595 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/resolve +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/mathjs/examples/node_modules/resolve/LICENSE b/node_modules/mathjs/examples/node_modules/resolve/LICENSE new file mode 100644 index 0000000..ff4fce2 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012 James Halliday + +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. diff --git a/node_modules/mathjs/examples/node_modules/resolve/SECURITY.md b/node_modules/mathjs/examples/node_modules/resolve/SECURITY.md new file mode 100644 index 0000000..82e4285 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. diff --git a/node_modules/mathjs/examples/node_modules/resolve/appveyor.yml b/node_modules/mathjs/examples/node_modules/resolve/appveyor.yml new file mode 100644 index 0000000..f74b7b8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/appveyor.yml @@ -0,0 +1,76 @@ +version: 1.0.{build} +skip_branch_with_pr: true +build: off + +environment: + matrix: + #- nodejs_version: "17" + - nodejs_version: "16" + - nodejs_version: "15" + - nodejs_version: "14" + - nodejs_version: "13" + - nodejs_version: "12" + - nodejs_version: "11" + - nodejs_version: "10" + - nodejs_version: "9" + - nodejs_version: "8" + - nodejs_version: "7" + - nodejs_version: "6" + - nodejs_version: "5" + - nodejs_version: "4" + - nodejs_version: "3" + - nodejs_version: "2" + - nodejs_version: "1" + - nodejs_version: "0.12" + - nodejs_version: "0.10" + - nodejs_version: "0.8" + - nodejs_version: "0.6" +matrix: + # fast_finish: true + allow_failures: + - nodejs_version: "0.8" + # platform: x86 # x64 has started failing on the registry side, around early November 2020 + - nodejs_version: "0.6" + +platform: + - x86 + - x64 + +# Install scripts. (runs after repo cloning) +install: + # Fix symlinks in working copy (see https://github.com/appveyor/ci/issues/650#issuecomment-186592582) / https://github.com/charleskorn/batect/commit/d08986802ec43086902958c4ee7e57ff3e71dbef + - git config core.symlinks true + - git reset --hard + # Get the latest stable version of Node.js or io.js + - ps: if ($env:nodejs_version -ne '0.6') { Install-Product node $env:nodejs_version $env:platform } + - ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version) $env:platform + - IF %nodejs_version% EQU 0.6 npm config set strict-ssl false && npm -g install npm@1.3 + - IF %nodejs_version% EQU 0.8 npm config set strict-ssl false && npm -g install npm@1.4.28 && npm install -g npm@4.5 + - IF %nodejs_version% EQU 1 npm -g install npm@2.9 + - IF %nodejs_version% EQU 2 npm -g install npm@4 + - IF %nodejs_version% EQU 3 npm -g install npm@4 + - IF %nodejs_version% EQU 4 npm -g install npm@5.3 + - IF %nodejs_version% EQU 5 npm -g install npm@5.3 + - IF %nodejs_version% EQU 6 npm -g install npm@6.9 + - IF %nodejs_version% EQU 7 npm -g install npm@6 + - IF %nodejs_version% EQU 8 npm -g install npm@6 + - IF %nodejs_version% EQU 9 npm -g install npm@6.9 + - IF %nodejs_version% EQU 10 npm -g install npm@7 + - IF %nodejs_version% EQU 11 npm -g install npm@7 + - IF %nodejs_version% EQU 12 npm -g install npm@7 + - IF %nodejs_version% EQU 13 npm -g install npm@7 + - IF %nodejs_version% EQU 14 npm -g install npm@7 + - IF %nodejs_version% EQU 15 npm -g install npm@7 + - IF %nodejs_version% EQU 16 npm -g install npm@7 + - set PATH=%APPDATA%\npm;%PATH% + #- IF %nodejs_version% NEQ 0.6 AND %nodejs_version% NEQ 0.8 npm -g install npm + # install modules + - npm install + +# Post-install test scripts. +test_script: + # Output useful info for debugging. + - node --version + - npm --version + # run tests + - npm run tests-only diff --git a/node_modules/mathjs/examples/node_modules/resolve/async.js b/node_modules/mathjs/examples/node_modules/resolve/async.js new file mode 100644 index 0000000..f38c581 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/async.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/async'); diff --git a/node_modules/mathjs/examples/node_modules/resolve/bin/resolve b/node_modules/mathjs/examples/node_modules/resolve/bin/resolve new file mode 100644 index 0000000..5ee329a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/bin/resolve @@ -0,0 +1,50 @@ +#!/usr/bin/env node + +'use strict'; + +var path = require('path'); +var fs = require('fs'); + +if ( + String(process.env.npm_lifecycle_script).slice(0, 8) !== 'resolve ' + && ( + !process.argv + || process.argv.length < 2 + || (process.argv[1] !== __filename && fs.statSync(process.argv[1]).ino !== fs.statSync(__filename).ino) + || (process.env._ && path.resolve(process.env._) !== __filename) + ) +) { + console.error('Error: `resolve` must be run directly as an executable'); + process.exit(1); +} + +var supportsPreserveSymlinkFlag = require('supports-preserve-symlinks-flag'); + +var preserveSymlinks = false; +for (var i = 2; i < process.argv.length; i += 1) { + if (process.argv[i].slice(0, 2) === '--') { + if (supportsPreserveSymlinkFlag && process.argv[i] === '--preserve-symlinks') { + preserveSymlinks = true; + } else if (process.argv[i].length > 2) { + console.error('Unknown argument ' + process.argv[i].replace(/[=].*$/, '')); + process.exit(2); + } + process.argv.splice(i, 1); + i -= 1; + if (process.argv[i] === '--') { break; } // eslint-disable-line no-restricted-syntax + } +} + +if (process.argv.length < 3) { + console.error('Error: `resolve` expects a specifier'); + process.exit(2); +} + +var resolve = require('../'); + +var result = resolve.sync(process.argv[2], { + basedir: process.cwd(), + preserveSymlinks: preserveSymlinks +}); + +console.log(result); diff --git a/node_modules/mathjs/examples/node_modules/resolve/example/async.js b/node_modules/mathjs/examples/node_modules/resolve/example/async.js new file mode 100644 index 0000000..20e65dc --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/example/async.js @@ -0,0 +1,5 @@ +var resolve = require('../'); +resolve('tap', { basedir: __dirname }, function (err, res) { + if (err) console.error(err); + else console.log(res); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/example/sync.js b/node_modules/mathjs/examples/node_modules/resolve/example/sync.js new file mode 100644 index 0000000..54b2cc1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/example/sync.js @@ -0,0 +1,3 @@ +var resolve = require('../'); +var res = resolve.sync('tap', { basedir: __dirname }); +console.log(res); diff --git a/node_modules/mathjs/examples/node_modules/resolve/index.js b/node_modules/mathjs/examples/node_modules/resolve/index.js new file mode 100644 index 0000000..125d814 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/index.js @@ -0,0 +1,6 @@ +var async = require('./lib/async'); +async.core = require('./lib/core'); +async.isCore = require('./lib/is-core'); +async.sync = require('./lib/sync'); + +module.exports = async; diff --git a/node_modules/mathjs/examples/node_modules/resolve/lib/async.js b/node_modules/mathjs/examples/node_modules/resolve/lib/async.js new file mode 100644 index 0000000..2b0f0f3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/lib/async.js @@ -0,0 +1,329 @@ +var fs = require('fs'); +var getHomedir = require('./homedir'); +var path = require('path'); +var caller = require('./caller'); +var nodeModulesPaths = require('./node-modules-paths'); +var normalizeOptions = require('./normalize-options'); +var isCore = require('is-core-module'); + +var realpathFS = fs.realpath && typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath; + +var homedir = getHomedir(); +var defaultPaths = function () { + return [ + path.join(homedir, '.node_modules'), + path.join(homedir, '.node_libraries') + ]; +}; + +var defaultIsFile = function isFile(file, cb) { + fs.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultIsDir = function isDirectory(dir, cb) { + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultRealpath = function realpath(x, cb) { + realpathFS(x, function (realpathErr, realPath) { + if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr); + else cb(null, realpathErr ? x : realPath); + }); +}; + +var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) { + if (opts && opts.preserveSymlinks === false) { + realpath(x, cb); + } else { + cb(null, x); + } +}; + +var defaultReadPackage = function defaultReadPackage(readFile, pkgfile, cb) { + readFile(pkgfile, function (readFileErr, body) { + if (readFileErr) cb(readFileErr); + else { + try { + var pkg = JSON.parse(body); + cb(null, pkg); + } catch (jsonErr) { + cb(null); + } + } + }); +}; + +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path.join(dirs[i], x); + } + return dirs; +}; + +module.exports = function resolve(x, options, callback) { + var cb = callback; + var opts = options; + if (typeof options === 'function') { + cb = opts; + opts = {}; + } + if (typeof x !== 'string') { + var err = new TypeError('Path must be a string.'); + return process.nextTick(function () { + cb(err); + }); + } + + opts = normalizeOptions(x, opts); + + var isFile = opts.isFile || defaultIsFile; + var isDirectory = opts.isDirectory || defaultIsDir; + var readFile = opts.readFile || fs.readFile; + var realpath = opts.realpath || defaultRealpath; + var readPackage = opts.readPackage || defaultReadPackage; + if (opts.readFile && opts.readPackage) { + var conflictErr = new TypeError('`readFile` and `readPackage` are mutually exclusive.'); + return process.nextTick(function () { + cb(conflictErr); + }); + } + var packageIterator = opts.packageIterator; + + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; + + opts.paths = opts.paths || defaultPaths(); + + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = path.resolve(basedir); + + maybeRealpath( + realpath, + absoluteStart, + opts, + function (err, realStart) { + if (err) cb(err); + else init(realStart); + } + ); + + var res; + function init(basedir) { + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + res = path.resolve(basedir, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + if ((/\/$/).test(x) && res === basedir) { + loadAsDirectory(res, opts.package, onfile); + } else loadAsFile(res, opts.package, onfile); + } else if (includeCoreModules && isCore(x)) { + return cb(null, x); + } else loadNodeModules(x, basedir, function (err, n, pkg) { + if (err) cb(err); + else if (n) { + return maybeRealpath(realpath, n, opts, function (err, realN) { + if (err) { + cb(err); + } else { + cb(null, realN, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function onfile(err, m, pkg) { + if (err) cb(err); + else if (m) cb(null, m, pkg); + else loadAsDirectory(res, function (err, d, pkg) { + if (err) cb(err); + else if (d) { + maybeRealpath(realpath, d, opts, function (err, realD) { + if (err) { + cb(err); + } else { + cb(null, realD, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function loadAsFile(x, thePackage, callback) { + var loadAsFilePackage = thePackage; + var cb = callback; + if (typeof loadAsFilePackage === 'function') { + cb = loadAsFilePackage; + loadAsFilePackage = undefined; + } + + var exts = [''].concat(extensions); + load(exts, x, loadAsFilePackage); + + function load(exts, x, loadPackage) { + if (exts.length === 0) return cb(null, undefined, loadPackage); + var file = x + exts[0]; + + var pkg = loadPackage; + if (pkg) onpkg(null, pkg); + else loadpkg(path.dirname(file), onpkg); + + function onpkg(err, pkg_, dir) { + pkg = pkg_; + if (err) return cb(err); + if (dir && pkg && opts.pathFilter) { + var rfile = path.relative(dir, file); + var rel = rfile.slice(0, rfile.length - exts[0].length); + var r = opts.pathFilter(pkg, x, rel); + if (r) return load( + [''].concat(extensions.slice()), + path.resolve(dir, r), + pkg + ); + } + isFile(file, onex); + } + function onex(err, ex) { + if (err) return cb(err); + if (ex) return cb(null, file, pkg); + load(exts.slice(1), x, pkg); + } + } + } + + function loadpkg(dir, cb) { + if (dir === '' || dir === '/') return cb(null); + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return cb(null); + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); + + maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return loadpkg(path.dirname(dir), cb); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + // on err, ex is false + if (!ex) return loadpkg(path.dirname(dir), cb); + + readPackage(readFile, pkgfile, function (err, pkgParam) { + if (err) cb(err); + + var pkg = pkgParam; + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + cb(null, pkg, dir); + }); + }); + }); + } + + function loadAsDirectory(x, loadAsDirectoryPackage, callback) { + var cb = callback; + var fpkg = loadAsDirectoryPackage; + if (typeof fpkg === 'function') { + cb = fpkg; + fpkg = opts.package; + } + + maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return cb(unwrapErr); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + if (err) return cb(err); + if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); + + readPackage(readFile, pkgfile, function (err, pkgParam) { + if (err) return cb(err); + + var pkg = pkgParam; + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + return cb(mainError); + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb); + + var dir = path.resolve(x, pkg.main); + loadAsDirectory(dir, pkg, function (err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + loadAsFile(path.join(x, 'index'), pkg, cb); + }); + }); + return; + } + + loadAsFile(path.join(x, '/index'), pkg, cb); + }); + }); + }); + } + + function processDirs(cb, dirs) { + if (dirs.length === 0) return cb(null, undefined); + var dir = dirs[0]; + + isDirectory(path.dirname(dir), isdir); + + function isdir(err, isdir) { + if (err) return cb(err); + if (!isdir) return processDirs(cb, dirs.slice(1)); + loadAsFile(dir, opts.package, onfile); + } + + function onfile(err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + loadAsDirectory(dir, opts.package, ondir); + } + + function ondir(err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + processDirs(cb, dirs.slice(1)); + } + } + function loadNodeModules(x, start, cb) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + processDirs( + cb, + packageIterator ? packageIterator(x, start, thunk, opts) : thunk() + ); + } +}; diff --git a/node_modules/mathjs/examples/node_modules/resolve/lib/caller.js b/node_modules/mathjs/examples/node_modules/resolve/lib/caller.js new file mode 100644 index 0000000..b14a280 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/lib/caller.js @@ -0,0 +1,8 @@ +module.exports = function () { + // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + var origPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function (_, stack) { return stack; }; + var stack = (new Error()).stack; + Error.prepareStackTrace = origPrepareStackTrace; + return stack[2].getFileName(); +}; diff --git a/node_modules/mathjs/examples/node_modules/resolve/lib/core.js b/node_modules/mathjs/examples/node_modules/resolve/lib/core.js new file mode 100644 index 0000000..ecc5b2e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/lib/core.js @@ -0,0 +1,52 @@ +var current = (process.versions && process.versions.node && process.versions.node.split('.')) || []; + +function specifierIncluded(specifier) { + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + + for (var i = 0; i < 3; ++i) { + var cur = parseInt(current[i] || 0, 10); + var ver = parseInt(versionParts[i] || 0, 10); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } else if (op === '>=') { + return cur >= ver; + } + return false; + } + return op === '>='; +} + +function matchesRange(range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { return false; } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(specifiers[i])) { return false; } + } + return true; +} + +function versionIncluded(specifierValue) { + if (typeof specifierValue === 'boolean') { return specifierValue; } + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(specifierValue[i])) { return true; } + } + return false; + } + return matchesRange(specifierValue); +} + +var data = require('./core.json'); + +var core = {}; +for (var mod in data) { // eslint-disable-line no-restricted-syntax + if (Object.prototype.hasOwnProperty.call(data, mod)) { + core[mod] = versionIncluded(data[mod]); + } +} +module.exports = core; diff --git a/node_modules/mathjs/examples/node_modules/resolve/lib/core.json b/node_modules/mathjs/examples/node_modules/resolve/lib/core.json new file mode 100644 index 0000000..d275294 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/lib/core.json @@ -0,0 +1,152 @@ +{ + "assert": true, + "node:assert": [">= 14.18 && < 15", ">= 16"], + "assert/strict": ">= 15", + "node:assert/strict": ">= 16", + "async_hooks": ">= 8", + "node:async_hooks": [">= 14.18 && < 15", ">= 16"], + "buffer_ieee754": ">= 0.5 && < 0.9.7", + "buffer": true, + "node:buffer": [">= 14.18 && < 15", ">= 16"], + "child_process": true, + "node:child_process": [">= 14.18 && < 15", ">= 16"], + "cluster": ">= 0.5", + "node:cluster": [">= 14.18 && < 15", ">= 16"], + "console": true, + "node:console": [">= 14.18 && < 15", ">= 16"], + "constants": true, + "node:constants": [">= 14.18 && < 15", ">= 16"], + "crypto": true, + "node:crypto": [">= 14.18 && < 15", ">= 16"], + "_debug_agent": ">= 1 && < 8", + "_debugger": "< 8", + "dgram": true, + "node:dgram": [">= 14.18 && < 15", ">= 16"], + "diagnostics_channel": [">= 14.17 && < 15", ">= 15.1"], + "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"], + "dns": true, + "node:dns": [">= 14.18 && < 15", ">= 16"], + "dns/promises": ">= 15", + "node:dns/promises": ">= 16", + "domain": ">= 0.7.12", + "node:domain": [">= 14.18 && < 15", ">= 16"], + "events": true, + "node:events": [">= 14.18 && < 15", ">= 16"], + "freelist": "< 6", + "fs": true, + "node:fs": [">= 14.18 && < 15", ">= 16"], + "fs/promises": [">= 10 && < 10.1", ">= 14"], + "node:fs/promises": [">= 14.18 && < 15", ">= 16"], + "_http_agent": ">= 0.11.1", + "node:_http_agent": [">= 14.18 && < 15", ">= 16"], + "_http_client": ">= 0.11.1", + "node:_http_client": [">= 14.18 && < 15", ">= 16"], + "_http_common": ">= 0.11.1", + "node:_http_common": [">= 14.18 && < 15", ">= 16"], + "_http_incoming": ">= 0.11.1", + "node:_http_incoming": [">= 14.18 && < 15", ">= 16"], + "_http_outgoing": ">= 0.11.1", + "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"], + "_http_server": ">= 0.11.1", + "node:_http_server": [">= 14.18 && < 15", ">= 16"], + "http": true, + "node:http": [">= 14.18 && < 15", ">= 16"], + "http2": ">= 8.8", + "node:http2": [">= 14.18 && < 15", ">= 16"], + "https": true, + "node:https": [">= 14.18 && < 15", ">= 16"], + "inspector": ">= 8", + "node:inspector": [">= 14.18 && < 15", ">= 16"], + "_linklist": "< 8", + "module": true, + "node:module": [">= 14.18 && < 15", ">= 16"], + "net": true, + "node:net": [">= 14.18 && < 15", ">= 16"], + "node-inspect/lib/_inspect": ">= 7.6 && < 12", + "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12", + "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12", + "os": true, + "node:os": [">= 14.18 && < 15", ">= 16"], + "path": true, + "node:path": [">= 14.18 && < 15", ">= 16"], + "path/posix": ">= 15.3", + "node:path/posix": ">= 16", + "path/win32": ">= 15.3", + "node:path/win32": ">= 16", + "perf_hooks": ">= 8.5", + "node:perf_hooks": [">= 14.18 && < 15", ">= 16"], + "process": ">= 1", + "node:process": [">= 14.18 && < 15", ">= 16"], + "punycode": ">= 0.5", + "node:punycode": [">= 14.18 && < 15", ">= 16"], + "querystring": true, + "node:querystring": [">= 14.18 && < 15", ">= 16"], + "readline": true, + "node:readline": [">= 14.18 && < 15", ">= 16"], + "readline/promises": ">= 17", + "node:readline/promises": ">= 17", + "repl": true, + "node:repl": [">= 14.18 && < 15", ">= 16"], + "smalloc": ">= 0.11.5 && < 3", + "_stream_duplex": ">= 0.9.4", + "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"], + "_stream_transform": ">= 0.9.4", + "node:_stream_transform": [">= 14.18 && < 15", ">= 16"], + "_stream_wrap": ">= 1.4.1", + "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"], + "_stream_passthrough": ">= 0.9.4", + "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"], + "_stream_readable": ">= 0.9.4", + "node:_stream_readable": [">= 14.18 && < 15", ">= 16"], + "_stream_writable": ">= 0.9.4", + "node:_stream_writable": [">= 14.18 && < 15", ">= 16"], + "stream": true, + "node:stream": [">= 14.18 && < 15", ">= 16"], + "stream/consumers": ">= 16.7", + "node:stream/consumers": ">= 16.7", + "stream/promises": ">= 15", + "node:stream/promises": ">= 16", + "stream/web": ">= 16.5", + "node:stream/web": ">= 16.5", + "string_decoder": true, + "node:string_decoder": [">= 14.18 && < 15", ">= 16"], + "sys": [">= 0.4 && < 0.7", ">= 0.8"], + "node:sys": [">= 14.18 && < 15", ">= 16"], + "timers": true, + "node:timers": [">= 14.18 && < 15", ">= 16"], + "timers/promises": ">= 15", + "node:timers/promises": ">= 16", + "_tls_common": ">= 0.11.13", + "node:_tls_common": [">= 14.18 && < 15", ">= 16"], + "_tls_legacy": ">= 0.11.3 && < 10", + "_tls_wrap": ">= 0.11.3", + "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"], + "tls": true, + "node:tls": [">= 14.18 && < 15", ">= 16"], + "trace_events": ">= 10", + "node:trace_events": [">= 14.18 && < 15", ">= 16"], + "tty": true, + "node:tty": [">= 14.18 && < 15", ">= 16"], + "url": true, + "node:url": [">= 14.18 && < 15", ">= 16"], + "util": true, + "node:util": [">= 14.18 && < 15", ">= 16"], + "util/types": ">= 15.3", + "node:util/types": ">= 16", + "v8/tools/arguments": ">= 10 && < 12", + "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8": ">= 1", + "node:v8": [">= 14.18 && < 15", ">= 16"], + "vm": true, + "node:vm": [">= 14.18 && < 15", ">= 16"], + "wasi": ">= 13.4 && < 13.5", + "worker_threads": ">= 11.7", + "node:worker_threads": [">= 14.18 && < 15", ">= 16"], + "zlib": ">= 0.5", + "node:zlib": [">= 14.18 && < 15", ">= 16"] +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/lib/homedir.js b/node_modules/mathjs/examples/node_modules/resolve/lib/homedir.js new file mode 100644 index 0000000..5ffdf73 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/lib/homedir.js @@ -0,0 +1,24 @@ +'use strict'; + +var os = require('os'); + +// adapted from https://github.com/sindresorhus/os-homedir/blob/11e089f4754db38bb535e5a8416320c4446e8cfd/index.js + +module.exports = os.homedir || function homedir() { + var home = process.env.HOME; + var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME; + + if (process.platform === 'win32') { + return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null; + } + + if (process.platform === 'darwin') { + return home || (user ? '/Users/' + user : null); + } + + if (process.platform === 'linux') { + return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); // eslint-disable-line no-extra-parens + } + + return home || null; +}; diff --git a/node_modules/mathjs/examples/node_modules/resolve/lib/is-core.js b/node_modules/mathjs/examples/node_modules/resolve/lib/is-core.js new file mode 100644 index 0000000..537f5c7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/lib/is-core.js @@ -0,0 +1,5 @@ +var isCoreModule = require('is-core-module'); + +module.exports = function isCore(x) { + return isCoreModule(x); +}; diff --git a/node_modules/mathjs/examples/node_modules/resolve/lib/node-modules-paths.js b/node_modules/mathjs/examples/node_modules/resolve/lib/node-modules-paths.js new file mode 100644 index 0000000..1cff010 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/lib/node-modules-paths.js @@ -0,0 +1,42 @@ +var path = require('path'); +var parse = path.parse || require('path-parse'); // eslint-disable-line global-require + +var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { + var prefix = '/'; + if ((/^([A-Za-z]:)/).test(absoluteStart)) { + prefix = ''; + } else if ((/^\\\\/).test(absoluteStart)) { + prefix = '\\\\'; + } + + var paths = [absoluteStart]; + var parsed = parse(absoluteStart); + while (parsed.dir !== paths[paths.length - 1]) { + paths.push(parsed.dir); + parsed = parse(parsed.dir); + } + + return paths.reduce(function (dirs, aPath) { + return dirs.concat(modules.map(function (moduleDir) { + return path.resolve(prefix, aPath, moduleDir); + })); + }, []); +}; + +module.exports = function nodeModulesPaths(start, opts, request) { + var modules = opts && opts.moduleDirectory + ? [].concat(opts.moduleDirectory) + : ['node_modules']; + + if (opts && typeof opts.paths === 'function') { + return opts.paths( + request, + start, + function () { return getNodeModulesDirs(start, modules); }, + opts + ); + } + + var dirs = getNodeModulesDirs(start, modules); + return opts && opts.paths ? dirs.concat(opts.paths) : dirs; +}; diff --git a/node_modules/mathjs/examples/node_modules/resolve/lib/normalize-options.js b/node_modules/mathjs/examples/node_modules/resolve/lib/normalize-options.js new file mode 100644 index 0000000..4b56904 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/lib/normalize-options.js @@ -0,0 +1,10 @@ +module.exports = function (x, opts) { + /** + * This file is purposefully a passthrough. It's expected that third-party + * environments will override it at runtime in order to inject special logic + * into `resolve` (by manipulating the options). One such example is the PnP + * code path in Yarn. + */ + + return opts || {}; +}; diff --git a/node_modules/mathjs/examples/node_modules/resolve/lib/sync.js b/node_modules/mathjs/examples/node_modules/resolve/lib/sync.js new file mode 100644 index 0000000..3246989 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/lib/sync.js @@ -0,0 +1,208 @@ +var isCore = require('is-core-module'); +var fs = require('fs'); +var path = require('path'); +var getHomedir = require('./homedir'); +var caller = require('./caller'); +var nodeModulesPaths = require('./node-modules-paths'); +var normalizeOptions = require('./normalize-options'); + +var realpathFS = fs.realpathSync && typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync; + +var homedir = getHomedir(); +var defaultPaths = function () { + return [ + path.join(homedir, '.node_modules'), + path.join(homedir, '.node_libraries') + ]; +}; + +var defaultIsFile = function isFile(file) { + try { + var stat = fs.statSync(file, { throwIfNoEntry: false }); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return !!stat && (stat.isFile() || stat.isFIFO()); +}; + +var defaultIsDir = function isDirectory(dir) { + try { + var stat = fs.statSync(dir, { throwIfNoEntry: false }); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return !!stat && stat.isDirectory(); +}; + +var defaultRealpathSync = function realpathSync(x) { + try { + return realpathFS(x); + } catch (realpathErr) { + if (realpathErr.code !== 'ENOENT') { + throw realpathErr; + } + } + return x; +}; + +var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) { + if (opts && opts.preserveSymlinks === false) { + return realpathSync(x); + } + return x; +}; + +var defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) { + var body = readFileSync(pkgfile); + try { + var pkg = JSON.parse(body); + return pkg; + } catch (jsonErr) {} +}; + +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path.join(dirs[i], x); + } + return dirs; +}; + +module.exports = function resolveSync(x, options) { + if (typeof x !== 'string') { + throw new TypeError('Path must be a string.'); + } + var opts = normalizeOptions(x, options); + + var isFile = opts.isFile || defaultIsFile; + var readFileSync = opts.readFileSync || fs.readFileSync; + var isDirectory = opts.isDirectory || defaultIsDir; + var realpathSync = opts.realpathSync || defaultRealpathSync; + var readPackageSync = opts.readPackageSync || defaultReadPackageSync; + if (opts.readFileSync && opts.readPackageSync) { + throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.'); + } + var packageIterator = opts.packageIterator; + + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; + + opts.paths = opts.paths || defaultPaths(); + + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = maybeRealpathSync(realpathSync, path.resolve(basedir), opts); + + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + var res = path.resolve(absoluteStart, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + var m = loadAsFileSync(res) || loadAsDirectorySync(res); + if (m) return maybeRealpathSync(realpathSync, m, opts); + } else if (includeCoreModules && isCore(x)) { + return x; + } else { + var n = loadNodeModulesSync(x, absoluteStart); + if (n) return maybeRealpathSync(realpathSync, n, opts); + } + + var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + err.code = 'MODULE_NOT_FOUND'; + throw err; + + function loadAsFileSync(x) { + var pkg = loadpkg(path.dirname(x)); + + if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { + var rfile = path.relative(pkg.dir, x); + var r = opts.pathFilter(pkg.pkg, x, rfile); + if (r) { + x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign + } + } + + if (isFile(x)) { + return x; + } + + for (var i = 0; i < extensions.length; i++) { + var file = x + extensions[i]; + if (isFile(file)) { + return file; + } + } + } + + function loadpkg(dir) { + if (dir === '' || dir === '/') return; + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return; + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; + + var pkgfile = path.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json'); + + if (!isFile(pkgfile)) { + return loadpkg(path.dirname(dir)); + } + + var pkg = readPackageSync(readFileSync, pkgfile); + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment + } + + return { pkg: pkg, dir: dir }; + } + + function loadAsDirectorySync(x) { + var pkgfile = path.join(maybeRealpathSync(realpathSync, x, opts), '/package.json'); + if (isFile(pkgfile)) { + try { + var pkg = readPackageSync(readFileSync, pkgfile); + } catch (e) {} + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + throw mainError; + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + try { + var m = loadAsFileSync(path.resolve(x, pkg.main)); + if (m) return m; + var n = loadAsDirectorySync(path.resolve(x, pkg.main)); + if (n) return n; + } catch (e) {} + } + } + + return loadAsFileSync(path.join(x, '/index')); + } + + function loadNodeModulesSync(x, start) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk(); + + for (var i = 0; i < dirs.length; i++) { + var dir = dirs[i]; + if (isDirectory(path.dirname(dir))) { + var m = loadAsFileSync(dir); + if (m) return m; + var n = loadAsDirectorySync(dir); + if (n) return n; + } + } + } +}; diff --git a/node_modules/mathjs/examples/node_modules/resolve/package.json b/node_modules/mathjs/examples/node_modules/resolve/package.json new file mode 100644 index 0000000..5cad3f3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/package.json @@ -0,0 +1,62 @@ +{ + "name": "resolve", + "description": "resolve like require.resolve() on behalf of files asynchronously and synchronously", + "version": "1.22.0", + "repository": { + "type": "git", + "url": "git://github.com/browserify/resolve.git" + }, + "bin": { + "resolve": "./bin/resolve" + }, + "main": "index.js", + "keywords": [ + "resolve", + "require", + "node", + "module" + ], + "scripts": { + "prepublishOnly": "safe-publish-latest && cp node_modules/is-core-module/core.json ./lib/ ||:", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs --no-eslintrc -c .eslintrc . 'bin/**'", + "pretests-only": "cd ./test/resolver/nested_symlinks && node mylib/sync && node mylib/async", + "tests-only": "tape test/*.js", + "pretest": "npm run lint", + "test": "npm run --silent tests-only", + "posttest": "npm run test:multirepo && aud --production", + "test:multirepo": "cd ./test/resolver/multirepo && npm install && npm test" + }, + "devDependencies": { + "@ljharb/eslint-config": "^20.2.0", + "array.prototype.map": "^1.0.4", + "aud": "^2.0.0", + "copy-dir": "^1.3.0", + "eclint": "^2.8.1", + "eslint": "^8.7.0", + "in-publish": "^2.0.1", + "mkdirp": "^0.5.5", + "mv": "^2.1.1", + "object-keys": "^1.1.1", + "rimraf": "^2.7.1", + "safe-publish-latest": "^2.0.0", + "tap": "0.4.13", + "tape": "^5.4.1", + "tmp": "^0.0.31" + }, + "license": "MIT", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "dependencies": { + "is-core-module": "^2.8.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/readme.markdown b/node_modules/mathjs/examples/node_modules/resolve/readme.markdown new file mode 100644 index 0000000..ad34d60 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/readme.markdown @@ -0,0 +1,301 @@ +# resolve [![Version Badge][2]][1] + +implements the [node `require.resolve()` algorithm](https://nodejs.org/api/modules.html#modules_all_together) such that you can `require.resolve()` on behalf of a file asynchronously and synchronously + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +# example + +asynchronously resolve: + +```js +var resolve = require('resolve/async'); // or, require('resolve') +resolve('tap', { basedir: __dirname }, function (err, res) { + if (err) console.error(err); + else console.log(res); +}); +``` + +``` +$ node example/async.js +/home/substack/projects/node-resolve/node_modules/tap/lib/main.js +``` + +synchronously resolve: + +```js +var resolve = require('resolve/sync'); // or, `require('resolve').sync +var res = resolve('tap', { basedir: __dirname }); +console.log(res); +``` + +``` +$ node example/sync.js +/home/substack/projects/node-resolve/node_modules/tap/lib/main.js +``` + +# methods + +```js +var resolve = require('resolve'); +var async = require('resolve/async'); +var sync = require('resolve/sync'); +``` + +For both the synchronous and asynchronous methods, errors may have any of the following `err.code` values: + +- `MODULE_NOT_FOUND`: the given path string (`id`) could not be resolved to a module +- `INVALID_BASEDIR`: the specified `opts.basedir` doesn't exist, or is not a directory +- `INVALID_PACKAGE_MAIN`: a `package.json` was encountered with an invalid `main` property (eg. not a string) + +## resolve(id, opts={}, cb) + +Asynchronously resolve the module path string `id` into `cb(err, res [, pkg])`, where `pkg` (if defined) is the data from `package.json`. + +options are: + +* opts.basedir - directory to begin resolving from + +* opts.package - `package.json` data applicable to the module being loaded + +* opts.extensions - array of file extensions to search in order + +* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search + +* opts.readFile - how to read files asynchronously + +* opts.isFile - function to asynchronously test whether a file exists + +* opts.isDirectory - function to asynchronously test whether a file exists and is a directory + +* opts.realpath - function to asynchronously resolve a potential symlink to its real path + +* `opts.readPackage(readFile, pkgfile, cb)` - function to asynchronously read and parse a package.json file + * readFile - the passed `opts.readFile` or `fs.readFile` if not specified + * pkgfile - path to package.json + * cb - callback + +* `opts.packageFilter(pkg, pkgfile, dir)` - transform the parsed package.json contents before looking at the "main" field + * pkg - package data + * pkgfile - path to package.json + * dir - directory that contains package.json + +* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package + * pkg - package data + * path - the path being resolved + * relativePath - the path relative from the package.json location + * returns - a relative path that will be joined from the package.json location + +* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this) + + For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function + * request - the import specifier being resolved + * start - lookup path + * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this) + * request - the import specifier being resolved + * start - lookup path + * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"` + +* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving. +This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag. +**Note:** this property is currently `true` by default but it will be changed to +`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*. + +default `opts` values: + +```js +{ + paths: [], + basedir: __dirname, + extensions: ['.js'], + includeCoreModules: true, + readFile: fs.readFile, + isFile: function isFile(file, cb) { + fs.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }, + isDirectory: function isDirectory(dir, cb) { + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }, + realpath: function realpath(file, cb) { + var realpath = typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath; + realpath(file, function (realPathErr, realPath) { + if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr); + else cb(null, realPathErr ? file : realPath); + }); + }, + readPackage: function defaultReadPackage(readFile, pkgfile, cb) { + readFile(pkgfile, function (readFileErr, body) { + if (readFileErr) cb(readFileErr); + else { + try { + var pkg = JSON.parse(body); + cb(null, pkg); + } catch (jsonErr) { + cb(null); + } + } + }); + }, + moduleDirectory: 'node_modules', + preserveSymlinks: true +} +``` + +## resolve.sync(id, opts) + +Synchronously resolve the module path string `id`, returning the result and +throwing an error when `id` can't be resolved. + +options are: + +* opts.basedir - directory to begin resolving from + +* opts.extensions - array of file extensions to search in order + +* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search + +* opts.readFileSync - how to read files synchronously + +* opts.isFile - function to synchronously test whether a file exists + +* opts.isDirectory - function to synchronously test whether a file exists and is a directory + +* opts.realpathSync - function to synchronously resolve a potential symlink to its real path + +* `opts.readPackageSync(readFileSync, pkgfile)` - function to synchronously read and parse a package.json file + * readFileSync - the passed `opts.readFileSync` or `fs.readFileSync` if not specified + * pkgfile - path to package.json + +* `opts.packageFilter(pkg, dir)` - transform the parsed package.json contents before looking at the "main" field + * pkg - package data + * dir - directory that contains package.json (Note: the second argument will change to "pkgfile" in v2) + +* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package + * pkg - package data + * path - the path being resolved + * relativePath - the path relative from the package.json location + * returns - a relative path that will be joined from the package.json location + +* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this) + + For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function + * request - the import specifier being resolved + * start - lookup path + * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this) + * request - the import specifier being resolved + * start - lookup path + * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"` + +* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving. +This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag. +**Note:** this property is currently `true` by default but it will be changed to +`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*. + +default `opts` values: + +```js +{ + paths: [], + basedir: __dirname, + extensions: ['.js'], + includeCoreModules: true, + readFileSync: fs.readFileSync, + isFile: function isFile(file) { + try { + var stat = fs.statSync(file); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isFile() || stat.isFIFO(); + }, + isDirectory: function isDirectory(dir) { + try { + var stat = fs.statSync(dir); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isDirectory(); + }, + realpathSync: function realpathSync(file) { + try { + var realpath = typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync; + return realpath(file); + } catch (realPathErr) { + if (realPathErr.code !== 'ENOENT') { + throw realPathErr; + } + } + return file; + }, + readPackageSync: function defaultReadPackageSync(readFileSync, pkgfile) { + var body = readFileSync(pkgfile); + try { + var pkg = JSON.parse(body); + return pkg; + } catch (jsonErr) {} + }, + moduleDirectory: 'node_modules', + preserveSymlinks: true +} +``` + +# install + +With [npm](https://npmjs.org) do: + +```sh +npm install resolve +``` + +# license + +MIT + +[1]: https://npmjs.org/package/resolve +[2]: https://versionbadg.es/browserify/resolve.svg +[5]: https://david-dm.org/browserify/resolve.svg +[6]: https://david-dm.org/browserify/resolve +[7]: https://david-dm.org/browserify/resolve/dev-status.svg +[8]: https://david-dm.org/browserify/resolve#info=devDependencies +[11]: https://nodei.co/npm/resolve.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/resolve.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/resolve.svg +[downloads-url]: https://npm-stat.com/charts.html?package=resolve +[codecov-image]: https://codecov.io/gh/browserify/resolve/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/browserify/resolve/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/browserify/resolve +[actions-url]: https://github.com/browserify/resolve/actions diff --git a/node_modules/mathjs/examples/node_modules/resolve/sync.js b/node_modules/mathjs/examples/node_modules/resolve/sync.js new file mode 100644 index 0000000..cd0ee04 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/sync.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/sync'); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/core.js b/node_modules/mathjs/examples/node_modules/resolve/test/core.js new file mode 100644 index 0000000..7a3ccb1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/core.js @@ -0,0 +1,81 @@ +var test = require('tape'); +var keys = require('object-keys'); +var resolve = require('../'); + +test('core modules', function (t) { + t.test('isCore()', function (st) { + st.ok(resolve.isCore('fs')); + st.ok(resolve.isCore('net')); + st.ok(resolve.isCore('http')); + + st.ok(!resolve.isCore('seq')); + st.ok(!resolve.isCore('../')); + + st.ok(!resolve.isCore('toString')); + + st.end(); + }); + + t.test('core list', function (st) { + var cores = keys(resolve.core); + st.plan(cores.length); + + for (var i = 0; i < cores.length; ++i) { + var mod = cores[i]; + var requireFunc = function () { require(mod); }; // eslint-disable-line no-loop-func + console.log(mod, resolve.core, resolve.core[mod]); + if (resolve.core[mod]) { + st.doesNotThrow(requireFunc, mod + ' supported; requiring does not throw'); + } else { + st.throws(requireFunc, mod + ' not supported; requiring throws'); + } + } + + st.end(); + }); + + t.test('core via repl module', { skip: !resolve.core.repl }, function (st) { + var libs = require('repl')._builtinLibs; // eslint-disable-line no-underscore-dangle + if (!libs) { + st.skip('module.builtinModules does not exist'); + return st.end(); + } + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + st.ok(resolve.core[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + } + st.end(); + }); + + t.test('core via builtinModules list', { skip: !resolve.core.module }, function (st) { + var libs = require('module').builtinModules; + if (!libs) { + st.skip('module.builtinModules does not exist'); + return st.end(); + } + var blacklist = [ + '_debug_agent', + 'v8/tools/tickprocessor-driver', + 'v8/tools/SourceMap', + 'v8/tools/tickprocessor', + 'v8/tools/profile' + ]; + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + if (blacklist.indexOf(mod) === -1) { + st.ok(resolve.core[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + } + } + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/dotdot.js b/node_modules/mathjs/examples/node_modules/resolve/test/dotdot.js new file mode 100644 index 0000000..3080665 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/dotdot.js @@ -0,0 +1,29 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('dotdot', function (t) { + t.plan(4); + var dir = path.join(__dirname, '/dotdot/abc'); + + resolve('..', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'dotdot/index.js')); + }); + + resolve('.', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('dotdot sync', function (t) { + t.plan(2); + var dir = path.join(__dirname, '/dotdot/abc'); + + var a = resolve.sync('..', { basedir: dir }); + t.equal(a, path.join(__dirname, 'dotdot/index.js')); + + var b = resolve.sync('.', { basedir: dir }); + t.equal(b, path.join(dir, 'index.js')); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/dotdot/abc/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/dotdot/abc/index.js new file mode 100644 index 0000000..67f2534 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/dotdot/abc/index.js @@ -0,0 +1,2 @@ +var x = require('..'); +console.log(x); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/dotdot/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/dotdot/index.js new file mode 100644 index 0000000..643f9fc --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/dotdot/index.js @@ -0,0 +1 @@ +module.exports = 'whatever'; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/faulty_basedir.js b/node_modules/mathjs/examples/node_modules/resolve/test/faulty_basedir.js new file mode 100644 index 0000000..5f2141a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/faulty_basedir.js @@ -0,0 +1,29 @@ +var test = require('tape'); +var path = require('path'); +var resolve = require('../'); + +test('faulty basedir must produce error in windows', { skip: process.platform !== 'win32' }, function (t) { + t.plan(1); + + var resolverDir = 'C:\\a\\b\\c\\d'; + + resolve('tape/lib/test.js', { basedir: resolverDir }, function (err, res, pkg) { + t.equal(!!err, true); + }); +}); + +test('non-existent basedir should not throw when preserveSymlinks is false', function (t) { + t.plan(2); + + var opts = { + basedir: path.join(path.sep, 'unreal', 'path', 'that', 'does', 'not', 'exist'), + preserveSymlinks: false + }; + + var module = './dotdot/abc'; + + resolve(module, opts, function (err, res) { + t.equal(err.code, 'MODULE_NOT_FOUND'); + t.equal(res, undefined); + }); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/filter.js b/node_modules/mathjs/examples/node_modules/resolve/test/filter.js new file mode 100644 index 0000000..8f8cccd --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/filter.js @@ -0,0 +1,34 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('filter', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'resolver'); + var packageFilterArgs; + resolve('./baz', { + basedir: dir, + packageFilter: function (pkg, pkgfile) { + pkg.main = 'doom'; // eslint-disable-line no-param-reassign + packageFilterArgs = [pkg, pkgfile]; + return pkg; + } + }, function (err, res, pkg) { + if (err) t.fail(err); + + t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works'); + + var packageData = packageFilterArgs[0]; + t.equal(pkg, packageData, 'first packageFilter argument is "pkg"'); + t.equal(packageData.main, 'doom', 'package "main" was altered'); + + var packageFile = packageFilterArgs[1]; + t.equal( + packageFile, + path.join(dir, 'baz/package.json'), + 'second packageFilter argument is "pkgfile"' + ); + + t.end(); + }); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/filter_sync.js b/node_modules/mathjs/examples/node_modules/resolve/test/filter_sync.js new file mode 100644 index 0000000..8a43b98 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/filter_sync.js @@ -0,0 +1,33 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('filter', function (t) { + var dir = path.join(__dirname, 'resolver'); + var packageFilterArgs; + var res = resolve.sync('./baz', { + basedir: dir, + // NOTE: in v2.x, this will be `pkg, pkgfile, dir`, but must remain "broken" here in v1.x for compatibility + packageFilter: function (pkg, /*pkgfile,*/ dir) { // eslint-disable-line spaced-comment + pkg.main = 'doom'; // eslint-disable-line no-param-reassign + packageFilterArgs = 'is 1.x' ? [pkg, dir] : [pkg, pkgfile, dir]; // eslint-disable-line no-constant-condition, no-undef + return pkg; + } + }); + + t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works'); + + var packageData = packageFilterArgs[0]; + t.equal(packageData.main, 'doom', 'package "main" was altered'); + + if (!'is 1.x') { // eslint-disable-line no-constant-condition + var packageFile = packageFilterArgs[1]; + t.equal(packageFile, path.join(dir, 'baz', 'package.json'), 'package.json path is correct'); + } + + var packageDir = packageFilterArgs['is 1.x' ? 1 : 2]; // eslint-disable-line no-constant-condition + // eslint-disable-next-line no-constant-condition + t.equal(packageDir, path.join(dir, 'baz'), ('is 1.x' ? 'second' : 'third') + ' packageFilter argument is "dir"'); + + t.end(); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/home_paths.js b/node_modules/mathjs/examples/node_modules/resolve/test/home_paths.js new file mode 100644 index 0000000..3b8c9b3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/home_paths.js @@ -0,0 +1,127 @@ +'use strict'; + +var fs = require('fs'); +var homedir = require('../lib/homedir'); +var path = require('path'); + +var test = require('tape'); +var mkdirp = require('mkdirp'); +var rimraf = require('rimraf'); +var mv = require('mv'); +var copyDir = require('copy-dir'); +var tmp = require('tmp'); + +var HOME = homedir(); + +var hnm = path.join(HOME, '.node_modules'); +var hnl = path.join(HOME, '.node_libraries'); + +var resolve = require('../async'); + +function makeDir(t, dir, cb) { + mkdirp(dir, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function cleanup() { + rimraf.sync(dir); + }); + cb(); + } + }); +} + +function makeTempDir(t, dir, cb) { + if (fs.existsSync(dir)) { + var tmpResult = tmp.dirSync(); + t.teardown(tmpResult.removeCallback); + var backup = path.join(tmpResult.name, path.basename(dir)); + mv(dir, backup, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function () { + mv(backup, dir, cb); + }); + makeDir(t, dir, cb); + } + }); + } else { + makeDir(t, dir, cb); + } +} + +test('homedir module paths', function (t) { + t.plan(7); + + makeTempDir(t, hnm, function (err) { + t.error(err, 'no error with HNM temp dir'); + if (err) { + return t.end(); + } + + var bazHNMDir = path.join(hnm, 'baz'); + var dotMainDir = path.join(hnm, 'dot_main'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNMDir); + copyDir.sync(path.join(__dirname, 'resolver/dot_main'), dotMainDir); + + var bazPkg = { name: 'baz', main: 'quux.js' }; + var dotMainPkg = { main: 'index' }; + + var bazHNMmain = path.join(bazHNMDir, 'quux.js'); + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + var dotMainMain = path.join(dotMainDir, 'index.js'); + t.equal(require.resolve('dot_main'), dotMainMain, 'sanity check: require.resolve finds `dot_main`'); + + makeTempDir(t, hnl, function (err) { + t.error(err, 'no error with HNL temp dir'); + if (err) { + return t.end(); + } + var bazHNLDir = path.join(hnl, 'baz'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNLDir); + + var dotSlashMainDir = path.join(hnl, 'dot_slash_main'); + var dotSlashMainMain = path.join(dotSlashMainDir, 'index.js'); + var dotSlashMainPkg = { main: 'index' }; + copyDir.sync(path.join(__dirname, 'resolver/dot_slash_main'), dotSlashMainDir); + + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + t.equal(require.resolve('dot_slash_main'), dotSlashMainMain, 'sanity check: require.resolve finds HNL `dot_slash_main`'); + + t.test('with temp dirs', function (st) { + st.plan(3); + + st.test('just in `$HOME/.node_modules`', function (s2t) { + s2t.plan(3); + + resolve('dot_main', function (err, res, pkg) { + s2t.error(err, 'no error resolving `dot_main`'); + s2t.equal(res, dotMainMain, '`dot_main` resolves in `$HOME/.node_modules`'); + s2t.deepEqual(pkg, dotMainPkg); + }); + }); + + st.test('just in `$HOME/.node_libraries`', function (s2t) { + s2t.plan(3); + + resolve('dot_slash_main', function (err, res, pkg) { + s2t.error(err, 'no error resolving `dot_slash_main`'); + s2t.equal(res, dotSlashMainMain, '`dot_slash_main` resolves in `$HOME/.node_libraries`'); + s2t.deepEqual(pkg, dotSlashMainPkg); + }); + }); + + st.test('in `$HOME/.node_libraries` and `$HOME/.node_modules`', function (s2t) { + s2t.plan(3); + + resolve('baz', function (err, res, pkg) { + s2t.error(err, 'no error resolving `baz`'); + s2t.equal(res, bazHNMmain, '`baz` resolves in `$HOME/.node_modules` when in both'); + s2t.deepEqual(pkg, bazPkg); + }); + }); + }); + }); + }); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/home_paths_sync.js b/node_modules/mathjs/examples/node_modules/resolve/test/home_paths_sync.js new file mode 100644 index 0000000..5d2c56f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/home_paths_sync.js @@ -0,0 +1,114 @@ +'use strict'; + +var fs = require('fs'); +var homedir = require('../lib/homedir'); +var path = require('path'); + +var test = require('tape'); +var mkdirp = require('mkdirp'); +var rimraf = require('rimraf'); +var mv = require('mv'); +var copyDir = require('copy-dir'); +var tmp = require('tmp'); + +var HOME = homedir(); + +var hnm = path.join(HOME, '.node_modules'); +var hnl = path.join(HOME, '.node_libraries'); + +var resolve = require('../sync'); + +function makeDir(t, dir, cb) { + mkdirp(dir, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function cleanup() { + rimraf.sync(dir); + }); + cb(); + } + }); +} + +function makeTempDir(t, dir, cb) { + if (fs.existsSync(dir)) { + var tmpResult = tmp.dirSync(); + t.teardown(tmpResult.removeCallback); + var backup = path.join(tmpResult.name, path.basename(dir)); + mv(dir, backup, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function () { + mv(backup, dir, cb); + }); + makeDir(t, dir, cb); + } + }); + } else { + makeDir(t, dir, cb); + } +} + +test('homedir module paths', function (t) { + t.plan(7); + + makeTempDir(t, hnm, function (err) { + t.error(err, 'no error with HNM temp dir'); + if (err) { + return t.end(); + } + + var bazHNMDir = path.join(hnm, 'baz'); + var dotMainDir = path.join(hnm, 'dot_main'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNMDir); + copyDir.sync(path.join(__dirname, 'resolver/dot_main'), dotMainDir); + + var bazHNMmain = path.join(bazHNMDir, 'quux.js'); + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + var dotMainMain = path.join(dotMainDir, 'index.js'); + t.equal(require.resolve('dot_main'), dotMainMain, 'sanity check: require.resolve finds `dot_main`'); + + makeTempDir(t, hnl, function (err) { + t.error(err, 'no error with HNL temp dir'); + if (err) { + return t.end(); + } + var bazHNLDir = path.join(hnl, 'baz'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNLDir); + + var dotSlashMainDir = path.join(hnl, 'dot_slash_main'); + var dotSlashMainMain = path.join(dotSlashMainDir, 'index.js'); + copyDir.sync(path.join(__dirname, 'resolver/dot_slash_main'), dotSlashMainDir); + + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + t.equal(require.resolve('dot_slash_main'), dotSlashMainMain, 'sanity check: require.resolve finds HNL `dot_slash_main`'); + + t.test('with temp dirs', function (st) { + st.plan(3); + + st.test('just in `$HOME/.node_modules`', function (s2t) { + s2t.plan(1); + + var res = resolve('dot_main'); + s2t.equal(res, dotMainMain, '`dot_main` resolves in `$HOME/.node_modules`'); + }); + + st.test('just in `$HOME/.node_libraries`', function (s2t) { + s2t.plan(1); + + var res = resolve('dot_slash_main'); + s2t.equal(res, dotSlashMainMain, '`dot_slash_main` resolves in `$HOME/.node_libraries`'); + }); + + st.test('in `$HOME/.node_libraries` and `$HOME/.node_modules`', function (s2t) { + s2t.plan(1); + + var res = resolve('baz'); + s2t.equal(res, bazHNMmain, '`baz` resolves in `$HOME/.node_modules` when in both'); + }); + }); + }); + }); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/mock.js b/node_modules/mathjs/examples/node_modules/resolve/test/mock.js new file mode 100644 index 0000000..6116275 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/mock.js @@ -0,0 +1,315 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('mock', function (t) { + t.plan(8); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('../baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('mock from package', function (t) { + t.plan(8); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, file)); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[file]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg && pkg.main, 'bar'); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg && pkg.main, 'bar'); + }); + + resolve('baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('../baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('mock package', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('bar', opts('/foo'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + t.equal(pkg && pkg.main, './baz.js'); + }); +}); + +test('mock package from package', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('bar', opts('/foo'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + t.equal(pkg && pkg.main, './baz.js'); + }); +}); + +test('symlinked', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + dirs[path.resolve('/foo/bar/symlinked')] = true; + + function opts(basedir) { + return { + preserveSymlinks: false, + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + var resolved = path.resolve(file); + + if (resolved.indexOf('symlinked') >= 0) { + cb(null, resolved); + return; + } + + var ext = path.extname(resolved); + + if (ext) { + var dir = path.dirname(resolved); + var base = path.basename(resolved); + cb(null, path.join(dir, 'symlinked', base)); + } else { + cb(null, path.join(resolved, 'symlinked')); + } + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/symlinked/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/symlinked/baz.js')); + t.equal(pkg, undefined); + }); +}); + +test('readPackage', function (t) { + t.plan(3); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop'; + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + t.test('with readFile', function (st) { + st.plan(3); + + resolve('bar', opts('/foo'), function (err, res, pkg) { + st.error(err); + st.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + st.equal(pkg && pkg.main, './baz.js'); + }); + }); + + var readPackage = function (readFile, file, cb) { + var barPackage = path.join('bar', 'package.json'); + if (file.slice(-barPackage.length) === barPackage) { + cb(null, { main: './something-else.js' }); + } else { + cb(null, JSON.parse(files[path.resolve(file)])); + } + }; + + t.test('with readPackage', function (st) { + st.plan(3); + + var options = opts('/foo'); + delete options.readFile; + options.readPackage = readPackage; + resolve('bar', options, function (err, res, pkg) { + st.error(err); + st.equal(res, path.resolve('/foo/node_modules/bar/something-else.js')); + st.equal(pkg && pkg.main, './something-else.js'); + }); + }); + + t.test('with readFile and readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + options.readPackage = readPackage; + resolve('bar', options, function (err) { + st.throws(function () { throw err; }, TypeError, 'errors when both readFile and readPackage are provided'); + }); + }); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/mock_sync.js b/node_modules/mathjs/examples/node_modules/resolve/test/mock_sync.js new file mode 100644 index 0000000..c5a7e2a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/mock_sync.js @@ -0,0 +1,214 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('mock', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + + t.equal( + resolve.sync('./baz', opts('/foo/bar')), + path.resolve('/foo/bar/baz.js') + ); + + t.equal( + resolve.sync('./baz.js', opts('/foo/bar')), + path.resolve('/foo/bar/baz.js') + ); + + t.throws(function () { + resolve.sync('baz', opts('/foo/bar')); + }); + + t.throws(function () { + resolve.sync('../baz', opts('/foo/bar')); + }); +}); + +test('mock package', function (t) { + t.plan(1); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + + t.equal( + resolve.sync('bar', opts('/foo')), + path.resolve('/foo/node_modules/bar/baz.js') + ); +}); + +test('symlinked', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + dirs[path.resolve('/foo/bar/symlinked')] = true; + + function opts(basedir) { + return { + preserveSymlinks: false, + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + var resolved = path.resolve(file); + + if (resolved.indexOf('symlinked') >= 0) { + return resolved; + } + + var ext = path.extname(resolved); + + if (ext) { + var dir = path.dirname(resolved); + var base = path.basename(resolved); + return path.join(dir, 'symlinked', base); + } + return path.join(resolved, 'symlinked'); + } + }; + } + + t.equal( + resolve.sync('./baz', opts('/foo/bar')), + path.resolve('/foo/bar/symlinked/baz.js') + ); + + t.equal( + resolve.sync('./baz.js', opts('/foo/bar')), + path.resolve('/foo/bar/symlinked/baz.js') + ); +}); + +test('readPackageSync', function (t) { + t.plan(3); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop'; + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir, useReadPackage) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: useReadPackage ? null : function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + t.test('with readFile', function (st) { + st.plan(1); + + st.equal( + resolve.sync('bar', opts('/foo')), + path.resolve('/foo/node_modules/bar/baz.js') + ); + }); + + var readPackageSync = function (readFileSync, file) { + if (file.indexOf(path.join('bar', 'package.json')) >= 0) { + return { main: './something-else.js' }; + } + return JSON.parse(files[path.resolve(file)]); + }; + + t.test('with readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + delete options.readFileSync; + options.readPackageSync = readPackageSync; + + st.equal( + resolve.sync('bar', options), + path.resolve('/foo/node_modules/bar/something-else.js') + ); + }); + + t.test('with readFile and readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + options.readPackageSync = readPackageSync; + st.throws( + function () { resolve.sync('bar', options); }, + TypeError, + 'errors when both readFile and readPackage are provided' + ); + }); +}); + diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/module_dir.js b/node_modules/mathjs/examples/node_modules/resolve/test/module_dir.js new file mode 100644 index 0000000..b50e5bb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/module_dir.js @@ -0,0 +1,56 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('moduleDirectory strings', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'module_dir'); + var xopts = { + basedir: dir, + moduleDirectory: 'xmodules' + }; + resolve('aaa', xopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/xmodules/aaa/index.js')); + }); + + var yopts = { + basedir: dir, + moduleDirectory: 'ymodules' + }; + resolve('aaa', yopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/ymodules/aaa/index.js')); + }); +}); + +test('moduleDirectory array', function (t) { + t.plan(6); + var dir = path.join(__dirname, 'module_dir'); + var aopts = { + basedir: dir, + moduleDirectory: ['xmodules', 'ymodules', 'zmodules'] + }; + resolve('aaa', aopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/xmodules/aaa/index.js')); + }); + + var bopts = { + basedir: dir, + moduleDirectory: ['zmodules', 'ymodules', 'xmodules'] + }; + resolve('aaa', bopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/ymodules/aaa/index.js')); + }); + + var copts = { + basedir: dir, + moduleDirectory: ['xmodules', 'ymodules', 'zmodules'] + }; + resolve('bbb', copts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/zmodules/bbb/main.js')); + }); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/xmodules/aaa/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/xmodules/aaa/index.js new file mode 100644 index 0000000..dd7cf7b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/xmodules/aaa/index.js @@ -0,0 +1 @@ +module.exports = function (x) { return x * 100; }; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/ymodules/aaa/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/ymodules/aaa/index.js new file mode 100644 index 0000000..ef2d4d4 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/ymodules/aaa/index.js @@ -0,0 +1 @@ +module.exports = function (x) { return x + 100; }; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/zmodules/bbb/main.js b/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/zmodules/bbb/main.js new file mode 100644 index 0000000..e8ba629 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/zmodules/bbb/main.js @@ -0,0 +1 @@ +module.exports = function (n) { return n * 111; }; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/zmodules/bbb/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/zmodules/bbb/package.json new file mode 100644 index 0000000..c13b8cf --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/module_dir/zmodules/bbb/package.json @@ -0,0 +1,3 @@ +{ + "main": "main.js" +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/node-modules-paths.js b/node_modules/mathjs/examples/node_modules/resolve/test/node-modules-paths.js new file mode 100644 index 0000000..675441d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/node-modules-paths.js @@ -0,0 +1,143 @@ +var test = require('tape'); +var path = require('path'); +var parse = path.parse || require('path-parse'); +var keys = require('object-keys'); + +var nodeModulesPaths = require('../lib/node-modules-paths'); + +var verifyDirs = function verifyDirs(t, start, dirs, moduleDirectories, paths) { + var moduleDirs = [].concat(moduleDirectories || 'node_modules'); + if (paths) { + for (var k = 0; k < paths.length; ++k) { + moduleDirs.push(path.basename(paths[k])); + } + } + + var foundModuleDirs = {}; + var uniqueDirs = {}; + var parsedDirs = {}; + for (var i = 0; i < dirs.length; ++i) { + var parsed = parse(dirs[i]); + if (!foundModuleDirs[parsed.base]) { foundModuleDirs[parsed.base] = 0; } + foundModuleDirs[parsed.base] += 1; + parsedDirs[parsed.dir] = true; + uniqueDirs[dirs[i]] = true; + } + t.equal(keys(parsedDirs).length >= start.split(path.sep).length, true, 'there are >= dirs than "start" has'); + var foundModuleDirNames = keys(foundModuleDirs); + t.deepEqual(foundModuleDirNames, moduleDirs, 'all desired module dirs were found'); + t.equal(keys(uniqueDirs).length, dirs.length, 'all dirs provided were unique'); + + var counts = {}; + for (var j = 0; j < foundModuleDirNames.length; ++j) { + counts[foundModuleDirs[j]] = true; + } + t.equal(keys(counts).length, 1, 'all found module directories had the same count'); +}; + +test('node-modules-paths', function (t) { + t.test('no options', function (t) { + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start); + + verifyDirs(t, start, dirs); + + t.end(); + }); + + t.test('empty options', function (t) { + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, {}); + + verifyDirs(t, start, dirs); + + t.end(); + }); + + t.test('with paths=array option', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var dirs = nodeModulesPaths(start, { paths: paths }); + + verifyDirs(t, start, dirs, null, paths); + + t.end(); + }); + + t.test('with paths=function option', function (t) { + var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) { + return getNodeModulesDirs().concat(path.join(absoluteStart, 'not node modules', request)); + }; + + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, { paths: paths }, 'pkg'); + + verifyDirs(t, start, dirs, null, [path.join(start, 'not node modules', 'pkg')]); + + t.end(); + }); + + t.test('with paths=function skipping node modules resolution', function (t) { + var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) { + return []; + }; + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, { paths: paths }); + t.deepEqual(dirs, [], 'no node_modules was computed'); + t.end(); + }); + + t.test('with moduleDirectory option', function (t) { + var start = path.join(__dirname, 'resolver'); + var moduleDirectory = 'not node modules'; + var dirs = nodeModulesPaths(start, { moduleDirectory: moduleDirectory }); + + verifyDirs(t, start, dirs, moduleDirectory); + + t.end(); + }); + + t.test('with 1 moduleDirectory and paths options', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var moduleDirectory = 'not node modules'; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectory }); + + verifyDirs(t, start, dirs, moduleDirectory, paths); + + t.end(); + }); + + t.test('with 1+ moduleDirectory and paths options', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var moduleDirectories = ['not node modules', 'other modules']; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + verifyDirs(t, start, dirs, moduleDirectories, paths); + + t.end(); + }); + + t.test('combine paths correctly on Windows', function (t) { + var start = 'C:\\Users\\username\\myProject\\src'; + var paths = []; + var moduleDirectories = ['node_modules', start]; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir'); + + t.end(); + }); + + t.test('combine paths correctly on non-Windows', { skip: process.platform === 'win32' }, function (t) { + var start = '/Users/username/git/myProject/src'; + var paths = []; + var moduleDirectories = ['node_modules', '/Users/username/git/myProject/src']; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir'); + + t.end(); + }); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/node_path.js b/node_modules/mathjs/examples/node_modules/resolve/test/node_path.js new file mode 100644 index 0000000..e463d6c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/node_path.js @@ -0,0 +1,70 @@ +var fs = require('fs'); +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('$NODE_PATH', function (t) { + t.plan(8); + + var isDir = function (dir, cb) { + if (dir === '/node_path' || dir === 'node_path/x') { + return cb(null, true); + } + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }; + + resolve('aaa', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/x/aaa/index.js'), 'aaa resolves'); + }); + + resolve('bbb', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/y/bbb/index.js'), 'bbb resolves'); + }); + + resolve('ccc', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/x/ccc/index.js'), 'ccc resolves'); + }); + + // ensure that relative paths still resolve against the regular `node_modules` correctly + resolve('tap', { + paths: [ + 'node_path' + ], + basedir: path.join(__dirname, 'node_path/x'), + isDirectory: isDir + }, function (err, res) { + var root = require('tap/package.json').main; // eslint-disable-line global-require + t.error(err); + t.equal(res, path.resolve(__dirname, '..', 'node_modules/tap', root), 'tap resolves'); + }); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/node_path/x/aaa/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/node_path/x/aaa/index.js new file mode 100644 index 0000000..ad70d0b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/node_path/x/aaa/index.js @@ -0,0 +1 @@ +module.exports = 'A'; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/node_path/x/ccc/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/node_path/x/ccc/index.js new file mode 100644 index 0000000..a64132e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/node_path/x/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'C'; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/node_path/y/bbb/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/node_path/y/bbb/index.js new file mode 100644 index 0000000..4d0f32e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/node_path/y/bbb/index.js @@ -0,0 +1 @@ +module.exports = 'B'; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/node_path/y/ccc/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/node_path/y/ccc/index.js new file mode 100644 index 0000000..793315e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/node_path/y/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'CY'; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/nonstring.js b/node_modules/mathjs/examples/node_modules/resolve/test/nonstring.js new file mode 100644 index 0000000..ef63c40 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/nonstring.js @@ -0,0 +1,9 @@ +var test = require('tape'); +var resolve = require('../'); + +test('nonstring', function (t) { + t.plan(1); + resolve(555, function (err, res, pkg) { + t.ok(err); + }); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/pathfilter.js b/node_modules/mathjs/examples/node_modules/resolve/test/pathfilter.js new file mode 100644 index 0000000..16519ae --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/pathfilter.js @@ -0,0 +1,75 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +var resolverDir = path.join(__dirname, '/pathfilter/deep_ref'); + +var pathFilterFactory = function (t) { + return function (pkg, x, remainder) { + t.equal(pkg.version, '1.2.3'); + t.equal(x, path.join(resolverDir, 'node_modules/deep/ref')); + t.equal(remainder, 'ref'); + return 'alt'; + }; +}; + +test('#62: deep module references and the pathFilter', function (t) { + t.test('deep/ref.js', function (st) { + st.plan(3); + + resolve('deep/ref', { basedir: resolverDir }, function (err, res, pkg) { + if (err) st.fail(err); + + st.equal(pkg.version, '1.2.3'); + st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js')); + }); + + var res = resolve.sync('deep/ref', { basedir: resolverDir }); + st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js')); + }); + + t.test('deep/deeper/ref', function (st) { + st.plan(4); + + resolve( + 'deep/deeper/ref', + { basedir: resolverDir }, + function (err, res, pkg) { + if (err) t.fail(err); + st.notEqual(pkg, undefined); + st.equal(pkg.version, '1.2.3'); + st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js')); + } + ); + + var res = resolve.sync( + 'deep/deeper/ref', + { basedir: resolverDir } + ); + st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js')); + }); + + t.test('deep/ref alt', function (st) { + st.plan(8); + + var pathFilter = pathFilterFactory(st); + + var res = resolve.sync( + 'deep/ref', + { basedir: resolverDir, pathFilter: pathFilter } + ); + st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js')); + + resolve( + 'deep/ref', + { basedir: resolverDir, pathFilter: pathFilter }, + function (err, res, pkg) { + if (err) st.fail(err); + st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js')); + st.end(); + } + ); + }); + + t.end(); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/pathfilter/deep_ref/main.js b/node_modules/mathjs/examples/node_modules/resolve/test/pathfilter/deep_ref/main.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/precedence.js b/node_modules/mathjs/examples/node_modules/resolve/test/precedence.js new file mode 100644 index 0000000..2febb59 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/precedence.js @@ -0,0 +1,23 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('precedence', function (t) { + t.plan(3); + var dir = path.join(__dirname, 'precedence/aaa'); + + resolve('./', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, 'index.js')); + t.equal(pkg.name, 'resolve'); + }); +}); + +test('./ should not load ${dir}.js', function (t) { // eslint-disable-line no-template-curly-in-string + t.plan(1); + var dir = path.join(__dirname, 'precedence/bbb'); + + resolve('./', { basedir: dir }, function (err, res, pkg) { + t.ok(err); + }); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/precedence/aaa.js b/node_modules/mathjs/examples/node_modules/resolve/test/precedence/aaa.js new file mode 100644 index 0000000..b83a3e7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/precedence/aaa.js @@ -0,0 +1 @@ +module.exports = 'wtf'; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/precedence/aaa/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/precedence/aaa/index.js new file mode 100644 index 0000000..e0f8f6a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/precedence/aaa/index.js @@ -0,0 +1 @@ +module.exports = 'okok'; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/precedence/aaa/main.js b/node_modules/mathjs/examples/node_modules/resolve/test/precedence/aaa/main.js new file mode 100644 index 0000000..93542a9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/precedence/aaa/main.js @@ -0,0 +1 @@ +console.log(require('./')); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/precedence/bbb.js b/node_modules/mathjs/examples/node_modules/resolve/test/precedence/bbb.js new file mode 100644 index 0000000..2298f47 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/precedence/bbb.js @@ -0,0 +1 @@ +module.exports = '>_<'; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/precedence/bbb/main.js b/node_modules/mathjs/examples/node_modules/resolve/test/precedence/bbb/main.js new file mode 100644 index 0000000..716b81d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/precedence/bbb/main.js @@ -0,0 +1 @@ +console.log(require('./')); // should throw diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver.js new file mode 100644 index 0000000..09da686 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver.js @@ -0,0 +1,546 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); +var async = require('../async'); + +test('`./async` entry point', function (t) { + t.equal(resolve, async, '`./async` entry point is the same as `main`'); + t.end(); +}); + +test('async foo', function (t) { + t.plan(12); + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo.js', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.main, 'resolver'); + }); + + resolve('./foo.js', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg.main, 'resolver'); + }); + + resolve('./foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + }); + + resolve('foo', { basedir: dir }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.join(dir, 'baz.js') + "'"); + }); +}); + +test('bar', function (t) { + t.plan(6); + var dir = path.join(__dirname, 'resolver'); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar', 'package': { main: 'bar' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg.main, 'bar'); + }); +}); + +test('baz', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'resolver'); + + resolve('./baz', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); + + resolve('./baz', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); +}); + +test('biz', function (t) { + t.plan(24); + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + + resolve('./grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('./grux', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'biz'); + }); + + resolve('./garply', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('./garply', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('tiv', { basedir: dir + '/grux' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/grux', 'package': { main: 'grux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, 'grux'); + }); + + resolve('tiv', { basedir: dir + '/garply' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/garply', 'package': { main: './lib' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('grux', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('grux', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'tiv'); + }); + + resolve('garply', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('garply', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); +}); + +test('quux', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/quux'); + + resolve('./foo', { basedir: dir, 'package': { main: 'quux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo/index.js')); + t.equal(pkg.main, 'quux'); + }); +}); + +test('normalize', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + + resolve('../grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + t.equal(pkg, undefined); + }); +}); + +test('cup', function (t) { + t.plan(5); + var dir = path.join(__dirname, 'resolver'); + + resolve('./cup', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup.coffee', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup', { basedir: dir, extensions: ['.js'] }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('./cup', { basedir: dir, extensions: ['.js'], filename: path.join(dir, 'cupboard.js') }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.join(dir, 'cupboard.js') + "'"); + }); +}); + +test('mug', function (t) { + t.plan(3); + var dir = path.join(__dirname, 'resolver'); + + resolve('./mug', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'mug.js')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.coffee', '.js'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, '/mug.coffee')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + t.equal(res, path.join(dir, '/mug.js')); + }); +}); + +test('other path', function (t) { + t.plan(6); + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + resolve('root', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/root.js')); + }); + + resolve('lib/other-lib', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/lib/other-lib.js')); + }); + + resolve('root', { basedir: dir }, function (err, res) { + t.equal(err.message, "Cannot find module 'root' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('zzz', { basedir: dir, paths: [otherDir] }, function (err, res) { + t.equal(err.message, "Cannot find module 'zzz' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('path iterator', function (t) { + t.plan(2); + + var resolverDir = path.join(__dirname, 'resolver'); + + var exactIterator = function (x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + }; + + resolve('baz', { packageIterator: exactIterator }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'baz/quux.js')); + t.equal(pkg && pkg.name, 'baz'); + }); +}); + +test('incorrect main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + resolve('./incorrect_main', { basedir: resolverDir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('without basedir', function (t) { + t.plan(1); + + var dir = path.join(__dirname, 'resolver/without_basedir'); + var tester = require(path.join(dir, 'main.js')); // eslint-disable-line global-require + + tester(t, function (err, res, pkg) { + if (err) { + t.fail(err); + } else { + t.equal(res, path.join(dir, 'node_modules/mymodule.js')); + } + }); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo.js')); + }); + + resolve('./foo/', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); + + resolve('.', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('async: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.plan(1); + resolve('./' + testFile, function (err, res, pkg) { + if (err) t.fail(err); + st.equal(res, __filename, 'sanity check'); + }); + }); + + t.test('with a fake directory', function (st) { + st.plan(4); + + resolve('./' + testFile + '/blah', function (err, res, pkg) { + st.ok(err, 'there is an error'); + st.notOk(res, 'no result'); + + st.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + err && err.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + st.end(); + }); + }); + + t.end(); +}); + +test('async dot main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('async dot slash main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_slash_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_slash_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('not a directory', function (t) { + t.plan(6); + var path = './foo'; + resolve(path, { basedir: __filename }, function (err, res, pkg) { + t.ok(err, 'a non-directory errors'); + t.equal(arguments.length, 1); + t.equal(res, undefined); + t.equal(pkg, undefined); + + t.equal(err && err.message, 'Cannot find module \'' + path + '\' from \'' + __filename + '\''); + t.equal(err && err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('browser field in package.json', function (t) { + t.plan(3); + + var dir = path.join(__dirname, 'resolver'); + resolve( + './browser_field', + { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }, + function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.equal(pkg && pkg.main, 'b'); + t.equal(pkg && pkg.browser, undefined); + } + ); +}); + +test('absolute paths', function (t) { + t.plan(4); + + var extensionless = __filename.slice(0, -path.extname(__filename).length); + + resolve(__filename, function (err, res) { + t.equal( + res, + __filename, + 'absolute path to this file resolves' + ); + }); + resolve(extensionless, function (err, res) { + t.equal( + res, + __filename, + 'extensionless absolute path to this file resolves' + ); + }); + resolve(__filename, { basedir: process.cwd() }, function (err, res) { + t.equal( + res, + __filename, + 'absolute path to this file with a basedir resolves' + ); + }); + resolve(extensionless, { basedir: process.cwd() }, function (err, res) { + t.equal( + res, + __filename, + 'extensionless absolute path to this file with a basedir resolves' + ); + }); +}); + +test('malformed package.json', function (t) { + /* eslint operator-linebreak: ["error", "before"], function-paren-newline: "off" */ + t.plan( + (3 * 3) // 3 sets of 3 assertions in the final callback + + 2 // 1 readPackage call with malformed package.json + ); + + var basedir = path.join(__dirname, 'resolver/malformed_package_json'); + var expected = path.join(basedir, 'index.js'); + + resolve('./index.js', { basedir: basedir }, function (err, res, pkg) { + t.error(err, 'no error'); + t.equal(res, expected, 'malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'malformed package.json gives an undefined `pkg` argument'); + }); + + resolve( + './index.js', + { + basedir: basedir, + packageFilter: function (pkg, pkgfile, dir) { + t.fail('should not reach here'); + } + }, + function (err, res, pkg) { + t.error(err, 'with packageFilter: no error'); + t.equal(res, expected, 'with packageFilter: malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'with packageFilter: malformed package.json gives an undefined `pkg` argument'); + } + ); + + resolve( + './index.js', + { + basedir: basedir, + readPackage: function (readFile, pkgfile, cb) { + t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path'); + readFile(pkgfile, function (err, result) { + try { + cb(null, JSON.parse(result)); + } catch (e) { + t.ok(e instanceof SyntaxError, 'readPackage: malformed package.json parses as a syntax error'); + cb(null); + } + }); + } + }, + function (err, res, pkg) { + t.error(err, 'with readPackage: no error'); + t.equal(res, expected, 'with readPackage: malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'with readPackage: malformed package.json gives an undefined `pkg` argument'); + } + ); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/baz/doom.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/baz/doom.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/baz/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/baz/package.json new file mode 100644 index 0000000..2f77720 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/baz/package.json @@ -0,0 +1,4 @@ +{ + "name": "baz", + "main": "quux.js" +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/baz/quux.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/baz/quux.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/baz/quux.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/browser_field/a.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/browser_field/a.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/browser_field/b.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/browser_field/b.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/browser_field/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/browser_field/package.json new file mode 100644 index 0000000..bf406f0 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/browser_field/package.json @@ -0,0 +1,5 @@ +{ + "name": "browser_field", + "main": "a", + "browser": "b" +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/cup.coffee b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/cup.coffee new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/cup.coffee @@ -0,0 +1 @@ + diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_main/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_main/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_main/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_main/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_main/package.json new file mode 100644 index 0000000..d7f4fc8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "." +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_slash_main/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_slash_main/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_slash_main/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_slash_main/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_slash_main/package.json new file mode 100644 index 0000000..f51287b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/dot_slash_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "./" +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/foo.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/foo.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/foo.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/incorrect_main/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/incorrect_main/index.js new file mode 100644 index 0000000..bc1fb0a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/incorrect_main/index.js @@ -0,0 +1,2 @@ +// this is the actual main file 'index.js', not 'wrong.js' like the package.json would indicate +module.exports = 1; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/incorrect_main/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/incorrect_main/package.json new file mode 100644 index 0000000..b718804 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/incorrect_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "wrong.js" +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/invalid_main/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/invalid_main/package.json new file mode 100644 index 0000000..0590748 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/invalid_main/package.json @@ -0,0 +1,7 @@ +{ + "name": "invalid_main", + "main": [ + "why is this a thing", + "srsly omg wtf" + ] +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/malformed_package_json/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/malformed_package_json/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/malformed_package_json/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/malformed_package_json/package.json new file mode 100644 index 0000000..98232c6 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/malformed_package_json/package.json @@ -0,0 +1 @@ +{ diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/mug.coffee b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/mug.coffee new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/mug.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/mug.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/lerna.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/lerna.json new file mode 100644 index 0000000..d6707ca --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/lerna.json @@ -0,0 +1,6 @@ +{ + "packages": [ + "packages/*" + ], + "version": "0.0.0" +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/package.json new file mode 100644 index 0000000..8508f9d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/package.json @@ -0,0 +1,20 @@ +{ + "name": "monorepo-symlink-test", + "private": true, + "version": "0.0.0", + "description": "", + "main": "index.js", + "scripts": { + "postinstall": "lerna bootstrap", + "test": "node packages/package-a" + }, + "author": "", + "license": "MIT", + "dependencies": { + "jquery": "^3.3.1", + "resolve": "../../../" + }, + "devDependencies": { + "lerna": "^3.4.3" + } +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js new file mode 100644 index 0000000..8875a32 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var assert = require('assert'); +var path = require('path'); +var resolve = require('resolve'); + +var basedir = __dirname + '/node_modules/@my-scope/package-b'; + +var expected = path.join(__dirname, '../../node_modules/jquery/dist/jquery.js'); + +/* + * preserveSymlinks === false + * will search NPM package from + * - packages/package-b/node_modules + * - packages/node_modules + * - node_modules + */ +assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: false }), expected); +assert.equal(resolve.sync('../../node_modules/jquery', { basedir: basedir, preserveSymlinks: false }), expected); + +/* + * preserveSymlinks === true + * will search NPM package from + * - packages/package-a/node_modules/@my-scope/packages/package-b/node_modules + * - packages/package-a/node_modules/@my-scope/packages/node_modules + * - packages/package-a/node_modules/@my-scope/node_modules + * - packages/package-a/node_modules/node_modules + * - packages/package-a/node_modules + * - packages/node_modules + * - node_modules + */ +assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: true }), expected); +assert.equal(resolve.sync('../../../../../node_modules/jquery', { basedir: basedir, preserveSymlinks: true }), expected); + +console.log(' * all monorepo paths successfully resolved through symlinks'); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json new file mode 100644 index 0000000..204de51 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json @@ -0,0 +1,14 @@ +{ + "name": "@my-scope/package-a", + "version": "0.0.0", + "private": true, + "description": "", + "license": "MIT", + "main": "index.js", + "scripts": { + "test": "echo \"Error: run tests from root\" && exit 1" + }, + "dependencies": { + "@my-scope/package-b": "^0.0.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/packages/package-b/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/packages/package-b/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json new file mode 100644 index 0000000..f57c3b5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json @@ -0,0 +1,14 @@ +{ + "name": "@my-scope/package-b", + "private": true, + "version": "0.0.0", + "description": "", + "license": "MIT", + "main": "index.js", + "scripts": { + "test": "echo \"Error: run tests from root\" && exit 1" + }, + "dependencies": { + "@my-scope/package-a": "^0.0.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js new file mode 100644 index 0000000..9b4846a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js @@ -0,0 +1,26 @@ +var a = require.resolve('buffer/').replace(process.cwd(), '$CWD'); +var b; +var c; + +var test = function test() { + console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false')); + console.log(b, ': preserveSymlinks true'); + console.log(c, ': preserveSymlinks false'); + + if (a !== b && a !== c) { + throw 'async: no match'; + } + console.log('async: success! a matched either b or c\n'); +}; + +require('resolve')('buffer/', { preserveSymlinks: true }, function (err, result) { + if (err) { throw err; } + b = result.replace(process.cwd(), '$CWD'); + if (b && c) { test(); } +}); +require('resolve')('buffer/', { preserveSymlinks: false }, function (err, result) { + if (err) { throw err; } + c = result.replace(process.cwd(), '$CWD'); + if (b && c) { test(); } +}); + diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json new file mode 100644 index 0000000..acfe9e9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json @@ -0,0 +1,15 @@ +{ + "name": "mylib", + "version": "0.0.0", + "description": "", + "private": true, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "buffer": "*" + } +} diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js new file mode 100644 index 0000000..3283efc --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js @@ -0,0 +1,12 @@ +var a = require.resolve('buffer/').replace(process.cwd(), '$CWD'); +var b = require('resolve').sync('buffer/', { preserveSymlinks: true }).replace(process.cwd(), '$CWD'); +var c = require('resolve').sync('buffer/', { preserveSymlinks: false }).replace(process.cwd(), '$CWD'); + +console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false')); +console.log(b, ': preserveSymlinks true'); +console.log(c, ': preserveSymlinks false'); + +if (a !== b && a !== c) { + throw 'sync: no match'; +} +console.log('sync: success! a matched either b or c\n'); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/other_path/lib/other-lib.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/other_path/lib/other-lib.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/other_path/root.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/other_path/root.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/quux/foo/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/quux/foo/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/quux/foo/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/same_names/foo.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/same_names/foo.js new file mode 100644 index 0000000..888cae3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/same_names/foo.js @@ -0,0 +1 @@ +module.exports = 42; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/same_names/foo/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/same_names/foo/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/same_names/foo/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/symlinked/_/node_modules/foo.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/symlinked/_/node_modules/foo.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/symlinked/_/symlink_target/.gitkeep b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/symlinked/_/symlink_target/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/symlinked/package/bar.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/symlinked/package/bar.js new file mode 100644 index 0000000..cb1c2c0 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/symlinked/package/bar.js @@ -0,0 +1 @@ +module.exports = 'bar'; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/symlinked/package/package.json b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/symlinked/package/package.json new file mode 100644 index 0000000..8e1b585 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/symlinked/package/package.json @@ -0,0 +1,3 @@ +{ + "main": "bar.js" +} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver/without_basedir/main.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/without_basedir/main.js new file mode 100644 index 0000000..5b31975 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver/without_basedir/main.js @@ -0,0 +1,5 @@ +var resolve = require('../../../'); + +module.exports = function (t, cb) { + resolve('mymodule', null, cb); +}; diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/resolver_sync.js b/node_modules/mathjs/examples/node_modules/resolve/test/resolver_sync.js new file mode 100644 index 0000000..6e4ae1e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/resolver_sync.js @@ -0,0 +1,645 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); + +var resolve = require('../'); +var sync = require('../sync'); + +var requireResolveSupportsPaths = require.resolve.length > 1 + && (/^12\.[012]\./).test(process.version); // broken in v12.0-12.2, see https://github.com/nodejs/node/issues/27794 + +test('`./sync` entry point', function (t) { + t.equal(resolve.sync, sync, '`./sync` entry point is the same as `.sync` on `main`'); + t.end(); +}); + +test('foo', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./foo', { basedir: dir }), + path.join(dir, 'foo.js'), + './foo' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo', { basedir: dir }), + require.resolve('./foo', { paths: [dir] }), + './foo: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + path.join(dir, 'foo.js'), + './foo.js' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + require.resolve('./foo.js', { paths: [dir] }), + './foo.js: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo.js', { basedir: dir, filename: path.join(dir, 'bar.js') }), + path.join(dir, 'foo.js') + ); + + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }); + + // Test that filename is reported as the "from" value when passed. + t.throws( + function () { + resolve.sync('foo', { basedir: dir, filename: path.join(dir, 'bar.js') }); + }, + { + name: 'Error', + message: "Cannot find module 'foo' from '" + path.join(dir, 'bar.js') + "'" + } + ); + + t.end(); +}); + +test('bar', function (t) { + var dir = path.join(__dirname, 'resolver'); + + var basedir = path.join(dir, 'bar'); + + t.equal( + resolve.sync('foo', { basedir: basedir }), + path.join(dir, 'bar/node_modules/foo/index.js'), + 'foo in bar' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('foo', { basedir: basedir }), + require.resolve('foo', { paths: [basedir] }), + 'foo in bar: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('baz', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./baz', { basedir: dir }), + path.join(dir, 'baz/quux.js'), + './baz' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./baz', { basedir: dir }), + require.resolve('./baz', { paths: [dir] }), + './baz: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('biz', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + + t.equal( + resolve.sync('./grux', { basedir: dir }), + path.join(dir, 'grux/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./grux', { basedir: dir }), + require.resolve('./grux', { paths: [dir] }), + './grux: resolve.sync === require.resolve' + ); + } + + var tivDir = path.join(dir, 'grux'); + t.equal( + resolve.sync('tiv', { basedir: tivDir }), + path.join(dir, 'tiv/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('tiv', { basedir: tivDir }), + require.resolve('tiv', { paths: [tivDir] }), + 'tiv: resolve.sync === require.resolve' + ); + } + + var gruxDir = path.join(dir, 'tiv'); + t.equal( + resolve.sync('grux', { basedir: gruxDir }), + path.join(dir, 'grux/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('grux', { basedir: gruxDir }), + require.resolve('grux', { paths: [gruxDir] }), + 'grux: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('normalize', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + + t.equal( + resolve.sync('../grux', { basedir: dir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('../grux', { basedir: dir }), + require.resolve('../grux', { paths: [dir] }), + '../grux: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('cup', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'cup.coffee'), + './cup -> ./cup.coffee' + ); + + t.equal( + resolve.sync('./cup.coffee', { basedir: dir }), + path.join(dir, 'cup.coffee'), + './cup.coffee' + ); + + t.throws(function () { + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js'] + }); + }); + + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./cup.coffee', { basedir: dir, extensions: ['.js', '.coffee'] }), + require.resolve('./cup.coffee', { paths: [dir] }), + './cup.coffee: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('mug', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./mug', { basedir: dir }), + path.join(dir, 'mug.js'), + './mug -> ./mug.js' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./mug', { basedir: dir }), + require.resolve('./mug', { paths: [dir] }), + './mug: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.coffee', '.js'] + }), + path.join(dir, 'mug.coffee'), + './mug -> ./mug.coffee' + ); + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'mug.js'), + './mug -> ./mug.js' + ); + + t.end(); +}); + +test('other path', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + t.equal( + resolve.sync('root', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/root.js') + ); + + t.equal( + resolve.sync('lib/other-lib', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/lib/other-lib.js') + ); + + t.throws(function () { + resolve.sync('root', { basedir: dir }); + }); + + t.throws(function () { + resolve.sync('zzz', { + basedir: dir, + paths: [otherDir] + }); + }); + + t.end(); +}); + +test('path iterator', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + var exactIterator = function (x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + }; + + t.equal( + resolve.sync('baz', { packageIterator: exactIterator }), + path.join(resolverDir, 'baz/quux.js') + ); + + t.end(); +}); + +test('incorrect main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + require.resolve('./incorrect_main', { paths: [resolverDir] }), + './incorrect_main: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +var stubStatSync = function stubStatSync(fn) { + var statSync = fs.statSync; + try { + fs.statSync = function () { + throw new EvalError('Unknown Error'); + }; + return fn(); + } finally { + fs.statSync = statSync; + } +}; + +test('#79 - re-throw non ENOENT errors from stat', function (t) { + var dir = path.join(__dirname, 'resolver'); + + stubStatSync(function () { + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }, /Unknown Error/); + }); + + t.end(); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + var basedir = path.join(dir, 'same_names'); + + t.equal( + resolve.sync('./foo', { basedir: basedir }), + path.join(dir, 'same_names/foo.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo', { basedir: basedir }), + require.resolve('./foo', { paths: [basedir] }), + './foo: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo/', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo/', { basedir: basedir }), + require.resolve('./foo/', { paths: [basedir] }), + './foo/: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + var basedir = path.join(dir, 'same_names/foo'); + + t.equal( + resolve.sync('./', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js'), + './' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./', { basedir: basedir }), + require.resolve('./', { paths: [basedir] }), + './: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('.', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js'), + '.' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('.', { basedir: basedir }), + require.resolve('.', { paths: [basedir] }), + '.: resolve.sync === require.resolve', + { todo: true } + ); + } + + t.end(); +}); + +test('sync: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.equal( + resolve.sync('./' + testFile), + __filename, + 'sanity check' + ); + st.equal( + resolve.sync('./' + testFile), + require.resolve('./' + testFile), + 'sanity check: resolve.sync === require.resolve' + ); + + st.end(); + }); + + t.test('with a fake directory', function (st) { + function run() { return resolve.sync('./' + testFile + '/blah'); } + + st.throws(run, 'throws an error'); + + try { + run(); + } catch (e) { + st.equal(e.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + e.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + } + + st.end(); + }); + + t.end(); +}); + +test('sync dot main', function (t) { + var start = new Date(); + + t.equal( + resolve.sync('./resolver/dot_main'), + path.join(__dirname, 'resolver/dot_main/index.js'), + './resolver/dot_main' + ); + t.equal( + resolve.sync('./resolver/dot_main'), + require.resolve('./resolver/dot_main'), + './resolver/dot_main: resolve.sync === require.resolve' + ); + + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + + t.end(); +}); + +test('sync dot slash main', function (t) { + var start = new Date(); + + t.equal( + resolve.sync('./resolver/dot_slash_main'), + path.join(__dirname, 'resolver/dot_slash_main/index.js') + ); + t.equal( + resolve.sync('./resolver/dot_slash_main'), + require.resolve('./resolver/dot_slash_main'), + './resolver/dot_slash_main: resolve.sync === require.resolve' + ); + + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + + t.end(); +}); + +test('not a directory', function (t) { + var path = './foo'; + try { + resolve.sync(path, { basedir: __filename }); + t.fail(); + } catch (err) { + t.ok(err, 'a non-directory errors'); + t.equal(err && err.message, 'Cannot find module \'' + path + "' from '" + __filename + "'"); + t.equal(err && err.code, 'MODULE_NOT_FOUND'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('browser field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + var res = resolve.sync('./browser_field', { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.end(); +}); + +test('absolute paths', function (t) { + var extensionless = __filename.slice(0, -path.extname(__filename).length); + + t.equal( + resolve.sync(__filename), + __filename, + 'absolute path to this file resolves' + ); + t.equal( + resolve.sync(__filename), + require.resolve(__filename), + 'absolute path to this file: resolve.sync === require.resolve' + ); + + t.equal( + resolve.sync(extensionless), + __filename, + 'extensionless absolute path to this file resolves' + ); + t.equal( + resolve.sync(__filename), + require.resolve(__filename), + 'absolute path to this file: resolve.sync === require.resolve' + ); + + t.equal( + resolve.sync(__filename, { basedir: process.cwd() }), + __filename, + 'absolute path to this file with a basedir resolves' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync(__filename, { basedir: process.cwd() }), + require.resolve(__filename, { paths: [process.cwd()] }), + 'absolute path to this file + basedir: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync(extensionless, { basedir: process.cwd() }), + __filename, + 'extensionless absolute path to this file with a basedir resolves' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync(extensionless, { basedir: process.cwd() }), + require.resolve(extensionless, { paths: [process.cwd()] }), + 'extensionless absolute path to this file + basedir: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('malformed package.json', function (t) { + t.plan(5 + (requireResolveSupportsPaths ? 1 : 0)); + + var basedir = path.join(__dirname, 'resolver/malformed_package_json'); + var expected = path.join(basedir, 'index.js'); + + t.equal( + resolve.sync('./index.js', { basedir: basedir }), + expected, + 'malformed package.json is silently ignored' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./index.js', { basedir: basedir }), + require.resolve('./index.js', { paths: [basedir] }), + 'malformed package.json: resolve.sync === require.resolve' + ); + } + + var res1 = resolve.sync( + './index.js', + { + basedir: basedir, + packageFilter: function (pkg, pkgfile, dir) { + t.fail('should not reach here'); + } + } + ); + + t.equal( + res1, + expected, + 'with packageFilter: malformed package.json is silently ignored' + ); + + var res2 = resolve.sync( + './index.js', + { + basedir: basedir, + readPackageSync: function (readFileSync, pkgfile) { + t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path'); + var result = String(readFileSync(pkgfile)); + try { + return JSON.parse(result); + } catch (e) { + t.ok(e instanceof SyntaxError, 'readPackageSync: malformed package.json parses as a syntax error'); + } + } + } + ); + + t.equal( + res2, + expected, + 'with readPackageSync: malformed package.json is silently ignored' + ); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/shadowed_core.js b/node_modules/mathjs/examples/node_modules/resolve/test/shadowed_core.js new file mode 100644 index 0000000..3a5f4fc --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/shadowed_core.js @@ -0,0 +1,54 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('shadowed core modules still return core module', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, 'util'); + }); +}); + +test('shadowed core modules still return core module [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, 'util'); +}); + +test('shadowed core modules return shadow when appending `/`', function (t) { + t.plan(2); + + resolve('util/', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow when appending `/` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util/', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false`', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/shadowed_core/node_modules/util/index.js b/node_modules/mathjs/examples/node_modules/resolve/test/shadowed_core/node_modules/util/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/subdirs.js b/node_modules/mathjs/examples/node_modules/resolve/test/subdirs.js new file mode 100644 index 0000000..b7b8450 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/subdirs.js @@ -0,0 +1,13 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('subdirs', function (t) { + t.plan(2); + + var dir = path.join(__dirname, '/subdirs'); + resolve('a/b/c/x.json', { basedir: dir }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(dir, 'node_modules/a/b/c/x.json')); + }); +}); diff --git a/node_modules/mathjs/examples/node_modules/resolve/test/symlinks.js b/node_modules/mathjs/examples/node_modules/resolve/test/symlinks.js new file mode 100644 index 0000000..35f881a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/resolve/test/symlinks.js @@ -0,0 +1,176 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); +var map = require('array.prototype.map'); +var resolve = require('../'); + +var symlinkDir = path.join(__dirname, 'resolver', 'symlinked', 'symlink'); +var packageDir = path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'package'); +var modADir = path.join(__dirname, 'symlinks', 'source', 'node_modules', 'mod-a'); +var symlinkModADir = path.join(__dirname, 'symlinks', 'dest', 'node_modules', 'mod-a'); +try { + fs.unlinkSync(symlinkDir); +} catch (err) {} +try { + fs.unlinkSync(packageDir); +} catch (err) {} +try { + fs.unlinkSync(modADir); +} catch (err) {} +try { + fs.unlinkSync(symlinkModADir); +} catch (err) {} + +try { + fs.symlinkSync('./_/symlink_target', symlinkDir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, 'resolver', 'symlinked', '_', 'symlink_target') + '\\', symlinkDir, 'junction'); +} +try { + fs.symlinkSync('../../package', packageDir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'package') + '\\', packageDir, 'junction'); +} +try { + fs.symlinkSync('../../source/node_modules/mod-a', symlinkModADir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'source', 'node_modules', 'mod-a') + '\\', symlinkModADir, 'junction'); +} + +test('symlink', function (t) { + t.plan(2); + + resolve('foo', { basedir: symlinkDir, preserveSymlinks: false }, function (err, res, pkg) { + t.error(err); + t.equal(res, path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js')); + }); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.plan(4); + + resolve('foo', { basedir: symlinkDir }, function (err, res, pkg) { + t.ok(err, 'there is an error'); + t.notOk(res, 'no result'); + + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + t.equal( + err && err.message, + 'Cannot find module \'foo\' from \'' + symlinkDir + '\'', + 'can not find nonexistent module' + ); + }); +}); + +test('sync symlink', function (t) { + var start = new Date(); + t.doesNotThrow(function () { + t.equal( + resolve.sync('foo', { basedir: symlinkDir, preserveSymlinks: false }), + path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js') + ); + }); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.throws(function () { + resolve.sync('foo', { basedir: symlinkDir }); + }, /Cannot find module 'foo'/); + t.end(); +}); + +test('sync symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + var fn = resolve.sync('package', { basedir: basedir, preserveSymlinks: false }); + + t.equal(fn, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + t.end(); +}); + +test('async symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + t.plan(2); + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + resolve('package', { basedir: basedir, preserveSymlinks: false }, function (err, result) { + t.notOk(err, 'no error'); + t.equal(result, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + }); +}); + +test('packageFilter', function (t) { + function relative(x) { + return path.relative(__dirname, x); + } + + function testPackageFilter(preserveSymlinks) { + return function (st) { + st.plan('is 1.x' ? 3 : 5); // eslint-disable-line no-constant-condition + + var destMain = 'symlinks/dest/node_modules/mod-a/index.js'; + var destPkg = 'symlinks/dest/node_modules/mod-a/package.json'; + var sourceMain = 'symlinks/source/node_modules/mod-a/index.js'; + var sourcePkg = 'symlinks/source/node_modules/mod-a/package.json'; + var destDir = path.join(__dirname, 'symlinks', 'dest'); + + /* eslint multiline-comment-style: 0 */ + /* v2.x will restore these tests + var packageFilterPath = []; + var actualPath = resolve.sync('mod-a', { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile, dir) { + packageFilterPath.push(pkgfile); + } + }); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'sync: actual path is correct' + ); + st.deepEqual( + map(packageFilterPath, relative), + map(preserveSymlinks ? [destPkg, destPkg] : [sourcePkg, sourcePkg], path.normalize), + 'sync: packageFilter pkgfile arg is correct' + ); + */ + + var asyncPackageFilterPath = []; + resolve( + 'mod-a', + { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile) { + asyncPackageFilterPath.push(pkgfile); + } + }, + function (err, actualPath) { + st.error(err, 'no error'); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'async: actual path is correct' + ); + st.deepEqual( + map(asyncPackageFilterPath, relative), + map( + preserveSymlinks ? [destPkg, destPkg, destPkg] : [sourcePkg, sourcePkg, sourcePkg], + path.normalize + ), + 'async: packageFilter pkgfile arg is correct' + ); + } + ); + }; + } + + t.test('preserveSymlinks: false', testPackageFilter(false)); + + t.test('preserveSymlinks: true', testPackageFilter(true)); + + t.end(); +}); diff --git a/node_modules/mathjs/examples/node_modules/safe-buffer/LICENSE b/node_modules/mathjs/examples/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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. diff --git a/node_modules/mathjs/examples/node_modules/safe-buffer/README.md b/node_modules/mathjs/examples/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/mathjs/examples/node_modules/safe-buffer/index.d.ts b/node_modules/mathjs/examples/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/safe-buffer/index.js b/node_modules/mathjs/examples/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..f8d3ec9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/mathjs/examples/node_modules/safe-buffer/package.json b/node_modules/mathjs/examples/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..f2869e2 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/safe-buffer/package.json @@ -0,0 +1,51 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/LICENSE b/node_modules/mathjs/examples/node_modules/schema-utils/LICENSE new file mode 100644 index 0000000..8c11fc7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +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. diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/README.md b/node_modules/mathjs/examples/node_modules/schema-utils/README.md new file mode 100644 index 0000000..b56ab02 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/README.md @@ -0,0 +1,290 @@ + + +[![npm][npm]][npm-url] +[![node][node]][node-url] +[![deps][deps]][deps-url] +[![tests][tests]][tests-url] +[![coverage][cover]][cover-url] +[![chat][chat]][chat-url] +[![size][size]][size-url] + +# schema-utils + +Package for validate options in loaders and plugins. + +## Getting Started + +To begin, you'll need to install `schema-utils`: + +```console +npm install schema-utils +``` + +## API + +**schema.json** + +```json +{ + "type": "object", + "properties": { + "option": { + "type": "boolean" + } + }, + "additionalProperties": false +} +``` + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { option: true }; +const configuration = { name: "Loader Name/Plugin Name/Name" }; + +validate(schema, options, configuration); +``` + +### `schema` + +Type: `String` + +JSON schema. + +Simple example of schema: + +```json +{ + "type": "object", + "properties": { + "name": { + "description": "This is description of option.", + "type": "string" + } + }, + "additionalProperties": false +} +``` + +### `options` + +Type: `Object` + +Object with options. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, { name: 123 }, { name: "MyPlugin" }); +``` + +### `configuration` + +Allow to configure validator. + +There is an alternative method to configure the `name` and`baseDataPath` options via the `title` property in the schema. +For example: + +```json +{ + "title": "My Loader options", + "type": "object", + "properties": { + "name": { + "description": "This is description of option.", + "type": "string" + } + }, + "additionalProperties": false +} +``` + +The last word used for the `baseDataPath` option, other words used for the `name` option. +Based on the example above the `name` option equals `My Loader`, the `baseDataPath` option equals `options`. + +#### `name` + +Type: `Object` +Default: `"Object"` + +Allow to setup name in validation errors. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, options, { name: "MyPlugin" }); +``` + +```shell +Invalid configuration object. MyPlugin has been initialised using a configuration object that does not match the API schema. + - configuration.optionName should be a integer. +``` + +#### `baseDataPath` + +Type: `String` +Default: `"configuration"` + +Allow to setup base data path in validation errors. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, options, { name: "MyPlugin", baseDataPath: "options" }); +``` + +```shell +Invalid options object. MyPlugin has been initialised using an options object that does not match the API schema. + - options.optionName should be a integer. +``` + +#### `postFormatter` + +Type: `Function` +Default: `undefined` + +Allow to reformat errors. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, options, { + name: "MyPlugin", + postFormatter: (formattedError, error) => { + if (error.keyword === "type") { + return `${formattedError}\nAdditional Information.`; + } + + return formattedError; + }, +}); +``` + +```shell +Invalid options object. MyPlugin has been initialized using an options object that does not match the API schema. + - options.optionName should be a integer. + Additional Information. +``` + +## Examples + +**schema.json** + +```json +{ + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "test": { + "anyOf": [ + { "type": "array" }, + { "type": "string" }, + { "instanceof": "RegExp" } + ] + }, + "transform": { + "instanceof": "Function" + }, + "sourceMap": { + "type": "boolean" + } + }, + "additionalProperties": false +} +``` + +### `Loader` + +```js +import { getOptions } from "loader-utils"; +import { validate } from "schema-utils"; + +import schema from "path/to/schema.json"; + +function loader(src, map) { + const options = getOptions(this); + + validate(schema, options, { + name: "Loader Name", + baseDataPath: "options", + }); + + // Code... +} + +export default loader; +``` + +### `Plugin` + +```js +import { validate } from "schema-utils"; + +import schema from "path/to/schema.json"; + +class Plugin { + constructor(options) { + validate(schema, options, { + name: "Plugin Name", + baseDataPath: "options", + }); + + this.options = options; + } + + apply(compiler) { + // Code... + } +} + +export default Plugin; +``` + +## Contributing + +Please take a moment to read our contributing guidelines if you haven't yet done so. + +[CONTRIBUTING](./.github/CONTRIBUTING.md) + +## License + +[MIT](./LICENSE) + +[npm]: https://img.shields.io/npm/v/schema-utils.svg +[npm-url]: https://npmjs.com/package/schema-utils +[node]: https://img.shields.io/node/v/schema-utils.svg +[node-url]: https://nodejs.org +[deps]: https://david-dm.org/webpack/schema-utils.svg +[deps-url]: https://david-dm.org/webpack/schema-utils +[tests]: https://github.com/webpack/schema-utils/workflows/schema-utils/badge.svg +[tests-url]: https://github.com/webpack/schema-utils/actions +[cover]: https://codecov.io/gh/webpack/schema-utils/branch/master/graph/badge.svg +[cover-url]: https://codecov.io/gh/webpack/schema-utils +[chat]: https://badges.gitter.im/webpack/webpack.svg +[chat-url]: https://gitter.im/webpack/webpack +[size]: https://packagephobia.com/badge?p=schema-utils +[size-url]: https://packagephobia.com/result?p=schema-utils diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/declarations/ValidationError.d.ts b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/ValidationError.d.ts new file mode 100644 index 0000000..55a8a9a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/ValidationError.d.ts @@ -0,0 +1,74 @@ +export default ValidationError; +export type JSONSchema6 = import("json-schema").JSONSchema6; +export type JSONSchema7 = import("json-schema").JSONSchema7; +export type Schema = import("./validate").Schema; +export type ValidationErrorConfiguration = + import("./validate").ValidationErrorConfiguration; +export type PostFormatter = import("./validate").PostFormatter; +export type SchemaUtilErrorObject = import("./validate").SchemaUtilErrorObject; +declare class ValidationError extends Error { + /** + * @param {Array} errors + * @param {Schema} schema + * @param {ValidationErrorConfiguration} configuration + */ + constructor( + errors: Array, + schema: Schema, + configuration?: ValidationErrorConfiguration + ); + /** @type {Array} */ + errors: Array; + /** @type {Schema} */ + schema: Schema; + /** @type {string} */ + headerName: string; + /** @type {string} */ + baseDataPath: string; + /** @type {PostFormatter | null} */ + postFormatter: PostFormatter | null; + /** + * @param {string} path + * @returns {Schema} + */ + getSchemaPart(path: string): Schema; + /** + * @param {Schema} schema + * @param {boolean} logic + * @param {Array} prevSchemas + * @returns {string} + */ + formatSchema( + schema: Schema, + logic?: boolean, + prevSchemas?: Array + ): string; + /** + * @param {Schema=} schemaPart + * @param {(boolean | Array)=} additionalPath + * @param {boolean=} needDot + * @param {boolean=} logic + * @returns {string} + */ + getSchemaPartText( + schemaPart?: Schema | undefined, + additionalPath?: (boolean | Array) | undefined, + needDot?: boolean | undefined, + logic?: boolean | undefined + ): string; + /** + * @param {Schema=} schemaPart + * @returns {string} + */ + getSchemaPartDescription(schemaPart?: Schema | undefined): string; + /** + * @param {SchemaUtilErrorObject} error + * @returns {string} + */ + formatValidationError(error: SchemaUtilErrorObject): string; + /** + * @param {Array} errors + * @returns {string} + */ + formatValidationErrors(errors: Array): string; +} diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/declarations/index.d.ts b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/index.d.ts new file mode 100644 index 0000000..df5ec27 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/index.d.ts @@ -0,0 +1,3 @@ +import { validate } from "./validate"; +import { ValidationError } from "./validate"; +export { validate, ValidationError }; diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts new file mode 100644 index 0000000..0d16689 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts @@ -0,0 +1,10 @@ +export default addAbsolutePathKeyword; +export type Ajv = import("ajv").Ajv; +export type ValidateFunction = import("ajv").ValidateFunction; +export type SchemaUtilErrorObject = import("../validate").SchemaUtilErrorObject; +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ +declare function addAbsolutePathKeyword(ajv: Ajv): Ajv; diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/declarations/util/Range.d.ts b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/util/Range.d.ts new file mode 100644 index 0000000..2ba97fc --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/util/Range.d.ts @@ -0,0 +1,79 @@ +export = Range; +/** + * @typedef {[number, boolean]} RangeValue + */ +/** + * @callback RangeValueCallback + * @param {RangeValue} rangeValue + * @returns {boolean} + */ +declare class Range { + /** + * @param {"left" | "right"} side + * @param {boolean} exclusive + * @returns {">" | ">=" | "<" | "<="} + */ + static getOperator( + side: "left" | "right", + exclusive: boolean + ): ">" | ">=" | "<" | "<="; + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatRight(value: number, logic: boolean, exclusive: boolean): string; + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatLeft(value: number, logic: boolean, exclusive: boolean): string; + /** + * @param {number} start left side value + * @param {number} end right side value + * @param {boolean} startExclusive is range exclusive from left side + * @param {boolean} endExclusive is range exclusive from right side + * @param {boolean} logic is not logic applied + * @returns {string} + */ + static formatRange( + start: number, + end: number, + startExclusive: boolean, + endExclusive: boolean, + logic: boolean + ): string; + /** + * @param {Array} values + * @param {boolean} logic is not logic applied + * @return {RangeValue} computed value and it's exclusive flag + */ + static getRangeValue(values: Array, logic: boolean): RangeValue; + /** @type {Array} */ + _left: Array; + /** @type {Array} */ + _right: Array; + /** + * @param {number} value + * @param {boolean=} exclusive + */ + left(value: number, exclusive?: boolean | undefined): void; + /** + * @param {number} value + * @param {boolean=} exclusive + */ + right(value: number, exclusive?: boolean | undefined): void; + /** + * @param {boolean} logic is not logic applied + * @return {string} "smart" range string representation + */ + format(logic?: boolean): string; +} +declare namespace Range { + export { RangeValue, RangeValueCallback }; +} +type RangeValue = [number, boolean]; +type RangeValueCallback = (rangeValue: RangeValue) => boolean; diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/declarations/util/hints.d.ts b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/util/hints.d.ts new file mode 100644 index 0000000..e43e32a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/util/hints.d.ts @@ -0,0 +1,3 @@ +export function stringHints(schema: Schema, logic: boolean): string[]; +export function numberHints(schema: Schema, logic: boolean): string[]; +export type Schema = import("../validate").Schema; diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/declarations/validate.d.ts b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/validate.d.ts new file mode 100644 index 0000000..a04b6dd --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/declarations/validate.d.ts @@ -0,0 +1,37 @@ +export type JSONSchema4 = import("json-schema").JSONSchema4; +export type JSONSchema6 = import("json-schema").JSONSchema6; +export type JSONSchema7 = import("json-schema").JSONSchema7; +export type ErrorObject = import("ajv").ErrorObject; +export type Extend = { + formatMinimum?: number | undefined; + formatMaximum?: number | undefined; + formatExclusiveMinimum?: boolean | undefined; + formatExclusiveMaximum?: boolean | undefined; + link?: string | undefined; +}; +export type Schema = (JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend; +export type SchemaUtilErrorObject = ErrorObject & { + children?: Array; +}; +export type PostFormatter = ( + formattedError: string, + error: SchemaUtilErrorObject +) => string; +export type ValidationErrorConfiguration = { + name?: string | undefined; + baseDataPath?: string | undefined; + postFormatter?: PostFormatter | undefined; +}; +/** + * @param {Schema} schema + * @param {Array | object} options + * @param {ValidationErrorConfiguration=} configuration + * @returns {void} + */ +export function validate( + schema: Schema, + options: Array | object, + configuration?: ValidationErrorConfiguration | undefined +): void; +import ValidationError from "./ValidationError"; +export { ValidationError }; diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/dist/ValidationError.js b/node_modules/mathjs/examples/node_modules/schema-utils/dist/ValidationError.js new file mode 100644 index 0000000..372dde1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/dist/ValidationError.js @@ -0,0 +1,1271 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +const { + stringHints, + numberHints +} = require("./util/hints"); +/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */ + +/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */ + +/** @typedef {import("./validate").Schema} Schema */ + +/** @typedef {import("./validate").ValidationErrorConfiguration} ValidationErrorConfiguration */ + +/** @typedef {import("./validate").PostFormatter} PostFormatter */ + +/** @typedef {import("./validate").SchemaUtilErrorObject} SchemaUtilErrorObject */ + +/** @enum {number} */ + + +const SPECIFICITY = { + type: 1, + not: 1, + oneOf: 1, + anyOf: 1, + if: 1, + enum: 1, + const: 1, + instanceof: 1, + required: 2, + pattern: 2, + patternRequired: 2, + format: 2, + formatMinimum: 2, + formatMaximum: 2, + minimum: 2, + exclusiveMinimum: 2, + maximum: 2, + exclusiveMaximum: 2, + multipleOf: 2, + uniqueItems: 2, + contains: 2, + minLength: 2, + maxLength: 2, + minItems: 2, + maxItems: 2, + minProperties: 2, + maxProperties: 2, + dependencies: 2, + propertyNames: 2, + additionalItems: 2, + additionalProperties: 2, + absolutePath: 2 +}; +/** + * + * @param {Array} array + * @param {(item: SchemaUtilErrorObject) => number} fn + * @returns {Array} + */ + +function filterMax(array, fn) { + const evaluatedMax = array.reduce((max, item) => Math.max(max, fn(item)), 0); + return array.filter(item => fn(item) === evaluatedMax); +} +/** + * + * @param {Array} children + * @returns {Array} + */ + + +function filterChildren(children) { + let newChildren = children; + newChildren = filterMax(newChildren, + /** + * + * @param {SchemaUtilErrorObject} error + * @returns {number} + */ + error => error.dataPath ? error.dataPath.length : 0); + newChildren = filterMax(newChildren, + /** + * @param {SchemaUtilErrorObject} error + * @returns {number} + */ + error => SPECIFICITY[ + /** @type {keyof typeof SPECIFICITY} */ + error.keyword] || 2); + return newChildren; +} +/** + * Find all children errors + * @param {Array} children + * @param {Array} schemaPaths + * @return {number} returns index of first child + */ + + +function findAllChildren(children, schemaPaths) { + let i = children.length - 1; + + const predicate = + /** + * @param {string} schemaPath + * @returns {boolean} + */ + schemaPath => children[i].schemaPath.indexOf(schemaPath) !== 0; + + while (i > -1 && !schemaPaths.every(predicate)) { + if (children[i].keyword === "anyOf" || children[i].keyword === "oneOf") { + const refs = extractRefs(children[i]); + const childrenStart = findAllChildren(children.slice(0, i), refs.concat(children[i].schemaPath)); + i = childrenStart - 1; + } else { + i -= 1; + } + } + + return i + 1; +} +/** + * Extracts all refs from schema + * @param {SchemaUtilErrorObject} error + * @return {Array} + */ + + +function extractRefs(error) { + const { + schema + } = error; + + if (!Array.isArray(schema)) { + return []; + } + + return schema.map(({ + $ref + }) => $ref).filter(s => s); +} +/** + * Groups children by their first level parent (assuming that error is root) + * @param {Array} children + * @return {Array} + */ + + +function groupChildrenByFirstChild(children) { + const result = []; + let i = children.length - 1; + + while (i > 0) { + const child = children[i]; + + if (child.keyword === "anyOf" || child.keyword === "oneOf") { + const refs = extractRefs(child); + const childrenStart = findAllChildren(children.slice(0, i), refs.concat(child.schemaPath)); + + if (childrenStart !== i) { + result.push(Object.assign({}, child, { + children: children.slice(childrenStart, i) + })); + i = childrenStart; + } else { + result.push(child); + } + } else { + result.push(child); + } + + i -= 1; + } + + if (i === 0) { + result.push(children[i]); + } + + return result.reverse(); +} +/** + * @param {string} str + * @param {string} prefix + * @returns {string} + */ + + +function indent(str, prefix) { + return str.replace(/\n(?!$)/g, `\n${prefix}`); +} +/** + * @param {Schema} schema + * @returns {schema is (Schema & {not: Schema})} + */ + + +function hasNotInSchema(schema) { + return !!schema.not; +} +/** + * @param {Schema} schema + * @return {Schema} + */ + + +function findFirstTypedSchema(schema) { + if (hasNotInSchema(schema)) { + return findFirstTypedSchema(schema.not); + } + + return schema; +} +/** + * @param {Schema} schema + * @return {boolean} + */ + + +function canApplyNot(schema) { + const typedSchema = findFirstTypedSchema(schema); + return likeNumber(typedSchema) || likeInteger(typedSchema) || likeString(typedSchema) || likeNull(typedSchema) || likeBoolean(typedSchema); +} +/** + * @param {any} maybeObj + * @returns {boolean} + */ + + +function isObject(maybeObj) { + return typeof maybeObj === "object" && maybeObj !== null; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeNumber(schema) { + return schema.type === "number" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeInteger(schema) { + return schema.type === "integer" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeString(schema) { + return schema.type === "string" || typeof schema.minLength !== "undefined" || typeof schema.maxLength !== "undefined" || typeof schema.pattern !== "undefined" || typeof schema.format !== "undefined" || typeof schema.formatMinimum !== "undefined" || typeof schema.formatMaximum !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeBoolean(schema) { + return schema.type === "boolean"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeArray(schema) { + return schema.type === "array" || typeof schema.minItems === "number" || typeof schema.maxItems === "number" || typeof schema.uniqueItems !== "undefined" || typeof schema.items !== "undefined" || typeof schema.additionalItems !== "undefined" || typeof schema.contains !== "undefined"; +} +/** + * @param {Schema & {patternRequired?: Array}} schema + * @returns {boolean} + */ + + +function likeObject(schema) { + return schema.type === "object" || typeof schema.minProperties !== "undefined" || typeof schema.maxProperties !== "undefined" || typeof schema.required !== "undefined" || typeof schema.properties !== "undefined" || typeof schema.patternProperties !== "undefined" || typeof schema.additionalProperties !== "undefined" || typeof schema.dependencies !== "undefined" || typeof schema.propertyNames !== "undefined" || typeof schema.patternRequired !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeNull(schema) { + return schema.type === "null"; +} +/** + * @param {string} type + * @returns {string} + */ + + +function getArticle(type) { + if (/^[aeiou]/i.test(type)) { + return "an"; + } + + return "a"; +} +/** + * @param {Schema=} schema + * @returns {string} + */ + + +function getSchemaNonTypes(schema) { + if (!schema) { + return ""; + } + + if (!schema.type) { + if (likeNumber(schema) || likeInteger(schema)) { + return " | should be any non-number"; + } + + if (likeString(schema)) { + return " | should be any non-string"; + } + + if (likeArray(schema)) { + return " | should be any non-array"; + } + + if (likeObject(schema)) { + return " | should be any non-object"; + } + } + + return ""; +} +/** + * @param {Array} hints + * @returns {string} + */ + + +function formatHints(hints) { + return hints.length > 0 ? `(${hints.join(", ")})` : ""; +} +/** + * @param {Schema} schema + * @param {boolean} logic + * @returns {string[]} + */ + + +function getHints(schema, logic) { + if (likeNumber(schema) || likeInteger(schema)) { + return numberHints(schema, logic); + } else if (likeString(schema)) { + return stringHints(schema, logic); + } + + return []; +} + +class ValidationError extends Error { + /** + * @param {Array} errors + * @param {Schema} schema + * @param {ValidationErrorConfiguration} configuration + */ + constructor(errors, schema, configuration = {}) { + super(); + /** @type {string} */ + + this.name = "ValidationError"; + /** @type {Array} */ + + this.errors = errors; + /** @type {Schema} */ + + this.schema = schema; + let headerNameFromSchema; + let baseDataPathFromSchema; + + if (schema.title && (!configuration.name || !configuration.baseDataPath)) { + const splittedTitleFromSchema = schema.title.match(/^(.+) (.+)$/); + + if (splittedTitleFromSchema) { + if (!configuration.name) { + [, headerNameFromSchema] = splittedTitleFromSchema; + } + + if (!configuration.baseDataPath) { + [,, baseDataPathFromSchema] = splittedTitleFromSchema; + } + } + } + /** @type {string} */ + + + this.headerName = configuration.name || headerNameFromSchema || "Object"; + /** @type {string} */ + + this.baseDataPath = configuration.baseDataPath || baseDataPathFromSchema || "configuration"; + /** @type {PostFormatter | null} */ + + this.postFormatter = configuration.postFormatter || null; + const header = `Invalid ${this.baseDataPath} object. ${this.headerName} has been initialized using ${getArticle(this.baseDataPath)} ${this.baseDataPath} object that does not match the API schema.\n`; + /** @type {string} */ + + this.message = `${header}${this.formatValidationErrors(errors)}`; + Error.captureStackTrace(this, this.constructor); + } + /** + * @param {string} path + * @returns {Schema} + */ + + + getSchemaPart(path) { + const newPath = path.split("/"); + let schemaPart = this.schema; + + for (let i = 1; i < newPath.length; i++) { + const inner = schemaPart[ + /** @type {keyof Schema} */ + newPath[i]]; + + if (!inner) { + break; + } + + schemaPart = inner; + } + + return schemaPart; + } + /** + * @param {Schema} schema + * @param {boolean} logic + * @param {Array} prevSchemas + * @returns {string} + */ + + + formatSchema(schema, logic = true, prevSchemas = []) { + let newLogic = logic; + + const formatInnerSchema = + /** + * + * @param {Object} innerSchema + * @param {boolean=} addSelf + * @returns {string} + */ + (innerSchema, addSelf) => { + if (!addSelf) { + return this.formatSchema(innerSchema, newLogic, prevSchemas); + } + + if (prevSchemas.includes(innerSchema)) { + return "(recursive)"; + } + + return this.formatSchema(innerSchema, newLogic, prevSchemas.concat(schema)); + }; + + if (hasNotInSchema(schema) && !likeObject(schema)) { + if (canApplyNot(schema.not)) { + newLogic = !logic; + return formatInnerSchema(schema.not); + } + + const needApplyLogicHere = !schema.not.not; + const prefix = logic ? "" : "non "; + newLogic = !logic; + return needApplyLogicHere ? prefix + formatInnerSchema(schema.not) : formatInnerSchema(schema.not); + } + + if ( + /** @type {Schema & {instanceof: string | Array}} */ + schema.instanceof) { + const { + instanceof: value + } = + /** @type {Schema & {instanceof: string | Array}} */ + schema; + const values = !Array.isArray(value) ? [value] : value; + return values.map( + /** + * @param {string} item + * @returns {string} + */ + item => item === "Function" ? "function" : item).join(" | "); + } + + if (schema.enum) { + return ( + /** @type {Array} */ + schema.enum.map(item => JSON.stringify(item)).join(" | ") + ); + } + + if (typeof schema.const !== "undefined") { + return JSON.stringify(schema.const); + } + + if (schema.oneOf) { + return ( + /** @type {Array} */ + schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ") + ); + } + + if (schema.anyOf) { + return ( + /** @type {Array} */ + schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ") + ); + } + + if (schema.allOf) { + return ( + /** @type {Array} */ + schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ") + ); + } + + if ( + /** @type {JSONSchema7} */ + schema.if) { + const { + if: ifValue, + then: thenValue, + else: elseValue + } = + /** @type {JSONSchema7} */ + schema; + return `${ifValue ? `if ${formatInnerSchema(ifValue)}` : ""}${thenValue ? ` then ${formatInnerSchema(thenValue)}` : ""}${elseValue ? ` else ${formatInnerSchema(elseValue)}` : ""}`; + } + + if (schema.$ref) { + return formatInnerSchema(this.getSchemaPart(schema.$ref), true); + } + + if (likeNumber(schema) || likeInteger(schema)) { + const [type, ...hints] = getHints(schema, logic); + const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; + return logic ? str : hints.length > 0 ? `non-${type} | ${str}` : `non-${type}`; + } + + if (likeString(schema)) { + const [type, ...hints] = getHints(schema, logic); + const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; + return logic ? str : str === "string" ? "non-string" : `non-string | ${str}`; + } + + if (likeBoolean(schema)) { + return `${logic ? "" : "non-"}boolean`; + } + + if (likeArray(schema)) { + // not logic already applied in formatValidationError + newLogic = true; + const hints = []; + + if (typeof schema.minItems === "number") { + hints.push(`should not have fewer than ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`); + } + + if (typeof schema.maxItems === "number") { + hints.push(`should not have more than ${schema.maxItems} item${schema.maxItems > 1 ? "s" : ""}`); + } + + if (schema.uniqueItems) { + hints.push("should not have duplicate items"); + } + + const hasAdditionalItems = typeof schema.additionalItems === "undefined" || Boolean(schema.additionalItems); + let items = ""; + + if (schema.items) { + if (Array.isArray(schema.items) && schema.items.length > 0) { + items = `${ + /** @type {Array} */ + schema.items.map(item => formatInnerSchema(item)).join(", ")}`; + + if (hasAdditionalItems) { + if (schema.additionalItems && isObject(schema.additionalItems) && Object.keys(schema.additionalItems).length > 0) { + hints.push(`additional items should be ${formatInnerSchema(schema.additionalItems)}`); + } + } + } else if (schema.items && Object.keys(schema.items).length > 0) { + // "additionalItems" is ignored + items = `${formatInnerSchema(schema.items)}`; + } else { + // Fallback for empty `items` value + items = "any"; + } + } else { + // "additionalItems" is ignored + items = "any"; + } + + if (schema.contains && Object.keys(schema.contains).length > 0) { + hints.push(`should contains at least one ${this.formatSchema(schema.contains)} item`); + } + + return `[${items}${hasAdditionalItems ? ", ..." : ""}]${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; + } + + if (likeObject(schema)) { + // not logic already applied in formatValidationError + newLogic = true; + const hints = []; + + if (typeof schema.minProperties === "number") { + hints.push(`should not have fewer than ${schema.minProperties} ${schema.minProperties > 1 ? "properties" : "property"}`); + } + + if (typeof schema.maxProperties === "number") { + hints.push(`should not have more than ${schema.maxProperties} ${schema.minProperties && schema.minProperties > 1 ? "properties" : "property"}`); + } + + if (schema.patternProperties && Object.keys(schema.patternProperties).length > 0) { + const patternProperties = Object.keys(schema.patternProperties); + hints.push(`additional property names should match pattern${patternProperties.length > 1 ? "s" : ""} ${patternProperties.map(pattern => JSON.stringify(pattern)).join(" | ")}`); + } + + const properties = schema.properties ? Object.keys(schema.properties) : []; + const required = schema.required ? schema.required : []; + const allProperties = [...new Set( + /** @type {Array} */ + [].concat(required).concat(properties))]; + const objectStructure = allProperties.map(property => { + const isRequired = required.includes(property); // Some properties need quotes, maybe we should add check + // Maybe we should output type of property (`foo: string`), but it is looks very unreadable + + return `${property}${isRequired ? "" : "?"}`; + }).concat(typeof schema.additionalProperties === "undefined" || Boolean(schema.additionalProperties) ? schema.additionalProperties && isObject(schema.additionalProperties) ? [`: ${formatInnerSchema(schema.additionalProperties)}`] : ["…"] : []).join(", "); + const { + dependencies, + propertyNames, + patternRequired + } = + /** @type {Schema & {patternRequired?: Array;}} */ + schema; + + if (dependencies) { + Object.keys(dependencies).forEach(dependencyName => { + const dependency = dependencies[dependencyName]; + + if (Array.isArray(dependency)) { + hints.push(`should have ${dependency.length > 1 ? "properties" : "property"} ${dependency.map(dep => `'${dep}'`).join(", ")} when property '${dependencyName}' is present`); + } else { + hints.push(`should be valid according to the schema ${formatInnerSchema(dependency)} when property '${dependencyName}' is present`); + } + }); + } + + if (propertyNames && Object.keys(propertyNames).length > 0) { + hints.push(`each property name should match format ${JSON.stringify(schema.propertyNames.format)}`); + } + + if (patternRequired && patternRequired.length > 0) { + hints.push(`should have property matching pattern ${patternRequired.map( + /** + * @param {string} item + * @returns {string} + */ + item => JSON.stringify(item))}`); + } + + return `object {${objectStructure ? ` ${objectStructure} ` : ""}}${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; + } + + if (likeNull(schema)) { + return `${logic ? "" : "non-"}null`; + } + + if (Array.isArray(schema.type)) { + // not logic already applied in formatValidationError + return `${schema.type.join(" | ")}`; + } // Fallback for unknown keywords + // not logic already applied in formatValidationError + + /* istanbul ignore next */ + + + return JSON.stringify(schema, null, 2); + } + /** + * @param {Schema=} schemaPart + * @param {(boolean | Array)=} additionalPath + * @param {boolean=} needDot + * @param {boolean=} logic + * @returns {string} + */ + + + getSchemaPartText(schemaPart, additionalPath, needDot = false, logic = true) { + if (!schemaPart) { + return ""; + } + + if (Array.isArray(additionalPath)) { + for (let i = 0; i < additionalPath.length; i++) { + /** @type {Schema | undefined} */ + const inner = schemaPart[ + /** @type {keyof Schema} */ + additionalPath[i]]; + + if (inner) { + // eslint-disable-next-line no-param-reassign + schemaPart = inner; + } else { + break; + } + } + } + + while (schemaPart.$ref) { + // eslint-disable-next-line no-param-reassign + schemaPart = this.getSchemaPart(schemaPart.$ref); + } + + let schemaText = `${this.formatSchema(schemaPart, logic)}${needDot ? "." : ""}`; + + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } + + if (schemaPart.link) { + schemaText += `\n-> Read more at ${schemaPart.link}`; + } + + return schemaText; + } + /** + * @param {Schema=} schemaPart + * @returns {string} + */ + + + getSchemaPartDescription(schemaPart) { + if (!schemaPart) { + return ""; + } + + while (schemaPart.$ref) { + // eslint-disable-next-line no-param-reassign + schemaPart = this.getSchemaPart(schemaPart.$ref); + } + + let schemaText = ""; + + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } + + if (schemaPart.link) { + schemaText += `\n-> Read more at ${schemaPart.link}`; + } + + return schemaText; + } + /** + * @param {SchemaUtilErrorObject} error + * @returns {string} + */ + + + formatValidationError(error) { + const { + keyword, + dataPath: errorDataPath + } = error; + const dataPath = `${this.baseDataPath}${errorDataPath}`; + + switch (keyword) { + case "type": + { + const { + parentSchema, + params + } = error; // eslint-disable-next-line default-case + + switch ( + /** @type {import("ajv").TypeParams} */ + params.type) { + case "number": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + + case "integer": + return `${dataPath} should be an ${this.getSchemaPartText(parentSchema, false, true)}`; + + case "string": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + + case "boolean": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + + case "array": + return `${dataPath} should be an array:\n${this.getSchemaPartText(parentSchema)}`; + + case "object": + return `${dataPath} should be an object:\n${this.getSchemaPartText(parentSchema)}`; + + case "null": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + + default: + return `${dataPath} should be:\n${this.getSchemaPartText(parentSchema)}`; + } + } + + case "instanceof": + { + const { + parentSchema + } = error; + return `${dataPath} should be an instance of ${this.getSchemaPartText(parentSchema, false, true)}`; + } + + case "pattern": + { + const { + params, + parentSchema + } = error; + const { + pattern + } = + /** @type {import("ajv").PatternParams} */ + params; + return `${dataPath} should match pattern ${JSON.stringify(pattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "format": + { + const { + params, + parentSchema + } = error; + const { + format + } = + /** @type {import("ajv").FormatParams} */ + params; + return `${dataPath} should match format ${JSON.stringify(format)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "formatMinimum": + case "formatMaximum": + { + const { + params, + parentSchema + } = error; + const { + comparison, + limit + } = + /** @type {import("ajv").ComparisonParams} */ + params; + return `${dataPath} should be ${comparison} ${JSON.stringify(limit)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "minimum": + case "maximum": + case "exclusiveMinimum": + case "exclusiveMaximum": + { + const { + parentSchema, + params + } = error; + const { + comparison, + limit + } = + /** @type {import("ajv").ComparisonParams} */ + params; + const [, ...hints] = getHints( + /** @type {Schema} */ + parentSchema, true); + + if (hints.length === 0) { + hints.push(`should be ${comparison} ${limit}`); + } + + return `${dataPath} ${hints.join(" ")}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "multipleOf": + { + const { + params, + parentSchema + } = error; + const { + multipleOf + } = + /** @type {import("ajv").MultipleOfParams} */ + params; + return `${dataPath} should be multiple of ${multipleOf}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "patternRequired": + { + const { + params, + parentSchema + } = error; + const { + missingPattern + } = + /** @type {import("ajv").PatternRequiredParams} */ + params; + return `${dataPath} should have property matching pattern ${JSON.stringify(missingPattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "minLength": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + + if (limit === 1) { + return `${dataPath} should be a non-empty string${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + const length = limit - 1; + return `${dataPath} should be longer than ${length} character${length > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "minItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + + if (limit === 1) { + return `${dataPath} should be a non-empty array${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + return `${dataPath} should not have fewer than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "minProperties": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + + if (limit === 1) { + return `${dataPath} should be a non-empty object${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + return `${dataPath} should not have fewer than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "maxLength": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + const max = limit + 1; + return `${dataPath} should be shorter than ${max} character${max > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "maxItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "maxProperties": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "uniqueItems": + { + const { + params, + parentSchema + } = error; + const { + i + } = + /** @type {import("ajv").UniqueItemsParams} */ + params; + return `${dataPath} should not contain the item '${error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "additionalItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}. These items are valid:\n${this.getSchemaPartText(parentSchema)}`; + } + + case "contains": + { + const { + parentSchema + } = error; + return `${dataPath} should contains at least one ${this.getSchemaPartText(parentSchema, ["contains"])} item${getSchemaNonTypes(parentSchema)}.`; + } + + case "required": + { + const { + parentSchema, + params + } = error; + const missingProperty = + /** @type {import("ajv").DependenciesParams} */ + params.missingProperty.replace(/^\./, ""); + const hasProperty = parentSchema && Boolean( + /** @type {Schema} */ + parentSchema.properties && + /** @type {Schema} */ + parentSchema.properties[missingProperty]); + return `${dataPath} misses the property '${missingProperty}'${getSchemaNonTypes(parentSchema)}.${hasProperty ? ` Should be:\n${this.getSchemaPartText(parentSchema, ["properties", missingProperty])}` : this.getSchemaPartDescription(parentSchema)}`; + } + + case "additionalProperties": + { + const { + params, + parentSchema + } = error; + const { + additionalProperty + } = + /** @type {import("ajv").AdditionalPropertiesParams} */ + params; + return `${dataPath} has an unknown property '${additionalProperty}'${getSchemaNonTypes(parentSchema)}. These properties are valid:\n${this.getSchemaPartText(parentSchema)}`; + } + + case "dependencies": + { + const { + params, + parentSchema + } = error; + const { + property, + deps + } = + /** @type {import("ajv").DependenciesParams} */ + params; + const dependencies = deps.split(",").map( + /** + * @param {string} dep + * @returns {string} + */ + dep => `'${dep.trim()}'`).join(", "); + return `${dataPath} should have properties ${dependencies} when property '${property}' is present${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "propertyNames": + { + const { + params, + parentSchema, + schema + } = error; + const { + propertyName + } = + /** @type {import("ajv").PropertyNamesParams} */ + params; + return `${dataPath} property name '${propertyName}' is invalid${getSchemaNonTypes(parentSchema)}. Property names should be match format ${JSON.stringify(schema.format)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "enum": + { + const { + parentSchema + } = error; + + if (parentSchema && + /** @type {Schema} */ + parentSchema.enum && + /** @type {Schema} */ + parentSchema.enum.length === 1) { + return `${dataPath} should be ${this.getSchemaPartText(parentSchema, false, true)}`; + } + + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; + } + + case "const": + { + const { + parentSchema + } = error; + return `${dataPath} should be equal to constant ${this.getSchemaPartText(parentSchema, false, true)}`; + } + + case "not": + { + const postfix = likeObject( + /** @type {Schema} */ + error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : ""; + const schemaOutput = this.getSchemaPartText(error.schema, false, false, false); + + if (canApplyNot(error.schema)) { + return `${dataPath} should be any ${schemaOutput}${postfix}.`; + } + + const { + schema, + parentSchema + } = error; + return `${dataPath} should not be ${this.getSchemaPartText(schema, false, true)}${parentSchema && likeObject(parentSchema) ? `\n${this.getSchemaPartText(parentSchema)}` : ""}`; + } + + case "oneOf": + case "anyOf": + { + const { + parentSchema, + children + } = error; + + if (children && children.length > 0) { + if (error.schema.length === 1) { + const lastChild = children[children.length - 1]; + const remainingChildren = children.slice(0, children.length - 1); + return this.formatValidationError(Object.assign({}, lastChild, { + children: remainingChildren, + parentSchema: Object.assign({}, parentSchema, lastChild.parentSchema) + })); + } + + let filteredChildren = filterChildren(children); + + if (filteredChildren.length === 1) { + return this.formatValidationError(filteredChildren[0]); + } + + filteredChildren = groupChildrenByFirstChild(filteredChildren); + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}\nDetails:\n${filteredChildren.map( + /** + * @param {SchemaUtilErrorObject} nestedError + * @returns {string} + */ + nestedError => ` * ${indent(this.formatValidationError(nestedError), " ")}`).join("\n")}`; + } + + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; + } + + case "if": + { + const { + params, + parentSchema + } = error; + const { + failingKeyword + } = + /** @type {import("ajv").IfParams} */ + params; + return `${dataPath} should match "${failingKeyword}" schema:\n${this.getSchemaPartText(parentSchema, [failingKeyword])}`; + } + + case "absolutePath": + { + const { + message, + parentSchema + } = error; + return `${dataPath}: ${message}${this.getSchemaPartDescription(parentSchema)}`; + } + + /* istanbul ignore next */ + + default: + { + const { + message, + parentSchema + } = error; + const ErrorInJSON = JSON.stringify(error, null, 2); // For `custom`, `false schema`, `$ref` keywords + // Fallback for unknown keywords + + return `${dataPath} ${message} (${ErrorInJSON}).\n${this.getSchemaPartText(parentSchema, false)}`; + } + } + } + /** + * @param {Array} errors + * @returns {string} + */ + + + formatValidationErrors(errors) { + return errors.map(error => { + let formattedError = this.formatValidationError(error); + + if (this.postFormatter) { + formattedError = this.postFormatter(formattedError, error); + } + + return ` - ${indent(formattedError, " ")}`; + }).join("\n"); + } + +} + +var _default = ValidationError; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/dist/index.js b/node_modules/mathjs/examples/node_modules/schema-utils/dist/index.js new file mode 100644 index 0000000..47f4345 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/dist/index.js @@ -0,0 +1,11 @@ +"use strict"; + +const { + validate, + ValidationError +} = require("./validate"); + +module.exports = { + validate, + ValidationError +}; \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/dist/keywords/absolutePath.js b/node_modules/mathjs/examples/node_modules/schema-utils/dist/keywords/absolutePath.js new file mode 100644 index 0000000..0a912da --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/dist/keywords/absolutePath.js @@ -0,0 +1,93 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/** @typedef {import("ajv").Ajv} Ajv */ + +/** @typedef {import("ajv").ValidateFunction} ValidateFunction */ + +/** @typedef {import("../validate").SchemaUtilErrorObject} SchemaUtilErrorObject */ + +/** + * @param {string} message + * @param {object} schema + * @param {string} data + * @returns {SchemaUtilErrorObject} + */ +function errorMessage(message, schema, data) { + return { + // @ts-ignore + // eslint-disable-next-line no-undefined + dataPath: undefined, + // @ts-ignore + // eslint-disable-next-line no-undefined + schemaPath: undefined, + keyword: "absolutePath", + params: { + absolutePath: data + }, + message, + parentSchema: schema + }; +} +/** + * @param {boolean} shouldBeAbsolute + * @param {object} schema + * @param {string} data + * @returns {SchemaUtilErrorObject} + */ + + +function getErrorFor(shouldBeAbsolute, schema, data) { + const message = shouldBeAbsolute ? `The provided value ${JSON.stringify(data)} is not an absolute path!` : `A relative path is expected. However, the provided value ${JSON.stringify(data)} is an absolute path!`; + return errorMessage(message, schema, data); +} +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ + + +function addAbsolutePathKeyword(ajv) { + ajv.addKeyword("absolutePath", { + errors: true, + type: "string", + + compile(schema, parentSchema) { + /** @type {ValidateFunction} */ + const callback = data => { + let passes = true; + const isExclamationMarkPresent = data.includes("!"); + + if (isExclamationMarkPresent) { + callback.errors = [errorMessage(`The provided value ${JSON.stringify(data)} contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.`, parentSchema, data)]; + passes = false; + } // ?:[A-Za-z]:\\ - Windows absolute path + // \\\\ - Windows network absolute path + // \/ - Unix-like OS absolute path + + + const isCorrectAbsolutePath = schema === /^(?:[A-Za-z]:(\\|\/)|\\\\|\/)/.test(data); + + if (!isCorrectAbsolutePath) { + callback.errors = [getErrorFor(schema, parentSchema, data)]; + passes = false; + } + + return passes; + }; + + callback.errors = []; + return callback; + } + + }); + return ajv; +} + +var _default = addAbsolutePathKeyword; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/dist/util/Range.js b/node_modules/mathjs/examples/node_modules/schema-utils/dist/util/Range.js new file mode 100644 index 0000000..14b2431 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/dist/util/Range.js @@ -0,0 +1,163 @@ +"use strict"; + +/** + * @typedef {[number, boolean]} RangeValue + */ + +/** + * @callback RangeValueCallback + * @param {RangeValue} rangeValue + * @returns {boolean} + */ +class Range { + /** + * @param {"left" | "right"} side + * @param {boolean} exclusive + * @returns {">" | ">=" | "<" | "<="} + */ + static getOperator(side, exclusive) { + if (side === "left") { + return exclusive ? ">" : ">="; + } + + return exclusive ? "<" : "<="; + } + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + + + static formatRight(value, logic, exclusive) { + if (logic === false) { + return Range.formatLeft(value, !logic, !exclusive); + } + + return `should be ${Range.getOperator("right", exclusive)} ${value}`; + } + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + + + static formatLeft(value, logic, exclusive) { + if (logic === false) { + return Range.formatRight(value, !logic, !exclusive); + } + + return `should be ${Range.getOperator("left", exclusive)} ${value}`; + } + /** + * @param {number} start left side value + * @param {number} end right side value + * @param {boolean} startExclusive is range exclusive from left side + * @param {boolean} endExclusive is range exclusive from right side + * @param {boolean} logic is not logic applied + * @returns {string} + */ + + + static formatRange(start, end, startExclusive, endExclusive, logic) { + let result = "should be"; + result += ` ${Range.getOperator(logic ? "left" : "right", logic ? startExclusive : !startExclusive)} ${start} `; + result += logic ? "and" : "or"; + result += ` ${Range.getOperator(logic ? "right" : "left", logic ? endExclusive : !endExclusive)} ${end}`; + return result; + } + /** + * @param {Array} values + * @param {boolean} logic is not logic applied + * @return {RangeValue} computed value and it's exclusive flag + */ + + + static getRangeValue(values, logic) { + let minMax = logic ? Infinity : -Infinity; + let j = -1; + const predicate = logic ? + /** @type {RangeValueCallback} */ + ([value]) => value <= minMax : + /** @type {RangeValueCallback} */ + ([value]) => value >= minMax; + + for (let i = 0; i < values.length; i++) { + if (predicate(values[i])) { + [minMax] = values[i]; + j = i; + } + } + + if (j > -1) { + return values[j]; + } + + return [Infinity, true]; + } + + constructor() { + /** @type {Array} */ + this._left = []; + /** @type {Array} */ + + this._right = []; + } + /** + * @param {number} value + * @param {boolean=} exclusive + */ + + + left(value, exclusive = false) { + this._left.push([value, exclusive]); + } + /** + * @param {number} value + * @param {boolean=} exclusive + */ + + + right(value, exclusive = false) { + this._right.push([value, exclusive]); + } + /** + * @param {boolean} logic is not logic applied + * @return {string} "smart" range string representation + */ + + + format(logic = true) { + const [start, leftExclusive] = Range.getRangeValue(this._left, logic); + const [end, rightExclusive] = Range.getRangeValue(this._right, !logic); + + if (!Number.isFinite(start) && !Number.isFinite(end)) { + return ""; + } + + const realStart = leftExclusive ? start + 1 : start; + const realEnd = rightExclusive ? end - 1 : end; // e.g. 5 < x < 7, 5 < x <= 6, 6 <= x <= 6 + + if (realStart === realEnd) { + return `should be ${logic ? "" : "!"}= ${realStart}`; + } // e.g. 4 < x < ∞ + + + if (Number.isFinite(start) && !Number.isFinite(end)) { + return Range.formatLeft(start, logic, leftExclusive); + } // e.g. ∞ < x < 4 + + + if (!Number.isFinite(start) && Number.isFinite(end)) { + return Range.formatRight(end, logic, rightExclusive); + } + + return Range.formatRange(start, end, leftExclusive, rightExclusive, logic); + } + +} + +module.exports = Range; \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/dist/util/hints.js b/node_modules/mathjs/examples/node_modules/schema-utils/dist/util/hints.js new file mode 100644 index 0000000..4317b86 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/dist/util/hints.js @@ -0,0 +1,105 @@ +"use strict"; + +const Range = require("./Range"); +/** @typedef {import("../validate").Schema} Schema */ + +/** + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} + */ + + +module.exports.stringHints = function stringHints(schema, logic) { + const hints = []; + let type = "string"; + const currentSchema = { ...schema + }; + + if (!logic) { + const tmpLength = currentSchema.minLength; + const tmpFormat = currentSchema.formatMinimum; + const tmpExclusive = currentSchema.formatExclusiveMaximum; + currentSchema.minLength = currentSchema.maxLength; + currentSchema.maxLength = tmpLength; + currentSchema.formatMinimum = currentSchema.formatMaximum; + currentSchema.formatMaximum = tmpFormat; + currentSchema.formatExclusiveMaximum = !currentSchema.formatExclusiveMinimum; + currentSchema.formatExclusiveMinimum = !tmpExclusive; + } + + if (typeof currentSchema.minLength === "number") { + if (currentSchema.minLength === 1) { + type = "non-empty string"; + } else { + const length = Math.max(currentSchema.minLength - 1, 0); + hints.push(`should be longer than ${length} character${length > 1 ? "s" : ""}`); + } + } + + if (typeof currentSchema.maxLength === "number") { + if (currentSchema.maxLength === 0) { + type = "empty string"; + } else { + const length = currentSchema.maxLength + 1; + hints.push(`should be shorter than ${length} character${length > 1 ? "s" : ""}`); + } + } + + if (currentSchema.pattern) { + hints.push(`should${logic ? "" : " not"} match pattern ${JSON.stringify(currentSchema.pattern)}`); + } + + if (currentSchema.format) { + hints.push(`should${logic ? "" : " not"} match format ${JSON.stringify(currentSchema.format)}`); + } + + if (currentSchema.formatMinimum) { + hints.push(`should be ${currentSchema.formatExclusiveMinimum ? ">" : ">="} ${JSON.stringify(currentSchema.formatMinimum)}`); + } + + if (currentSchema.formatMaximum) { + hints.push(`should be ${currentSchema.formatExclusiveMaximum ? "<" : "<="} ${JSON.stringify(currentSchema.formatMaximum)}`); + } + + return [type].concat(hints); +}; +/** + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} + */ + + +module.exports.numberHints = function numberHints(schema, logic) { + const hints = [schema.type === "integer" ? "integer" : "number"]; + const range = new Range(); + + if (typeof schema.minimum === "number") { + range.left(schema.minimum); + } + + if (typeof schema.exclusiveMinimum === "number") { + range.left(schema.exclusiveMinimum, true); + } + + if (typeof schema.maximum === "number") { + range.right(schema.maximum); + } + + if (typeof schema.exclusiveMaximum === "number") { + range.right(schema.exclusiveMaximum, true); + } + + const rangeFormat = range.format(logic); + + if (rangeFormat) { + hints.push(rangeFormat); + } + + if (typeof schema.multipleOf === "number") { + hints.push(`should${logic ? "" : " not"} be multiple of ${schema.multipleOf}`); + } + + return hints; +}; \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/dist/validate.js b/node_modules/mathjs/examples/node_modules/schema-utils/dist/validate.js new file mode 100644 index 0000000..8689ef0 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/dist/validate.js @@ -0,0 +1,163 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validate = validate; +Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function () { + return _ValidationError.default; + } +}); + +var _absolutePath = _interopRequireDefault(require("./keywords/absolutePath")); + +var _ValidationError = _interopRequireDefault(require("./ValidationError")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// Use CommonJS require for ajv libs so TypeScript consumers aren't locked into esModuleInterop (see #110). +const Ajv = require("ajv"); + +const ajvKeywords = require("ajv-keywords"); +/** @typedef {import("json-schema").JSONSchema4} JSONSchema4 */ + +/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */ + +/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */ + +/** @typedef {import("ajv").ErrorObject} ErrorObject */ + +/** + * @typedef {Object} Extend + * @property {number=} formatMinimum + * @property {number=} formatMaximum + * @property {boolean=} formatExclusiveMinimum + * @property {boolean=} formatExclusiveMaximum + * @property {string=} link + */ + +/** @typedef {(JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend} Schema */ + +/** @typedef {ErrorObject & { children?: Array}} SchemaUtilErrorObject */ + +/** + * @callback PostFormatter + * @param {string} formattedError + * @param {SchemaUtilErrorObject} error + * @returns {string} + */ + +/** + * @typedef {Object} ValidationErrorConfiguration + * @property {string=} name + * @property {string=} baseDataPath + * @property {PostFormatter=} postFormatter + */ + + +const ajv = new Ajv({ + allErrors: true, + verbose: true, + $data: true +}); +ajvKeywords(ajv, ["instanceof", "formatMinimum", "formatMaximum", "patternRequired"]); // Custom keywords + +(0, _absolutePath.default)(ajv); +/** + * @param {Schema} schema + * @param {Array | object} options + * @param {ValidationErrorConfiguration=} configuration + * @returns {void} + */ + +function validate(schema, options, configuration) { + let errors = []; + + if (Array.isArray(options)) { + errors = Array.from(options, nestedOptions => validateObject(schema, nestedOptions)); + errors.forEach((list, idx) => { + const applyPrefix = + /** + * @param {SchemaUtilErrorObject} error + */ + error => { + // eslint-disable-next-line no-param-reassign + error.dataPath = `[${idx}]${error.dataPath}`; + + if (error.children) { + error.children.forEach(applyPrefix); + } + }; + + list.forEach(applyPrefix); + }); + errors = errors.reduce((arr, items) => { + arr.push(...items); + return arr; + }, []); + } else { + errors = validateObject(schema, options); + } + + if (errors.length > 0) { + throw new _ValidationError.default(errors, schema, configuration); + } +} +/** + * @param {Schema} schema + * @param {Array | object} options + * @returns {Array} + */ + + +function validateObject(schema, options) { + const compiledSchema = ajv.compile(schema); + const valid = compiledSchema(options); + if (valid) return []; + return compiledSchema.errors ? filterErrors(compiledSchema.errors) : []; +} +/** + * @param {Array} errors + * @returns {Array} + */ + + +function filterErrors(errors) { + /** @type {Array} */ + let newErrors = []; + + for (const error of + /** @type {Array} */ + errors) { + const { + dataPath + } = error; + /** @type {Array} */ + + let children = []; + newErrors = newErrors.filter(oldError => { + if (oldError.dataPath.includes(dataPath)) { + if (oldError.children) { + children = children.concat(oldError.children.slice(0)); + } // eslint-disable-next-line no-undefined, no-param-reassign + + + oldError.children = undefined; + children.push(oldError); + return false; + } + + return true; + }); + + if (children.length) { + error.children = children; + } + + newErrors.push(error); + } + + return newErrors; +} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/schema-utils/package.json b/node_modules/mathjs/examples/node_modules/schema-utils/package.json new file mode 100644 index 0000000..912eaba --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/schema-utils/package.json @@ -0,0 +1,78 @@ +{ + "name": "schema-utils", + "version": "3.1.1", + "description": "webpack Validation Utils", + "license": "MIT", + "repository": "webpack/schema-utils", + "author": "webpack Contrib (https://github.com/webpack-contrib)", + "homepage": "https://github.com/webpack/schema-utils", + "bugs": "https://github.com/webpack/schema-utils/issues", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "main": "dist/index.js", + "types": "declarations/index.d.ts", + "engines": { + "node": ">= 10.13.0" + }, + "scripts": { + "start": "npm run build -- -w", + "clean": "del-cli dist declarations", + "prebuild": "npm run clean", + "build:types": "tsc --declaration --emitDeclarationOnly --outDir declarations && prettier \"declarations/**/*.ts\" --write", + "build:code": "cross-env NODE_ENV=production babel src -d dist --copy-files", + "build": "npm-run-all -p \"build:**\"", + "commitlint": "commitlint --from=master", + "security": "npm audit --production", + "fmt:check": "prettier \"{**/*,*}.{js,json,md,yml,css,ts}\" --list-different", + "lint:js": "eslint --cache .", + "lint:types": "tsc --pretty --noEmit", + "lint": "npm-run-all lint:js lint:types fmt:check", + "fmt": "npm run fmt:check -- --write", + "fix:js": "npm run lint:js -- --fix", + "fix": "npm-run-all fix:js fmt", + "test:only": "cross-env NODE_ENV=test jest", + "test:watch": "npm run test:only -- --watch", + "test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage", + "pretest": "npm run lint", + "test": "npm run test:coverage", + "prepare": "npm run build && husky install", + "release": "standard-version" + }, + "files": [ + "dist", + "declarations" + ], + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "devDependencies": { + "@babel/cli": "^7.14.3", + "@babel/core": "^7.14.6", + "@babel/preset-env": "^7.14.7", + "@commitlint/cli": "^12.1.4", + "@commitlint/config-conventional": "^12.1.4", + "@webpack-contrib/eslint-config-webpack": "^3.0.0", + "babel-jest": "^27.0.6", + "cross-env": "^7.0.3", + "del": "^6.0.0", + "del-cli": "^3.0.1", + "eslint": "^7.31.0", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-import": "^2.23.4", + "husky": "^6.0.0", + "jest": "^27.0.6", + "lint-staged": "^11.0.1", + "npm-run-all": "^4.1.5", + "prettier": "^2.3.2", + "standard-version": "^9.3.1", + "typescript": "^4.3.5", + "webpack": "^5.45.1" + }, + "keywords": [ + "webpack" + ] +} diff --git a/node_modules/mathjs/examples/node_modules/serialize-javascript/LICENSE b/node_modules/mathjs/examples/node_modules/serialize-javascript/LICENSE new file mode 100644 index 0000000..263382a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/serialize-javascript/LICENSE @@ -0,0 +1,27 @@ +Copyright 2014 Yahoo! Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the Yahoo! Inc. nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mathjs/examples/node_modules/serialize-javascript/README.md b/node_modules/mathjs/examples/node_modules/serialize-javascript/README.md new file mode 100644 index 0000000..8736fdb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/serialize-javascript/README.md @@ -0,0 +1,142 @@ +Serialize JavaScript +==================== + +Serialize JavaScript to a _superset_ of JSON that includes regular expressions, dates and functions. + +[![npm Version][npm-badge]][npm] +[![Dependency Status][david-badge]][david] +![Test](https://github.com/yahoo/serialize-javascript/workflows/Test/badge.svg) + +## Overview + +The code in this package began its life as an internal module to [express-state][]. To expand its usefulness, it now lives as `serialize-javascript` — an independent package on npm. + +You're probably wondering: **What about `JSON.stringify()`!?** We've found that sometimes we need to serialize JavaScript **functions**, **regexps**, **dates**, **sets** or **maps**. A great example is a web app that uses client-side URL routing where the route definitions are regexps that need to be shared from the server to the client. But this module is also great for communicating between node processes. + +The string returned from this package's single export function is literal JavaScript which can be saved to a `.js` file, or be embedded into an HTML document by making the content of a `' +}); +``` + +The above will produce the following string, HTML-escaped output which is safe to put into an HTML document as it will not cause the inline script element to terminate: + +```js +'{"haxorXSS":"\\u003C\\u002Fscript\\u003E"}' +``` + +> You can pass an optional `unsafe` argument to `serialize()` for straight serialization. + +### Options + +The `serialize()` function accepts an `options` object as its second argument. All options are being defaulted to `undefined`: + +#### `options.space` + +This option is the same as the `space` argument that can be passed to [`JSON.stringify`][JSON.stringify]. It can be used to add whitespace and indentation to the serialized output to make it more readable. + +```js +serialize(obj, {space: 2}); +``` + +#### `options.isJSON` + +This option is a signal to `serialize()` that the object being serialized does not contain any function or regexps values. This enables a hot-path that allows serialization to be over 3x faster. If you're serializing a lot of data, and know its pure JSON, then you can enable this option for a speed-up. + +**Note:** That when using this option, the output will still be escaped to protect against XSS. + +```js +serialize(obj, {isJSON: true}); +``` + +#### `options.unsafe` + +This option is to signal `serialize()` that we want to do a straight conversion, without the XSS protection. This options needs to be explicitly set to `true`. HTML characters and JavaScript line terminators will not be escaped. You will have to roll your own. + +```js +serialize(obj, {unsafe: true}); +``` + +#### `options.ignoreFunction` + +This option is to signal `serialize()` that we do not want serialize JavaScript function. +Just treat function like `JSON.stringify` do, but other features will work as expected. + +```js +serialize(obj, {ignoreFunction: true}); +``` + +## Deserializing + +For some use cases you might also need to deserialize the string. This is explicitly not part of this module. However, you can easily write it yourself: + +```js +function deserialize(serializedJavascript){ + return eval('(' + serializedJavascript + ')'); +} +``` + +**Note:** Don't forget the parentheses around the serialized javascript, as the opening bracket `{` will be considered to be the start of a body. + +## License + +This software is free to use under the Yahoo! Inc. BSD license. +See the [LICENSE file][LICENSE] for license text and copyright information. + + +[npm]: https://www.npmjs.org/package/serialize-javascript +[npm-badge]: https://img.shields.io/npm/v/serialize-javascript.svg?style=flat-square +[david]: https://david-dm.org/yahoo/serialize-javascript +[david-badge]: https://img.shields.io/david/yahoo/serialize-javascript.svg?style=flat-square +[express-state]: https://github.com/yahoo/express-state +[JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify +[LICENSE]: https://github.com/yahoo/serialize-javascript/blob/main/LICENSE diff --git a/node_modules/mathjs/examples/node_modules/serialize-javascript/index.js b/node_modules/mathjs/examples/node_modules/serialize-javascript/index.js new file mode 100644 index 0000000..ab82742 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/serialize-javascript/index.js @@ -0,0 +1,268 @@ +/* +Copyright (c) 2014, Yahoo! Inc. All rights reserved. +Copyrights licensed under the New BSD License. +See the accompanying LICENSE file for terms. +*/ + +'use strict'; + +var randomBytes = require('randombytes'); + +// Generate an internal UID to make the regexp pattern harder to guess. +var UID_LENGTH = 16; +var UID = generateUID(); +var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B|L)-' + UID + '-(\\d+)__@"', 'g'); + +var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g; +var IS_PURE_FUNCTION = /function.*?\(/; +var IS_ARROW_FUNCTION = /.*?=>.*?/; +var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g; + +var RESERVED_SYMBOLS = ['*', 'async']; + +// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their +// Unicode char counterparts which are safe to use in JavaScript strings. +var ESCAPED_CHARS = { + '<' : '\\u003C', + '>' : '\\u003E', + '/' : '\\u002F', + '\u2028': '\\u2028', + '\u2029': '\\u2029' +}; + +function escapeUnsafeChars(unsafeChar) { + return ESCAPED_CHARS[unsafeChar]; +} + +function generateUID() { + var bytes = randomBytes(UID_LENGTH); + var result = ''; + for(var i=0; i arg1+5 + if(IS_ARROW_FUNCTION.test(serializedFn)) { + return serializedFn; + } + + var argsStartsAt = serializedFn.indexOf('('); + var def = serializedFn.substr(0, argsStartsAt) + .trim() + .split(' ') + .filter(function(val) { return val.length > 0 }); + + var nonReservedSymbols = def.filter(function(val) { + return RESERVED_SYMBOLS.indexOf(val) === -1 + }); + + // enhanced literal objects, example: {key() {}} + if(nonReservedSymbols.length > 0) { + return (def.indexOf('async') > -1 ? 'async ' : '') + 'function' + + (def.join('').indexOf('*') > -1 ? '*' : '') + + serializedFn.substr(argsStartsAt); + } + + // arrow functions + return serializedFn; + } + + // Check if the parameter is function + if (options.ignoreFunction && typeof obj === "function") { + obj = undefined; + } + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (obj === undefined) { + return String(obj); + } + + var str; + + // Creates a JSON string representation of the value. + // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args. + if (options.isJSON && !options.space) { + str = JSON.stringify(obj); + } else { + str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space); + } + + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (typeof str !== 'string') { + return String(str); + } + + // Replace unsafe HTML and invalid JavaScript line terminator chars with + // their safe Unicode char counterpart. This _must_ happen before the + // regexps and functions are serialized and added back to the string. + if (options.unsafe !== true) { + str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars); + } + + if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && arrays.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0 && urls.length === 0) { + return str; + } + + // Replaces all occurrences of function, regexp, date, map and set placeholders in the + // JSON string with their string representations. If the original value can + // not be found, then `undefined` is used. + return str.replace(PLACE_HOLDER_REGEXP, function (match, backSlash, type, valueIndex) { + // The placeholder may not be preceded by a backslash. This is to prevent + // replacing things like `"a\"@__R--0__@"` and thus outputting + // invalid JS. + if (backSlash) { + return match; + } + + if (type === 'D') { + return "new Date(\"" + dates[valueIndex].toISOString() + "\")"; + } + + if (type === 'R') { + return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")"; + } + + if (type === 'M') { + return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")"; + } + + if (type === 'S') { + return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")"; + } + + if (type === 'A') { + return "Array.prototype.slice.call(" + serialize(Object.assign({ length: arrays[valueIndex].length }, arrays[valueIndex]), options) + ")"; + } + + if (type === 'U') { + return 'undefined' + } + + if (type === 'I') { + return infinities[valueIndex]; + } + + if (type === 'B') { + return "BigInt(\"" + bigInts[valueIndex] + "\")"; + } + + if (type === 'L') { + return "new URL(\"" + urls[valueIndex].toString() + "\")"; + } + + var fn = functions[valueIndex]; + + return serializeFunc(fn); + }); +} diff --git a/node_modules/mathjs/examples/node_modules/serialize-javascript/package.json b/node_modules/mathjs/examples/node_modules/serialize-javascript/package.json new file mode 100644 index 0000000..caacd5d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/serialize-javascript/package.json @@ -0,0 +1,36 @@ +{ + "name": "serialize-javascript", + "version": "6.0.0", + "description": "Serialize JavaScript to a superset of JSON that includes regular expressions and functions.", + "main": "index.js", + "scripts": { + "benchmark": "node -v && node test/benchmark/serialize.js", + "test": "nyc --reporter=lcov mocha test/unit" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/yahoo/serialize-javascript.git" + }, + "keywords": [ + "serialize", + "serialization", + "javascript", + "js", + "json" + ], + "author": "Eric Ferraiuolo ", + "license": "BSD-3-Clause", + "bugs": { + "url": "https://github.com/yahoo/serialize-javascript/issues" + }, + "homepage": "https://github.com/yahoo/serialize-javascript", + "devDependencies": { + "benchmark": "^2.1.4", + "chai": "^4.1.0", + "mocha": "^9.0.0", + "nyc": "^15.0.0" + }, + "dependencies": { + "randombytes": "^2.1.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/shallow-clone/LICENSE b/node_modules/mathjs/examples/node_modules/shallow-clone/LICENSE new file mode 100644 index 0000000..7cccaf9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shallow-clone/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-present, Jon Schlinkert. + +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. diff --git a/node_modules/mathjs/examples/node_modules/shallow-clone/README.md b/node_modules/mathjs/examples/node_modules/shallow-clone/README.md new file mode 100644 index 0000000..ea7514e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shallow-clone/README.md @@ -0,0 +1,153 @@ +# shallow-clone [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/shallow-clone.svg?style=flat)](https://www.npmjs.com/package/shallow-clone) [![NPM monthly downloads](https://img.shields.io/npm/dm/shallow-clone.svg?style=flat)](https://npmjs.org/package/shallow-clone) [![NPM total downloads](https://img.shields.io/npm/dt/shallow-clone.svg?style=flat)](https://npmjs.org/package/shallow-clone) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/shallow-clone.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/shallow-clone) + +> Creates a shallow clone of any JavaScript value. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save shallow-clone +``` + +## Usage + +```js +const clone = require('shallow-clone'); +``` + +**Supports** + +* array buffers +* arrays +* buffers +* dates +* errors +* float32 arrays +* float64 arrays +* int16 arrays +* int32 arrays +* int8 arrays +* maps +* objects +* primitives +* regular expressions +* sets +* symbols +* uint16 arrays +* uint32 arrays +* uint8 arrays +* uint8clamped arrays + +## Arrays + +By default, only the array itself is cloned (shallow), use [clone-deep](https://github.com/jonschlinkert/clone-deep) if you also need the elements in the array to be cloned. + +```js +const arr = [{ a: 0 }, { b: 1 }]; +const foo = clone(arr); +// foo => [{ 'a': 0 }, { 'b': 1 }] + +// array is cloned +assert(actual === expected); // false + +// array elements are not +assert.deepEqual(actual[0], expected[0]); // true +``` + +## Objects + +Only the object is shallow cloned, use [clone-deep](https://github.com/jonschlinkert/clone-deep) if you also need the values in the object to be cloned. + +```js +console.log(clone({ a: 1, b: 2, c: 3 })); +//=> {a: 1, b: 2, c: 3 } +``` + +## RegExp + +Clones regular expressions and flags, and preserves the `.lastIndex`. + +```js +const regex = clone(/foo/g); //=> /foo/g +// you can manually reset lastIndex if necessary +regex.lastIndex = 0; +``` + +## Primitives + +Simply returns primitives unchanged. + +```js +clone(0); //=> 0 +clone('foo'); //=> 'foo' +``` + +## About + +
    +Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
    + +
    +Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
    + +
    +Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
    + +### Related projects + +You might also be interested in these projects: + +* [assign-deep](https://www.npmjs.com/package/assign-deep): Deeply assign the values of all enumerable-own-properties and symbols from one or more source objects… [more](https://github.com/jonschlinkert/assign-deep) | [homepage](https://github.com/jonschlinkert/assign-deep "Deeply assign the values of all enumerable-own-properties and symbols from one or more source objects to a target object. Returns the target object.") +* [clone-deep](https://www.npmjs.com/package/clone-deep): Recursively (deep) clone JavaScript native types, like Object, Array, RegExp, Date as well as primitives. | [homepage](https://github.com/jonschlinkert/clone-deep "Recursively (deep) clone JavaScript native types, like Object, Array, RegExp, Date as well as primitives.") +* [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") +* [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 20 | [jonschlinkert](https://github.com/jonschlinkert) | +| 2 | [doowb](https://github.com/doowb) | +| 1 | [jakub-g](https://github.com/jakub-g) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 15, 2019._ \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/shallow-clone/index.js b/node_modules/mathjs/examples/node_modules/shallow-clone/index.js new file mode 100644 index 0000000..012746f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shallow-clone/index.js @@ -0,0 +1,83 @@ +/*! + * shallow-clone + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ + +'use strict'; + +const valueOf = Symbol.prototype.valueOf; +const typeOf = require('kind-of'); + +function clone(val, deep) { + switch (typeOf(val)) { + case 'array': + return val.slice(); + case 'object': + return Object.assign({}, val); + case 'date': + return new val.constructor(Number(val)); + case 'map': + return new Map(val); + case 'set': + return new Set(val); + case 'buffer': + return cloneBuffer(val); + case 'symbol': + return cloneSymbol(val); + case 'arraybuffer': + return cloneArrayBuffer(val); + case 'float32array': + case 'float64array': + case 'int16array': + case 'int32array': + case 'int8array': + case 'uint16array': + case 'uint32array': + case 'uint8clampedarray': + case 'uint8array': + return cloneTypedArray(val); + case 'regexp': + return cloneRegExp(val); + case 'error': + return Object.create(val); + default: { + return val; + } + } +} + +function cloneRegExp(val) { + const flags = val.flags !== void 0 ? val.flags : (/\w+$/.exec(val) || void 0); + const re = new val.constructor(val.source, flags); + re.lastIndex = val.lastIndex; + return re; +} + +function cloneArrayBuffer(val) { + const res = new val.constructor(val.byteLength); + new Uint8Array(res).set(new Uint8Array(val)); + return res; +} + +function cloneTypedArray(val, deep) { + return new val.constructor(val.buffer, val.byteOffset, val.length); +} + +function cloneBuffer(val) { + const len = val.length; + const buf = Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : Buffer.from(len); + val.copy(buf); + return buf; +} + +function cloneSymbol(val) { + return valueOf ? Object(valueOf.call(val)) : {}; +} + +/** + * Expose `clone` + */ + +module.exports = clone; diff --git a/node_modules/mathjs/examples/node_modules/shallow-clone/package.json b/node_modules/mathjs/examples/node_modules/shallow-clone/package.json new file mode 100644 index 0000000..91f281c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shallow-clone/package.json @@ -0,0 +1,64 @@ +{ + "name": "shallow-clone", + "description": "Creates a shallow clone of any JavaScript value.", + "version": "3.0.1", + "homepage": "https://github.com/jonschlinkert/shallow-clone", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Brian Woodward (https://twitter.com/doowb)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)" + ], + "repository": "jonschlinkert/shallow-clone", + "bugs": { + "url": "https://github.com/jonschlinkert/shallow-clone/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "mocha" + }, + "dependencies": { + "kind-of": "^6.0.2" + }, + "devDependencies": { + "gulp-format-md": "^2.0.0", + "mocha": "^6.1.3" + }, + "keywords": [ + "array", + "clone", + "copy", + "extend", + "mixin", + "object", + "primitive", + "shallow" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "related": { + "list": [ + "assign-deep", + "clone-deep", + "is-plain-object", + "kind-of" + ] + } + } +} diff --git a/node_modules/mathjs/examples/node_modules/shebang-command/index.js b/node_modules/mathjs/examples/node_modules/shebang-command/index.js new file mode 100644 index 0000000..f35db30 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shebang-command/index.js @@ -0,0 +1,19 @@ +'use strict'; +const shebangRegex = require('shebang-regex'); + +module.exports = (string = '') => { + const match = string.match(shebangRegex); + + if (!match) { + return null; + } + + const [path, argument] = match[0].replace(/#! ?/, '').split(' '); + const binary = path.split('/').pop(); + + if (binary === 'env') { + return argument; + } + + return argument ? `${binary} ${argument}` : binary; +}; diff --git a/node_modules/mathjs/examples/node_modules/shebang-command/license b/node_modules/mathjs/examples/node_modules/shebang-command/license new file mode 100644 index 0000000..db6bc32 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shebang-command/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Kevin Mårtensson (github.com/kevva) + +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. diff --git a/node_modules/mathjs/examples/node_modules/shebang-command/package.json b/node_modules/mathjs/examples/node_modules/shebang-command/package.json new file mode 100644 index 0000000..18e3c04 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shebang-command/package.json @@ -0,0 +1,34 @@ +{ + "name": "shebang-command", + "version": "2.0.0", + "description": "Get the command from a shebang", + "license": "MIT", + "repository": "kevva/shebang-command", + "author": { + "name": "Kevin Mårtensson", + "email": "kevinmartensson@gmail.com", + "url": "github.com/kevva" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "cmd", + "command", + "parse", + "shebang" + ], + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "devDependencies": { + "ava": "^2.3.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/shebang-command/readme.md b/node_modules/mathjs/examples/node_modules/shebang-command/readme.md new file mode 100644 index 0000000..84feb44 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shebang-command/readme.md @@ -0,0 +1,34 @@ +# shebang-command [![Build Status](https://travis-ci.org/kevva/shebang-command.svg?branch=master)](https://travis-ci.org/kevva/shebang-command) + +> Get the command from a shebang + + +## Install + +``` +$ npm install shebang-command +``` + + +## Usage + +```js +const shebangCommand = require('shebang-command'); + +shebangCommand('#!/usr/bin/env node'); +//=> 'node' + +shebangCommand('#!/bin/bash'); +//=> 'bash' +``` + + +## API + +### shebangCommand(string) + +#### string + +Type: `string` + +String containing a shebang. diff --git a/node_modules/mathjs/examples/node_modules/shebang-regex/index.d.ts b/node_modules/mathjs/examples/node_modules/shebang-regex/index.d.ts new file mode 100644 index 0000000..61d034b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shebang-regex/index.d.ts @@ -0,0 +1,22 @@ +/** +Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line. + +@example +``` +import shebangRegex = require('shebang-regex'); + +const string = '#!/usr/bin/env node\nconsole.log("unicorns");'; + +shebangRegex.test(string); +//=> true + +shebangRegex.exec(string)[0]; +//=> '#!/usr/bin/env node' + +shebangRegex.exec(string)[1]; +//=> '/usr/bin/env node' +``` +*/ +declare const shebangRegex: RegExp; + +export = shebangRegex; diff --git a/node_modules/mathjs/examples/node_modules/shebang-regex/index.js b/node_modules/mathjs/examples/node_modules/shebang-regex/index.js new file mode 100644 index 0000000..63fc4a0 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shebang-regex/index.js @@ -0,0 +1,2 @@ +'use strict'; +module.exports = /^#!(.*)/; diff --git a/node_modules/mathjs/examples/node_modules/shebang-regex/license b/node_modules/mathjs/examples/node_modules/shebang-regex/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shebang-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/shebang-regex/package.json b/node_modules/mathjs/examples/node_modules/shebang-regex/package.json new file mode 100644 index 0000000..00ab30f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shebang-regex/package.json @@ -0,0 +1,35 @@ +{ + "name": "shebang-regex", + "version": "3.0.0", + "description": "Regular expression for matching a shebang line", + "license": "MIT", + "repository": "sindresorhus/shebang-regex", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "regex", + "regexp", + "shebang", + "match", + "test", + "line" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/shebang-regex/readme.md b/node_modules/mathjs/examples/node_modules/shebang-regex/readme.md new file mode 100644 index 0000000..5ecf863 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/shebang-regex/readme.md @@ -0,0 +1,33 @@ +# shebang-regex [![Build Status](https://travis-ci.org/sindresorhus/shebang-regex.svg?branch=master)](https://travis-ci.org/sindresorhus/shebang-regex) + +> Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line + + +## Install + +``` +$ npm install shebang-regex +``` + + +## Usage + +```js +const shebangRegex = require('shebang-regex'); + +const string = '#!/usr/bin/env node\nconsole.log("unicorns");'; + +shebangRegex.test(string); +//=> true + +shebangRegex.exec(string)[0]; +//=> '#!/usr/bin/env node' + +shebangRegex.exec(string)[1]; +//=> '/usr/bin/env node' +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/mathjs/examples/node_modules/signal-exit/LICENSE.txt b/node_modules/mathjs/examples/node_modules/signal-exit/LICENSE.txt new file mode 100644 index 0000000..eead04a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/signal-exit/LICENSE.txt @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mathjs/examples/node_modules/signal-exit/README.md b/node_modules/mathjs/examples/node_modules/signal-exit/README.md new file mode 100644 index 0000000..f9c7c00 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/signal-exit/README.md @@ -0,0 +1,39 @@ +# signal-exit + +[![Build Status](https://travis-ci.org/tapjs/signal-exit.png)](https://travis-ci.org/tapjs/signal-exit) +[![Coverage](https://coveralls.io/repos/tapjs/signal-exit/badge.svg?branch=master)](https://coveralls.io/r/tapjs/signal-exit?branch=master) +[![NPM version](https://img.shields.io/npm/v/signal-exit.svg)](https://www.npmjs.com/package/signal-exit) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) + +When you want to fire an event no matter how a process exits: + +* reaching the end of execution. +* explicitly having `process.exit(code)` called. +* having `process.kill(pid, sig)` called. +* receiving a fatal signal from outside the process + +Use `signal-exit`. + +```js +var onExit = require('signal-exit') + +onExit(function (code, signal) { + console.log('process exited!') +}) +``` + +## API + +`var remove = onExit(function (code, signal) {}, options)` + +The return value of the function is a function that will remove the +handler. + +Note that the function *only* fires for signals if the signal would +cause the process to exit. That is, there are no other listeners, and +it is a fatal signal. + +## Options + +* `alwaysLast`: Run this handler after any other signal or exit + handlers. This causes `process.emit` to be monkeypatched. diff --git a/node_modules/mathjs/examples/node_modules/signal-exit/index.js b/node_modules/mathjs/examples/node_modules/signal-exit/index.js new file mode 100644 index 0000000..93703f3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/signal-exit/index.js @@ -0,0 +1,202 @@ +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +// grab a reference to node's real process object right away +var process = global.process + +const processOk = function (process) { + return process && + typeof process === 'object' && + typeof process.removeListener === 'function' && + typeof process.emit === 'function' && + typeof process.reallyExit === 'function' && + typeof process.listeners === 'function' && + typeof process.kill === 'function' && + typeof process.pid === 'number' && + typeof process.on === 'function' +} + +// some kind of non-node environment, just no-op +/* istanbul ignore if */ +if (!processOk(process)) { + module.exports = function () { + return function () {} + } +} else { + var assert = require('assert') + var signals = require('./signals.js') + var isWin = /^win/i.test(process.platform) + + var EE = require('events') + /* istanbul ignore if */ + if (typeof EE !== 'function') { + EE = EE.EventEmitter + } + + var emitter + if (process.__signal_exit_emitter__) { + emitter = process.__signal_exit_emitter__ + } else { + emitter = process.__signal_exit_emitter__ = new EE() + emitter.count = 0 + emitter.emitted = {} + } + + // Because this emitter is a global, we have to check to see if a + // previous version of this library failed to enable infinite listeners. + // I know what you're about to say. But literally everything about + // signal-exit is a compromise with evil. Get used to it. + if (!emitter.infinite) { + emitter.setMaxListeners(Infinity) + emitter.infinite = true + } + + module.exports = function (cb, opts) { + /* istanbul ignore if */ + if (!processOk(global.process)) { + return function () {} + } + assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') + + if (loaded === false) { + load() + } + + var ev = 'exit' + if (opts && opts.alwaysLast) { + ev = 'afterexit' + } + + var remove = function () { + emitter.removeListener(ev, cb) + if (emitter.listeners('exit').length === 0 && + emitter.listeners('afterexit').length === 0) { + unload() + } + } + emitter.on(ev, cb) + + return remove + } + + var unload = function unload () { + if (!loaded || !processOk(global.process)) { + return + } + loaded = false + + signals.forEach(function (sig) { + try { + process.removeListener(sig, sigListeners[sig]) + } catch (er) {} + }) + process.emit = originalProcessEmit + process.reallyExit = originalProcessReallyExit + emitter.count -= 1 + } + module.exports.unload = unload + + var emit = function emit (event, code, signal) { + /* istanbul ignore if */ + if (emitter.emitted[event]) { + return + } + emitter.emitted[event] = true + emitter.emit(event, code, signal) + } + + // { : , ... } + var sigListeners = {} + signals.forEach(function (sig) { + sigListeners[sig] = function listener () { + /* istanbul ignore if */ + if (!processOk(global.process)) { + return + } + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + var listeners = process.listeners(sig) + if (listeners.length === emitter.count) { + unload() + emit('exit', null, sig) + /* istanbul ignore next */ + emit('afterexit', null, sig) + /* istanbul ignore next */ + if (isWin && sig === 'SIGHUP') { + // "SIGHUP" throws an `ENOSYS` error on Windows, + // so use a supported signal instead + sig = 'SIGINT' + } + /* istanbul ignore next */ + process.kill(process.pid, sig) + } + } + }) + + module.exports.signals = function () { + return signals + } + + var loaded = false + + var load = function load () { + if (loaded || !processOk(global.process)) { + return + } + loaded = true + + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + emitter.count += 1 + + signals = signals.filter(function (sig) { + try { + process.on(sig, sigListeners[sig]) + return true + } catch (er) { + return false + } + }) + + process.emit = processEmit + process.reallyExit = processReallyExit + } + module.exports.load = load + + var originalProcessReallyExit = process.reallyExit + var processReallyExit = function processReallyExit (code) { + /* istanbul ignore if */ + if (!processOk(global.process)) { + return + } + process.exitCode = code || /* istanbul ignore next */ 0 + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + /* istanbul ignore next */ + originalProcessReallyExit.call(process, process.exitCode) + } + + var originalProcessEmit = process.emit + var processEmit = function processEmit (ev, arg) { + if (ev === 'exit' && processOk(global.process)) { + /* istanbul ignore else */ + if (arg !== undefined) { + process.exitCode = arg + } + var ret = originalProcessEmit.apply(this, arguments) + /* istanbul ignore next */ + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + /* istanbul ignore next */ + return ret + } else { + return originalProcessEmit.apply(this, arguments) + } + } +} diff --git a/node_modules/mathjs/examples/node_modules/signal-exit/package.json b/node_modules/mathjs/examples/node_modules/signal-exit/package.json new file mode 100644 index 0000000..e1a0031 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/signal-exit/package.json @@ -0,0 +1,38 @@ +{ + "name": "signal-exit", + "version": "3.0.7", + "description": "when you want to fire an event no matter how a process exits.", + "main": "index.js", + "scripts": { + "test": "tap", + "snap": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags" + }, + "files": [ + "index.js", + "signals.js" + ], + "repository": { + "type": "git", + "url": "https://github.com/tapjs/signal-exit.git" + }, + "keywords": [ + "signal", + "exit" + ], + "author": "Ben Coe ", + "license": "ISC", + "bugs": { + "url": "https://github.com/tapjs/signal-exit/issues" + }, + "homepage": "https://github.com/tapjs/signal-exit", + "devDependencies": { + "chai": "^3.5.0", + "coveralls": "^3.1.1", + "nyc": "^15.1.0", + "standard-version": "^9.3.1", + "tap": "^15.1.1" + } +} diff --git a/node_modules/mathjs/examples/node_modules/signal-exit/signals.js b/node_modules/mathjs/examples/node_modules/signal-exit/signals.js new file mode 100644 index 0000000..3bd67a8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/signal-exit/signals.js @@ -0,0 +1,53 @@ +// This is not the set of all possible signals. +// +// It IS, however, the set of all signals that trigger +// an exit on either Linux or BSD systems. Linux is a +// superset of the signal names supported on BSD, and +// the unknown signals just fail to register, so we can +// catch that easily enough. +// +// Don't bother with SIGKILL. It's uncatchable, which +// means that we can't fire any callbacks anyway. +// +// If a user does happen to register a handler on a non- +// fatal signal like SIGWINCH or something, and then +// exit, it'll end up firing `process.emit('exit')`, so +// the handler will be fired anyway. +// +// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised +// artificially, inherently leave the process in a +// state from which it is not safe to try and enter JS +// listeners. +module.exports = [ + 'SIGABRT', + 'SIGALRM', + 'SIGHUP', + 'SIGINT', + 'SIGTERM' +] + +if (process.platform !== 'win32') { + module.exports.push( + 'SIGVTALRM', + 'SIGXCPU', + 'SIGXFSZ', + 'SIGUSR2', + 'SIGTRAP', + 'SIGSYS', + 'SIGQUIT', + 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ) +} + +if (process.platform === 'linux') { + module.exports.push( + 'SIGIO', + 'SIGPOLL', + 'SIGPWR', + 'SIGSTKFLT', + 'SIGUNUSED' + ) +} diff --git a/node_modules/mathjs/examples/node_modules/source-map-support/LICENSE.md b/node_modules/mathjs/examples/node_modules/source-map-support/LICENSE.md new file mode 100644 index 0000000..6247ca9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map-support/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Evan Wallace + +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. diff --git a/node_modules/mathjs/examples/node_modules/source-map-support/README.md b/node_modules/mathjs/examples/node_modules/source-map-support/README.md new file mode 100644 index 0000000..40228b7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map-support/README.md @@ -0,0 +1,284 @@ +# Source Map Support +[![Build Status](https://travis-ci.org/evanw/node-source-map-support.svg?branch=master)](https://travis-ci.org/evanw/node-source-map-support) + +This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process. + +## Installation and Usage + +#### Node support + +``` +$ npm install source-map-support +``` + +Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler): + +``` +//# sourceMappingURL=path/to/source.map +``` + +If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be +respected (e.g. if a file mentions the comment in code, or went through multiple transpilers). +The path should either be absolute or relative to the compiled file. + +From here you have two options. + +##### CLI Usage + +```bash +node -r source-map-support/register compiled.js +``` + +##### Programmatic Usage + +Put the following line at the top of the compiled file. + +```js +require('source-map-support').install(); +``` + +It is also possible to install the source map support directly by +requiring the `register` module which can be handy with ES6: + +```js +import 'source-map-support/register' + +// Instead of: +import sourceMapSupport from 'source-map-support' +sourceMapSupport.install() +``` +Note: if you're using babel-register, it includes source-map-support already. + +It is also very useful with Mocha: + +``` +$ mocha --require source-map-support/register tests/ +``` + +#### Browser support + +This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code. + +This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify. + +```html + + +``` + +This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency: + +```html + +``` + +## Options + +This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer: + +```js +require('source-map-support').install({ + handleUncaughtExceptions: false +}); +``` + +This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access. + +```js +require('source-map-support').install({ + retrieveSourceMap: function(source) { + if (source === 'compiled.js') { + return { + url: 'original.js', + map: fs.readFileSync('compiled.js.map', 'utf8') + }; + } + return null; + } +}); +``` + +The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment. +In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'. + +```js +require('source-map-support').install({ + environment: 'node' +}); +``` + +To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps. + + +```js +require('source-map-support').install({ + hookRequire: true +}); +``` + +This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage. + +## Demos + +#### Basic Demo + +original.js: + +```js +throw new Error('test'); // This is the original code +``` + +compiled.js: + +```js +require('source-map-support').install(); + +throw new Error('test'); // This is the compiled code +// The next line defines the sourceMapping. +//# sourceMappingURL=compiled.js.map +``` + +compiled.js.map: + +```json +{ + "version": 3, + "file": "compiled.js", + "sources": ["original.js"], + "names": [], + "mappings": ";;AAAA,MAAM,IAAI" +} +``` + +Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js): + +``` +$ node compiled.js + +original.js:1 +throw new Error('test'); // This is the original code + ^ +Error: test + at Object. (original.js:1:7) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### TypeScript Demo + +demo.ts: + +```typescript +declare function require(name: string); +require('source-map-support').install(); +class Foo { + constructor() { this.bar(); } + bar() { throw new Error('this is a demo'); } +} +new Foo(); +``` + +Compile and run the file using the TypeScript compiler from the terminal: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('source-map-support').install()` in the code base: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node -r source-map-support/register demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### CoffeeScript Demo + +demo.coffee: + +```coffee +require('source-map-support').install() +foo = -> + bar = -> throw new Error 'this is a demo' + bar() +foo() +``` + +Compile and run the file using the CoffeeScript compiler from the terminal: + +```sh +$ npm install source-map-support coffeescript +$ node_modules/.bin/coffee --map --compile demo.coffee +$ node demo.js + +demo.coffee:3 + bar = -> throw new Error 'this is a demo' + ^ +Error: this is a demo + at bar (demo.coffee:3:22) + at foo (demo.coffee:4:3) + at Object. (demo.coffee:5:1) + at Object. (demo.coffee:1:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) +``` + +## Tests + +This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests: + +* Build the tests using `build.js` +* Launch the HTTP server (`npm run serve-tests`) and visit + * http://127.0.0.1:1336/amd-test + * http://127.0.0.1:1336/browser-test + * http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details). +* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/ + +## License + +This code is available under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/node_modules/mathjs/examples/node_modules/source-map-support/browser-source-map-support.js b/node_modules/mathjs/examples/node_modules/source-map-support/browser-source-map-support.js new file mode 100644 index 0000000..782da50 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map-support/browser-source-map-support.js @@ -0,0 +1,114 @@ +/* + * Support for source maps in V8 stack traces + * https://github.com/evanw/node-source-map-support + */ +/* + The buffer module from node.js, for the browser. + + @author Feross Aboukhadijeh + license MIT +*/ +(this.define||function(R,U){this.sourceMapSupport=U()})("browser-source-map-support",function(R){(function e(C,J,A){function p(f,c){if(!J[f]){if(!C[f]){var l="function"==typeof require&&require;if(!c&&l)return l(f,!0);if(t)return t(f,!0);throw Error("Cannot find module '"+f+"'");}l=J[f]={exports:{}};C[f][0].call(l.exports,function(q){var r=C[f][1][q];return p(r?r:q)},l,l.exports,e,C,J,A)}return J[f].exports}for(var t="function"==typeof require&&require,m=0;mm)return-1;if(58>m)return m-48+52;if(91>m)return m-65;if(123>m)return m-97+26}var t="undefined"!==typeof Uint8Array?Uint8Array:Array;e.toByteArray=function(m){function f(d){q[k++]=d}if(0>16);f((u&65280)>>8);f(u&255)}2===l?(u=p(m.charAt(c))<<2|p(m.charAt(c+1))>>4,f(u&255)):1===l&&(u=p(m.charAt(c))<<10|p(m.charAt(c+1))<<4|p(m.charAt(c+2))>>2,f(u>>8&255),f(u&255));return q};e.fromByteArray=function(m){var f=m.length%3,c="",l;var q=0;for(l=m.length-f;q> +18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);c+=r}switch(f){case 1:r=m[m.length-1];c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<4&63);c+="==";break;case 2:r=(m[m.length-2]<<8)+ +m[m.length-1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),c+="="}return c}})("undefined"===typeof A?this.base64js={}:A)},{}],3:[function(C,J,A){},{}],4:[function(C,J,A){(function(e){var p=Object.prototype.toString,t="function"===typeof e.alloc&&"function"===typeof e.allocUnsafe&&"function"=== +typeof e.from;J.exports=function(m,f,c){if("number"===typeof m)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===p.call(m).slice(8,-1)){f>>>=0;var l=m.byteLength-f;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===c)c=l;else if(c>>>=0,c>l)throw new RangeError("'length' is out of bounds");return t?e.from(m.slice(f,f+c)):new e(new Uint8Array(m.slice(f,f+c)))}if("string"===typeof m){c=f;if("string"!==typeof c||""===c)c="utf8";if(!e.isEncoding(c))throw new TypeError('"encoding" must be a valid string encoding'); +return t?e.from(m,c):new e(m,c)}return t?e.from(m):new e(m)}}).call(this,C("buffer").Buffer)},{buffer:5}],5:[function(C,J,A){function e(a,b,h){if(!(this instanceof e))return new e(a,b,h);var w=typeof a;if("number"===w)var y=0>>0:0;else if("string"===w){if("base64"===b)for(a=(a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")).replace(L,"");0!==a.length%4;)a+="=";y=e.byteLength(a,b)}else if("object"===w&&null!==a)"Buffer"===a.type&&z(a.data)&&(a=a.data),y=0<+a.length?Math.floor(+a.length):0;else throw new TypeError("must start with number, buffer, array or string"); +if(this.length>G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");if(e.TYPED_ARRAY_SUPPORT)var I=e._augment(new Uint8Array(y));else I=this,I.length=y,I._isBuffer=!0;if(e.TYPED_ARRAY_SUPPORT&&"number"===typeof a.byteLength)I._set(a);else{var K=a;if(z(K)||e.isBuffer(K)||K&&"object"===typeof K&&"number"===typeof K.length)if(e.isBuffer(a))for(b=0;ba)throw new RangeError("offset is not uint");if(a+b>h)throw new RangeError("Trying to access beyond buffer length");}function m(a,b,h,w,y,I){if(!e.isBuffer(a))throw new TypeError("buffer must be a Buffer instance");if(b>y||ba.length)throw new TypeError("index out of range"); +}function f(a,b,h,w){0>b&&(b=65535+b+1);for(var y=0,I=Math.min(a.length-h,2);y>>8*(w?y:1-y)}function c(a,b,h,w){0>b&&(b=4294967295+b+1);for(var y=0,I=Math.min(a.length-h,4);y>>8*(w?y:3-y)&255}function l(a,b,h,w,y,I){if(b>y||ba.length)throw new TypeError("index out of range");}function q(a,b,h,w,y){y||l(a,b,h,4,3.4028234663852886E38,-3.4028234663852886E38);v.write(a,b,h,w,23,4);return h+4}function r(a, +b,h,w,y){y||l(a,b,h,8,1.7976931348623157E308,-1.7976931348623157E308);v.write(a,b,h,w,52,8);return h+8}function k(a){for(var b=[],h=0;h=w)b.push(w);else{var y=h;55296<=w&&57343>=w&&h++;w=encodeURIComponent(a.slice(y,h+1)).substr(1).split("%");for(y=0;y=b.length||y>=a.length);y++)b[y+ +h]=a[y];return y}function g(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}}var n=C("base64-js"),v=C("ieee754"),z=C("is-array");A.Buffer=e;A.SlowBuffer=e;A.INSPECT_MAX_BYTES=50;e.poolSize=8192;var G=1073741823;e.TYPED_ARRAY_SUPPORT=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray&&0===(new Uint8Array(1)).subarray(1,1).byteLength}catch(h){return!1}}();e.isBuffer=function(a){return!(null== +a||!a._isBuffer)};e.compare=function(a,b){if(!e.isBuffer(a)||!e.isBuffer(b))throw new TypeError("Arguments must be Buffers");for(var h=a.length,w=b.length,y=0,I=Math.min(h,w);y>>1;break;case "utf8":case "utf-8":h=k(a).length;break;case "base64":h=n.toByteArray(a).length; +break;default:h=a.length}return h};e.prototype.length=void 0;e.prototype.parent=void 0;e.prototype.toString=function(a,b,h){var w=!1;b>>>=0;h=void 0===h||Infinity===h?this.length:h>>>0;a||(a="utf8");0>b&&(b=0);h>this.length&&(h=this.length);if(h<=b)return"";for(;;)switch(a){case "hex":a=b;b=h;h=this.length;if(!a||0>a)a=0;if(!b||0>b||b>h)b=h;w="";for(h=a;hw?"0"+w.toString(16):w.toString(16),w=a+w;return w;case "utf8":case "utf-8":w=a="";for(h=Math.min(this.length,h);b= +this[b]?(a+=g(w)+String.fromCharCode(this[b]),w=""):w+="%"+this[b].toString(16);return a+g(w);case "ascii":return p(this,b,h);case "binary":return p(this,b,h);case "base64":return b=0===b&&h===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(b,h)),b;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=this.slice(b,h);h="";for(a=0;ab&&(a+=" ... "));return""};e.prototype.compare=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return e.compare(this,a)};e.prototype.get=function(a){console.log(".get() is deprecated. Access using array indexes instead."); +return this.readUInt8(a)};e.prototype.set=function(a,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(a,b)};e.prototype.write=function(a,b,h,w){if(isFinite(b))isFinite(h)||(w=h,h=void 0);else{var y=w;w=b;b=h;h=y}b=Number(b)||0;y=this.length-b;h?(h=Number(h),h>y&&(h=y)):h=y;w=String(w||"utf8").toLowerCase();switch(w){case "hex":b=Number(b)||0;w=this.length-b;h?(h=Number(h),h>w&&(h=w)):h=w;w=a.length;if(0!==w%2)throw Error("Invalid hex string");h>w/ +2&&(h=w/2);for(w=0;w>8;K%=256;y.push(K);y.push(w)}a=d(y,this,b,h,2);break;default:throw new TypeError("Unknown encoding: "+ +w);}return a};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};e.prototype.slice=function(a,b){var h=this.length;a=~~a;b=void 0===b?h:~~b;0>a?(a+=h,0>a&&(a=0)):a>h&&(a=h);0>b?(b+=h,0>b&&(b=0)):b>h&&(b=h);b>>=0;h||m(this,a,b,1,255,0);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));this[b]=a;return b+1};e.prototype.writeUInt16LE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeUInt16BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeUInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b+3]=a>>>24,this[b+2]=a>>>16,this[b+1]=a>>>8,this[b]=a):c(this,a,b,!0);return b+4};e.prototype.writeUInt32BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,127,-128);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));0>a&&(a=255+a+1);this[b]=a;return b+1};e.prototype.writeInt16LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeInt16BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8,this[b+2]=a>>>16,this[b+3]=a>>>24):c(this,a,b,!0);return b+4};e.prototype.writeInt32BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);0>a&&(a=4294967295+a+1);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+ +2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeFloatLE=function(a,b,h){return q(this,a,b,!0,h)};e.prototype.writeFloatBE=function(a,b,h){return q(this,a,b,!1,h)};e.prototype.writeDoubleLE=function(a,b,h){return r(this,a,b,!0,h)};e.prototype.writeDoubleBE=function(a,b,h){return r(this,a,b,!1,h)};e.prototype.copy=function(a,b,h,w){h||(h=0);w||0===w||(w=this.length);b||(b=0);if(w!==h&&0!==a.length&&0!==this.length){if(wb||b>=a.length)throw new TypeError("targetStart out of bounds"); +if(0>h||h>=this.length)throw new TypeError("sourceStart out of bounds");if(0>w||w>this.length)throw new TypeError("sourceEnd out of bounds");w>this.length&&(w=this.length);a.length-bw||!e.TYPED_ARRAY_SUPPORT)for(var y=0;yb||b>=this.length)throw new TypeError("start out of bounds"); +if(0>h||h>this.length)throw new TypeError("end out of bounds");if("number"===typeof a)for(;b>1,r=-7;f=t?f-1:0;var k=t?-1:1,u=e[p+f];f+=k;t=u&(1<<-r)-1;u>>=-r;for(r+=c;0>=-r;for(r+=m;0>1,u=23===f?Math.pow(2,-24)-Math.pow(2,-77):0;c=m?0:c-1;var d=m?1:-1,g=0>p||0===p&&0>1/p?1:0;p=Math.abs(p);isNaN(p)||Infinity===p?(p=isNaN(p)?1:0,m=r):(m=Math.floor(Math.log(p)/Math.LN2),1>p*(l=Math.pow(2,-m))&&(m--,l*=2),p=1<=m+k?p+u/l:p+u*Math.pow(2,1-k),2<=p*l&&(m++,l/=2),m+k>=r?(p=0,m=r):1<=m+k?(p=(p*l-1)*Math.pow(2,f),m+=k):(p=p*Math.pow(2,k-1)*Math.pow(2,f),m=0));for(;8<=f;e[t+c]=p&255,c+= +d,p/=256,f-=8);m=m<z?[]:n.slice(v,z-v+1)}c=A.resolve(c).substr(1);l=A.resolve(l).substr(1); +for(var r=q(c.split("/")),k=q(l.split("/")),u=Math.min(r.length,k.length),d=u,g=0;gl&&(l=c.length+l);return c.substr(l,q)}}).call(this,C("g5I+bs"))},{"g5I+bs":9}],9:[function(C,J,A){function e(){}C=J.exports={};C.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(t){return window.setImmediate(t)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var p=[];window.addEventListener("message",function(t){var m=t.source;m!==window&&null!== +m||"process-tick"!==t.data||(t.stopPropagation(),0p?(-p<<1)+1:p<<1;do p=m&31,m>>>=5,0=f)throw Error("Expected more digits in base 64 VLQ value.");var q=e.decode(p.charCodeAt(t++));if(-1===q)throw Error("Invalid base64 digit: "+p.charAt(t-1));var r=!!(q&32);q&=31;c+=q<>1;m.value=1===(c&1)?-p:p;m.rest=t}},{"./base64":12}],12:[function(C, +J,A){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");A.encode=function(p){if(0<=p&&p=p?p-65:97<=p&&122>=p?p-97+26:48<=p&&57>=p?p-48+52:43==p?62:47==p?63:-1}},{}],13:[function(C,J,A){function e(p,t,m,f,c,l){var q=Math.floor((t-p)/2)+p,r=c(m,f[q],!0);return 0===r?q:0p?-1:p}A.GREATEST_LOWER_BOUND=1;A.LEAST_UPPER_BOUND=2;A.search=function(p,t,m,f){if(0===t.length)return-1;p=e(-1,t.length,p,t,m,f||A.GREATEST_LOWER_BOUND);if(0>p)return-1;for(;0<=p-1&&0===m(t[p],t[p-1],!0);)--p;return p}},{}],14:[function(C,J,A){function e(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var p=C("./util");e.prototype.unsortedForEach=function(t,m){this._array.forEach(t,m)};e.prototype.add=function(t){var m=this._last,f=m.generatedLine, +c=t.generatedLine,l=m.generatedColumn,q=t.generatedColumn;c>f||c==f&&q>=l||0>=p.compareByGeneratedPositionsInflated(m,t)?this._last=t:this._sorted=!1;this._array.push(t)};e.prototype.toArray=function(){this._sorted||(this._array.sort(p.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};A.MappingList=e},{"./util":19}],15:[function(C,J,A){function e(t,m,f){var c=t[m];t[m]=t[f];t[f]=c}function p(t,m,f,c){if(f=m(t[r],q)&&(l+=1,e(t,l,r));e(t,l+1,r);l+=1;p(t,m,f,l-1);p(t,m,l+1,c)}}A.quickSort=function(t,m){p(t,m,0,t.length-1)}},{}],16:[function(C,J,A){function e(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));return null!=d.sections?new m(d,u):new p(d,u)}function p(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version"),n=f.getArg(d,"sources"),v=f.getArg(d,"names",[]),z=f.getArg(d,"sourceRoot",null),G=f.getArg(d,"sourcesContent",null),D=f.getArg(d, +"mappings");d=f.getArg(d,"file",null);if(g!=this._version)throw Error("Unsupported version: "+g);z&&(z=f.normalize(z));n=n.map(String).map(f.normalize).map(function(L){return z&&f.isAbsolute(z)&&f.isAbsolute(L)?f.relative(z,L):L});this._names=l.fromArray(v.map(String),!0);this._sources=l.fromArray(n,!0);this.sourceRoot=z;this.sourcesContent=G;this._mappings=D;this._sourceMapURL=u;this.file=d}function t(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source= +null}function m(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version");d=f.getArg(d,"sections");if(g!=this._version)throw Error("Unsupported version: "+g);this._sources=new l;this._names=new l;var n={line:-1,column:0};this._sections=d.map(function(v){if(v.url)throw Error("Support for url field in sections not implemented.");var z=f.getArg(v,"offset"),G=f.getArg(z,"line"),D=f.getArg(z,"column");if(G=k[d])throw new TypeError("Line must be greater than or equal to 1, got "+ +k[d]);if(0>k[g])throw new TypeError("Column must be greater than or equal to 0, got "+k[g]);return c.search(k,u,n,v)};p.prototype.computeColumnSpans=function(){for(var k=0;k=this._sources.size()&&!this.sourcesContent.some(function(k){return null==k}):!1};p.prototype.sourceContentFor=function(k,u){if(!this.sourcesContent)return null;var d=k;null!=this.sourceRoot&&(d=f.relative(this.sourceRoot,d));if(this._sources.has(d))return this.sourcesContent[this._sources.indexOf(d)]; +var g=this.sources,n;for(n=0;n +g||95!==d.charCodeAt(g-1)||95!==d.charCodeAt(g-2)||111!==d.charCodeAt(g-3)||116!==d.charCodeAt(g-4)||111!==d.charCodeAt(g-5)||114!==d.charCodeAt(g-6)||112!==d.charCodeAt(g-7)||95!==d.charCodeAt(g-8)||95!==d.charCodeAt(g-9))return!1;for(g-=10;0<=g;g--)if(36!==d.charCodeAt(g))return!1;return!0}function r(d,g){return d===g?0:null===d?1:null===g?-1:d>g?1:-1}A.getArg=function(d,g,n){if(g in d)return d[g];if(3===arguments.length)return n;throw Error('"'+g+'" is a required argument.');};var k=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/, +u=/^data:.+,.+$/;A.urlParse=e;A.urlGenerate=p;A.normalize=t;A.join=m;A.isAbsolute=function(d){return"/"===d.charAt(0)||k.test(d)};A.relative=function(d,g){""===d&&(d=".");d=d.replace(/\/$/,"");for(var n=0;0!==g.indexOf(d+"/");){var v=d.lastIndexOf("/");if(0>v)return g;d=d.slice(0,v);if(d.match(/^([^\/]+:\/)?\/*$/))return g;++n}return Array(n+1).join("../")+g.substr(d.length+1)};C=!("__proto__"in Object.create(null));A.toSetString=C?f:c;A.fromSetString=C?f:l;A.compareByOriginalPositions=function(d, +g,n){var v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;if(0!==v||n)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v)return v;v=d.generatedLine-g.generatedLine;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsDeflated=function(d,g,n){var v=d.generatedLine-g.generatedLine;if(0!==v)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v||n)return v;v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine- +g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsInflated=function(d,g){var n=d.generatedLine-g.generatedLine;if(0!==n)return n;n=d.generatedColumn-g.generatedColumn;if(0!==n)return n;n=r(d.source,g.source);if(0!==n)return n;n=d.originalLine-g.originalLine;if(0!==n)return n;n=d.originalColumn-g.originalColumn;return 0!==n?n:r(d.name,g.name)};A.parseSourceMapInput=function(d){return JSON.parse(d.replace(/^\)]}'[^\n]*\n/, +""))};A.computeSourceURL=function(d,g,n){g=g||"";d&&("/"!==d[d.length-1]&&"/"!==g[0]&&(d+="/"),g=d+g);if(n){d=e(n);if(!d)throw Error("sourceMapURL could not be parsed");d.path&&(n=d.path.lastIndexOf("/"),0<=n&&(d.path=d.path.substring(0,n+1)));g=m(p(d),g)}return t(g)}},{}],20:[function(C,J,A){A.SourceMapGenerator=C("./lib/source-map-generator").SourceMapGenerator;A.SourceMapConsumer=C("./lib/source-map-consumer").SourceMapConsumer;A.SourceNode=C("./lib/source-node").SourceNode},{"./lib/source-map-consumer":16, +"./lib/source-map-generator":17,"./lib/source-node":18}],21:[function(C,J,A){(function(e){function p(){return"browser"===a?!0:"node"===a?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function t(x){return function(B){for(var F=0;F";B=this.getLineNumber();null!=B&&(x+=":"+B,(B= +this.getColumnNumber())&&(x+=":"+B))}B="";var F=this.getFunctionName(),E=!0,H=this.isConstructor();if(this.isToplevel()||H)H?B+="new "+(F||""):F?B+=F:(B+=x,E=!1);else{H=this.getTypeName();"[object Object]"===H&&(H="null");var M=this.getMethodName();F?(H&&0!=F.indexOf(H)&&(B+=H+"."),B+=F,M&&F.indexOf("."+M)!=F.length-M.length-1&&(B+=" [as "+M+"]")):B+=H+"."+(M||"")}E&&(B+=" ("+x+")");return B}function q(x){var B={};Object.getOwnPropertyNames(Object.getPrototypeOf(x)).forEach(function(F){B[F]= +/^(?:is|get)/.test(F)?function(){return x[F].call(x)}:x[F]});B.toString=l;return B}function r(x,B){void 0===B&&(B={nextPosition:null,curPosition:null});if(x.isNative())return B.curPosition=null,x;var F=x.getFileName()||x.getScriptNameOrSourceURL();if(F){var E=x.getLineNumber(),H=x.getColumnNumber()-1,M=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/,S=M.test;var V="object"===typeof e&&null!==e?e.version:"";M=S.call(M,V)?0:62;1===E&&H>M&&!p()&&!x.isEval()&&(H-=M);var O= +f({source:F,line:E,column:H});B.curPosition=O;x=q(x);var T=x.getFunctionName;x.getFunctionName=function(){return null==B.nextPosition?T():B.nextPosition.name||T()};x.getFileName=function(){return O.source};x.getLineNumber=function(){return O.line};x.getColumnNumber=function(){return O.column+1};x.getScriptNameOrSourceURL=function(){return O.source};return x}var Q=x.isEval()&&x.getEvalOrigin();Q&&(Q=c(Q),x=q(x),x.getEvalOrigin=function(){return Q});return x}function k(x,B){L&&(b={},h={});for(var F= +(x.name||"Error")+": "+(x.message||""),E={nextPosition:null,curPosition:null},H=[],M=B.length-1;0<=M;M--)H.push("\n at "+r(B[M],E)),E.nextPosition=E.curPosition;E.curPosition=E.nextPosition=null;return F+H.reverse().join("")}function u(x){var B=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(x.stack);if(B){x=B[1];var F=+B[2];B=+B[3];var E=b[x];if(!E&&v&&v.existsSync(x))try{E=v.readFileSync(x,"utf8")}catch(H){E=""}if(E&&(E=E.split(/(?:\r\n|\r|\n)/)[F-1]))return x+":"+F+"\n"+E+"\n"+Array(B).join(" ")+ +"^"}return null}function d(){var x=e.emit;e.emit=function(B){if("uncaughtException"===B){var F=arguments[1]&&arguments[1].stack,E=0 C:/dir/file + '/'; // file:///root-dir/file -> /root-dir/file + }); + } + if (path in fileContentsCache) { + return fileContentsCache[path]; + } + + var contents = ''; + try { + if (!fs) { + // Use SJAX if we are in the browser + var xhr = new XMLHttpRequest(); + xhr.open('GET', path, /** async */ false); + xhr.send(null); + if (xhr.readyState === 4 && xhr.status === 200) { + contents = xhr.responseText; + } + } else if (fs.existsSync(path)) { + // Otherwise, use the filesystem + contents = fs.readFileSync(path, 'utf8'); + } + } catch (er) { + /* ignore any errors */ + } + + return fileContentsCache[path] = contents; +}); + +// Support URLs relative to a directory, but be careful about a protocol prefix +// in case we are in the browser (i.e. directories may start with "http://" or "file:///") +function supportRelativeURL(file, url) { + if (!file) return url; + var dir = path.dirname(file); + var match = /^\w+:\/\/[^\/]*/.exec(dir); + var protocol = match ? match[0] : ''; + var startPath = dir.slice(protocol.length); + if (protocol && /^\/\w\:/.test(startPath)) { + // handle file:///C:/ paths + protocol += '/'; + return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/'); + } + return protocol + path.resolve(dir.slice(protocol.length), url); +} + +function retrieveSourceMapURL(source) { + var fileData; + + if (isInBrowser()) { + try { + var xhr = new XMLHttpRequest(); + xhr.open('GET', source, false); + xhr.send(null); + fileData = xhr.readyState === 4 ? xhr.responseText : null; + + // Support providing a sourceMappingURL via the SourceMap header + var sourceMapHeader = xhr.getResponseHeader("SourceMap") || + xhr.getResponseHeader("X-SourceMap"); + if (sourceMapHeader) { + return sourceMapHeader; + } + } catch (e) { + } + } + + // Get the URL of the source map + fileData = retrieveFile(source); + var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; + // Keep executing the search to find the *last* sourceMappingURL to avoid + // picking up sourceMappingURLs from comments, strings, etc. + var lastMatch, match; + while (match = re.exec(fileData)) lastMatch = match; + if (!lastMatch) return null; + return lastMatch[1]; +}; + +// Can be overridden by the retrieveSourceMap option to install. Takes a +// generated source filename; returns a {map, optional url} object, or null if +// there is no source map. The map field may be either a string or the parsed +// JSON object (ie, it must be a valid argument to the SourceMapConsumer +// constructor). +var retrieveSourceMap = handlerExec(retrieveMapHandlers); +retrieveMapHandlers.push(function(source) { + var sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) return null; + + // Read the contents of the source map + var sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + // Support source map URL as a data url + var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1); + sourceMapData = bufferFrom(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + // Support source map URLs relative to the source URL + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(sourceMappingURL); + } + + if (!sourceMapData) { + return null; + } + + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); + +function mapSourcePosition(position) { + var sourceMap = sourceMapCache[position.source]; + if (!sourceMap) { + // Call the (overrideable) retrieveSourceMap function to get the source map. + var urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap) { + sourceMap = sourceMapCache[position.source] = { + url: urlAndMap.url, + map: new SourceMapConsumer(urlAndMap.map) + }; + + // Load all sources stored inline with the source map into the file cache + // to pretend like they are already loaded. They may not exist on disk. + if (sourceMap.map.sourcesContent) { + sourceMap.map.sources.forEach(function(source, i) { + var contents = sourceMap.map.sourcesContent[i]; + if (contents) { + var url = supportRelativeURL(sourceMap.url, source); + fileContentsCache[url] = contents; + } + }); + } + } else { + sourceMap = sourceMapCache[position.source] = { + url: null, + map: null + }; + } + } + + // Resolve the source URL relative to the URL of the source map + if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') { + var originalPosition = sourceMap.map.originalPositionFor(position); + + // Only return the original position if a matching line was found. If no + // matching line is found then we return position instead, which will cause + // the stack trace to print the path and line for the compiled file. It is + // better to give a precise location in the compiled file than a vague + // location in the original file. + if (originalPosition.source !== null) { + originalPosition.source = supportRelativeURL( + sourceMap.url, originalPosition.source); + return originalPosition; + } + } + + return position; +} + +// Parses code generated by FormatEvalOrigin(), a function inside V8: +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +function mapEvalOrigin(origin) { + // Most eval() calls are in this format + var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + var position = mapSourcePosition({ + source: match[2], + line: +match[3], + column: match[4] - 1 + }); + return 'eval at ' + match[1] + ' (' + position.source + ':' + + position.line + ':' + (position.column + 1) + ')'; + } + + // Parse nested eval() calls using recursion + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) { + return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; + } + + // Make sure we still return useful information if we didn't find anything + return origin; +} + +// This is copied almost verbatim from the V8 source code at +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The +// implementation of wrapCallSite() used to just forward to the actual source +// code of CallSite.prototype.toString but unfortunately a new release of V8 +// did something to the prototype chain and broke the shim. The only fix I +// could find was copy/paste. +function CallSiteToString() { + var fileName; + var fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; // Expecting source position to follow. + } + + if (fileName) { + fileLocation += fileName; + } else { + // Source code does not originate from a file and is not native, but we + // can still get the source position inside the source string, e.g. in + // an eval string. + fileLocation += ""; + } + var lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += ":" + lineNumber; + var columnNumber = this.getColumnNumber(); + if (columnNumber) { + fileLocation += ":" + columnNumber; + } + } + } + + var line = ""; + var functionName = this.getFunctionName(); + var addSuffix = true; + var isConstructor = this.isConstructor(); + var isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + var typeName = this.getTypeName(); + // Fixes shim to be backward compatable with Node v0 to v4 + if (typeName === "[object Object]") { + typeName = "null"; + } + var methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) != 0) { + line += typeName + "."; + } + line += functionName; + if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { + line += " [as " + methodName + "]"; + } + } else { + line += typeName + "." + (methodName || ""); + } + } else if (isConstructor) { + line += "new " + (functionName || ""); + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) { + line += " (" + fileLocation + ")"; + } + return line; +} + +function cloneCallSite(frame) { + var object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { + object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; + }); + object.toString = CallSiteToString; + return object; +} + +function wrapCallSite(frame, state) { + // provides interface backward compatibility + if (state === undefined) { + state = { nextPosition: null, curPosition: null } + } + if(frame.isNative()) { + state.curPosition = null; + return frame; + } + + // Most call sites will return the source file from getFileName(), but code + // passed to eval() ending in "//# sourceURL=..." will return the source file + // from getScriptNameOrSourceURL() instead + var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + var line = frame.getLineNumber(); + var column = frame.getColumnNumber() - 1; + + // Fix position in Node where some (internal) code is prepended. + // See https://github.com/evanw/node-source-map-support/issues/36 + // Header removed in node at ^10.16 || >=11.11.0 + // v11 is not an LTS candidate, we can just test the one version with it. + // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11 + var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/; + var headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62; + if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { + column -= headerLength; + } + + var position = mapSourcePosition({ + source: source, + line: line, + column: column + }); + state.curPosition = position; + frame = cloneCallSite(frame); + var originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { + if (state.nextPosition == null) { + return originalFunctionName(); + } + return state.nextPosition.name || originalFunctionName(); + }; + frame.getFileName = function() { return position.source; }; + frame.getLineNumber = function() { return position.line; }; + frame.getColumnNumber = function() { return position.column + 1; }; + frame.getScriptNameOrSourceURL = function() { return position.source; }; + return frame; + } + + // Code called using eval() needs special handling + var origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { return origin; }; + return frame; + } + + // If we get here then we were unable to change the source position + return frame; +} + +// This function is part of the V8 stack trace API, for more info see: +// https://v8.dev/docs/stack-trace-api +function prepareStackTrace(error, stack) { + if (emptyCacheBetweenOperations) { + fileContentsCache = {}; + sourceMapCache = {}; + } + + var name = error.name || 'Error'; + var message = error.message || ''; + var errorString = name + ": " + message; + + var state = { nextPosition: null, curPosition: null }; + var processedStack = []; + for (var i = stack.length - 1; i >= 0; i--) { + processedStack.push('\n at ' + wrapCallSite(stack[i], state)); + state.nextPosition = state.curPosition; + } + state.curPosition = state.nextPosition = null; + return errorString + processedStack.reverse().join(''); +} + +// Generate position and snippet of original source with pointer +function getErrorSource(error) { + var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); + if (match) { + var source = match[1]; + var line = +match[2]; + var column = +match[3]; + + // Support the inline sourceContents inside the source map + var contents = fileContentsCache[source]; + + // Support files on disk + if (!contents && fs && fs.existsSync(source)) { + try { + contents = fs.readFileSync(source, 'utf8'); + } catch (er) { + contents = ''; + } + } + + // Format the line from the original source code like node does + if (contents) { + var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; + if (code) { + return source + ':' + line + '\n' + code + '\n' + + new Array(column).join(' ') + '^'; + } + } + } + return null; +} + +function printErrorAndExit (error) { + var source = getErrorSource(error); + + // Ensure error is printed synchronously and not truncated + var stderr = globalProcessStderr(); + if (stderr && stderr._handle && stderr._handle.setBlocking) { + stderr._handle.setBlocking(true); + } + + if (source) { + console.error(); + console.error(source); + } + + console.error(error.stack); + globalProcessExit(1); +} + +function shimEmitUncaughtException () { + var origEmit = process.emit; + + process.emit = function (type) { + if (type === 'uncaughtException') { + var hasStack = (arguments[1] && arguments[1].stack); + var hasListeners = (this.listeners(type).length > 0); + + if (hasStack && !hasListeners) { + return printErrorAndExit(arguments[1]); + } + } + + return origEmit.apply(this, arguments); + }; +} + +var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0); +var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0); + +exports.wrapCallSite = wrapCallSite; +exports.getErrorSource = getErrorSource; +exports.mapSourcePosition = mapSourcePosition; +exports.retrieveSourceMap = retrieveSourceMap; + +exports.install = function(options) { + options = options || {}; + + if (options.environment) { + environment = options.environment; + if (["node", "browser", "auto"].indexOf(environment) === -1) { + throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}") + } + } + + // Allow sources to be found by methods other than reading the files + // directly from disk. + if (options.retrieveFile) { + if (options.overrideRetrieveFile) { + retrieveFileHandlers.length = 0; + } + + retrieveFileHandlers.unshift(options.retrieveFile); + } + + // Allow source maps to be found by methods other than reading the files + // directly from disk. + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) { + retrieveMapHandlers.length = 0; + } + + retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + + // Support runtime transpilers that include inline source maps + if (options.hookRequire && !isInBrowser()) { + // Use dynamicRequire to avoid including in browser bundles + var Module = dynamicRequire(module, 'module'); + var $compile = Module.prototype._compile; + + if (!$compile.__sourceMapSupport) { + Module.prototype._compile = function(content, filename) { + fileContentsCache[filename] = content; + sourceMapCache[filename] = undefined; + return $compile.call(this, content, filename); + }; + + Module.prototype._compile.__sourceMapSupport = true; + } + } + + // Configure options + if (!emptyCacheBetweenOperations) { + emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? + options.emptyCacheBetweenOperations : false; + } + + // Install the error reformatter + if (!errorFormatterInstalled) { + errorFormatterInstalled = true; + Error.prepareStackTrace = prepareStackTrace; + } + + if (!uncaughtShimInstalled) { + var installHandler = 'handleUncaughtExceptions' in options ? + options.handleUncaughtExceptions : true; + + // Do not override 'uncaughtException' with our own handler in Node.js + // Worker threads. Workers pass the error to the main thread as an event, + // rather than printing something to stderr and exiting. + try { + // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify. + var worker_threads = dynamicRequire(module, 'worker_threads'); + if (worker_threads.isMainThread === false) { + installHandler = false; + } + } catch(e) {} + + // Provide the option to not install the uncaught exception handler. This is + // to support other uncaught exception handlers (in test frameworks, for + // example). If this handler is not installed and there are no other uncaught + // exception handlers, uncaught exceptions will be caught by node's built-in + // exception handler and the process will still be terminated. However, the + // generated JavaScript code will be shown above the stack trace instead of + // the original source code. + if (installHandler && hasGlobalProcessEventEmitter()) { + uncaughtShimInstalled = true; + shimEmitUncaughtException(); + } + } +}; + +exports.resetRetrieveHandlers = function() { + retrieveFileHandlers.length = 0; + retrieveMapHandlers.length = 0; + + retrieveFileHandlers = originalRetrieveFileHandlers.slice(0); + retrieveMapHandlers = originalRetrieveMapHandlers.slice(0); + + retrieveSourceMap = handlerExec(retrieveMapHandlers); + retrieveFile = handlerExec(retrieveFileHandlers); +} diff --git a/node_modules/mathjs/examples/node_modules/source-map/CHANGELOG.md b/node_modules/mathjs/examples/node_modules/source-map/CHANGELOG.md new file mode 100644 index 0000000..3a8c066 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/CHANGELOG.md @@ -0,0 +1,301 @@ +# Change Log + +## 0.5.6 + +* Fix for regression when people were using numbers as names in source maps. See + #236. + +## 0.5.5 + +* Fix "regression" of unsupported, implementation behavior that half the world + happens to have come to depend on. See #235. + +* Fix regression involving function hoisting in SpiderMonkey. See #233. + +## 0.5.4 + +* Large performance improvements to source-map serialization. See #228 and #229. + +## 0.5.3 + +* Do not include unnecessary distribution files. See + commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86. + +## 0.5.2 + +* Include browser distributions of the library in package.json's `files`. See + issue #212. + +## 0.5.1 + +* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See + ff05274becc9e6e1295ed60f3ea090d31d843379. + +## 0.5.0 + +* Node 0.8 is no longer supported. + +* Use webpack instead of dryice for bundling. + +* Big speedups serializing source maps. See pull request #203. + +* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that + explicitly start with the source root. See issue #199. + +## 0.4.4 + +* Fix an issue where using a `SourceMapGenerator` after having created a + `SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See + issue #191. + +* Fix an issue with where `SourceMapGenerator` would mistakenly consider + different mappings as duplicates of each other and avoid generating them. See + issue #192. + +## 0.4.3 + +* A very large number of performance improvements, particularly when parsing + source maps. Collectively about 75% of time shaved off of the source map + parsing benchmark! + +* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy + searching in the presence of a column option. See issue #177. + +* Fix a bug with joining a source and its source root when the source is above + the root. See issue #182. + +* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to + determine when all sources' contents are inlined into the source map. See + issue #190. + +## 0.4.2 + +* Add an `.npmignore` file so that the benchmarks aren't pulled down by + dependent projects. Issue #169. + +* Add an optional `column` argument to + `SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines + with no mappings. Issues #172 and #173. + +## 0.4.1 + +* Fix accidentally defining a global variable. #170. + +## 0.4.0 + +* The default direction for fuzzy searching was changed back to its original + direction. See #164. + +* There is now a `bias` option you can supply to `SourceMapConsumer` to control + the fuzzy searching direction. See #167. + +* About an 8% speed up in parsing source maps. See #159. + +* Added a benchmark for parsing and generating source maps. + +## 0.3.0 + +* Change the default direction that searching for positions fuzzes when there is + not an exact match. See #154. + +* Support for environments using json2.js for JSON serialization. See #156. + +## 0.2.0 + +* Support for consuming "indexed" source maps which do not have any remote + sections. See pull request #127. This introduces a minor backwards + incompatibility if you are monkey patching `SourceMapConsumer.prototype` + methods. + +## 0.1.43 + +* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue + #148 for some discussion and issues #150, #151, and #152 for implementations. + +## 0.1.42 + +* Fix an issue where `SourceNode`s from different versions of the source-map + library couldn't be used in conjunction with each other. See issue #142. + +## 0.1.41 + +* Fix a bug with getting the source content of relative sources with a "./" + prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768). + +* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the + column span of each mapping. + +* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find + all generated positions associated with a given original source and line. + +## 0.1.40 + +* Performance improvements for parsing source maps in SourceMapConsumer. + +## 0.1.39 + +* Fix a bug where setting a source's contents to null before any source content + had been set before threw a TypeError. See issue #131. + +## 0.1.38 + +* Fix a bug where finding relative paths from an empty path were creating + absolute paths. See issue #129. + +## 0.1.37 + +* Fix a bug where if the source root was an empty string, relative source paths + would turn into absolute source paths. Issue #124. + +## 0.1.36 + +* Allow the `names` mapping property to be an empty string. Issue #121. + +## 0.1.35 + +* A third optional parameter was added to `SourceNode.fromStringWithSourceMap` + to specify a path that relative sources in the second parameter should be + relative to. Issue #105. + +* If no file property is given to a `SourceMapGenerator`, then the resulting + source map will no longer have a `null` file property. The property will + simply not exist. Issue #104. + +* Fixed a bug where consecutive newlines were ignored in `SourceNode`s. + Issue #116. + +## 0.1.34 + +* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103. + +* Fix bug involving source contents and the + `SourceMapGenerator.prototype.applySourceMap`. Issue #100. + +## 0.1.33 + +* Fix some edge cases surrounding path joining and URL resolution. + +* Add a third parameter for relative path to + `SourceMapGenerator.prototype.applySourceMap`. + +* Fix issues with mappings and EOLs. + +## 0.1.32 + +* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns + (issue 92). + +* Fixed test runner to actually report number of failed tests as its process + exit code. + +* Fixed a typo when reporting bad mappings (issue 87). + +## 0.1.31 + +* Delay parsing the mappings in SourceMapConsumer until queried for a source + location. + +* Support Sass source maps (which at the time of writing deviate from the spec + in small ways) in SourceMapConsumer. + +## 0.1.30 + +* Do not join source root with a source, when the source is a data URI. + +* Extend the test runner to allow running single specific test files at a time. + +* Performance improvements in `SourceNode.prototype.walk` and + `SourceMapConsumer.prototype.eachMapping`. + +* Source map browser builds will now work inside Workers. + +* Better error messages when attempting to add an invalid mapping to a + `SourceMapGenerator`. + +## 0.1.29 + +* Allow duplicate entries in the `names` and `sources` arrays of source maps + (usually from TypeScript) we are parsing. Fixes github issue 72. + +## 0.1.28 + +* Skip duplicate mappings when creating source maps from SourceNode; github + issue 75. + +## 0.1.27 + +* Don't throw an error when the `file` property is missing in SourceMapConsumer, + we don't use it anyway. + +## 0.1.26 + +* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70. + +## 0.1.25 + +* Make compatible with browserify + +## 0.1.24 + +* Fix issue with absolute paths and `file://` URIs. See + https://bugzilla.mozilla.org/show_bug.cgi?id=885597 + +## 0.1.23 + +* Fix issue with absolute paths and sourcesContent, github issue 64. + +## 0.1.22 + +* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21. + +## 0.1.21 + +* Fixed handling of sources that start with a slash so that they are relative to + the source root's host. + +## 0.1.20 + +* Fixed github issue #43: absolute URLs aren't joined with the source root + anymore. + +## 0.1.19 + +* Using Travis CI to run tests. + +## 0.1.18 + +* Fixed a bug in the handling of sourceRoot. + +## 0.1.17 + +* Added SourceNode.fromStringWithSourceMap. + +## 0.1.16 + +* Added missing documentation. + +* Fixed the generating of empty mappings in SourceNode. + +## 0.1.15 + +* Added SourceMapGenerator.applySourceMap. + +## 0.1.14 + +* The sourceRoot is now handled consistently. + +## 0.1.13 + +* Added SourceMapGenerator.fromSourceMap. + +## 0.1.12 + +* SourceNode now generates empty mappings too. + +## 0.1.11 + +* Added name support to SourceNode. + +## 0.1.10 + +* Added sourcesContent support to the customer and generator. diff --git a/node_modules/mathjs/examples/node_modules/source-map/LICENSE b/node_modules/mathjs/examples/node_modules/source-map/LICENSE new file mode 100644 index 0000000..ed1b7cf --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/LICENSE @@ -0,0 +1,28 @@ + +Copyright (c) 2009-2011, Mozilla Foundation and contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the names of the Mozilla Foundation nor the names of project + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mathjs/examples/node_modules/source-map/README.md b/node_modules/mathjs/examples/node_modules/source-map/README.md new file mode 100644 index 0000000..fea4beb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/README.md @@ -0,0 +1,742 @@ +# Source Map + +[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) + +[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) + +This is a library to generate and consume the source map format +[described here][format]. + +[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit + +## Use with Node + + $ npm install source-map + +## Use on the Web + + + +-------------------------------------------------------------------------------- + + + + + +## Table of Contents + +- [Examples](#examples) + - [Consuming a source map](#consuming-a-source-map) + - [Generating a source map](#generating-a-source-map) + - [With SourceNode (high level API)](#with-sourcenode-high-level-api) + - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) +- [API](#api) + - [SourceMapConsumer](#sourcemapconsumer) + - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) + - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) + - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) + - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) + - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) + - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) + - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) + - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) + - [SourceMapGenerator](#sourcemapgenerator) + - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) + - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) + - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) + - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) + - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) + - [SourceNode](#sourcenode) + - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) + - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) + - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) + - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) + - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) + - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) + - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) + - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) + - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) + - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) + + + +## Examples + +### Consuming a source map + +```js +var rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' +}; + +var smc = new SourceMapConsumer(rawSourceMap); + +console.log(smc.sources); +// [ 'http://example.com/www/js/one.js', +// 'http://example.com/www/js/two.js' ] + +console.log(smc.originalPositionFor({ + line: 2, + column: 28 +})); +// { source: 'http://example.com/www/js/two.js', +// line: 2, +// column: 10, +// name: 'n' } + +console.log(smc.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10 +})); +// { line: 2, column: 28 } + +smc.eachMapping(function (m) { + // ... +}); +``` + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + +```js +function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), " + ", compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error("Bad AST"); + } +} + +var ast = parse("40 + 2", "add.js"); +console.log(compile(ast).toStringWithSourceMap({ + file: 'add.js' +})); +// { code: '40 + 2', +// map: [object SourceMapGenerator] } +``` + +#### With SourceMapGenerator (low level API) + +```js +var map = new SourceMapGenerator({ + file: "source-mapped.js" +}); + +map.addMapping({ + generated: { + line: 10, + column: 35 + }, + source: "foo.js", + original: { + line: 33, + column: 2 + }, + name: "christopher" +}); + +console.log(map.toString()); +// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' +``` + +## API + +Get a reference to the module: + +```js +// Node.js +var sourceMap = require('source-map'); + +// Browser builds +var sourceMap = window.sourceMap; + +// Inside Firefox +const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); +``` + +### SourceMapConsumer + +A SourceMapConsumer instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +* `version`: Which version of the source map spec this map is following. + +* `sources`: An array of URLs to the original source files. + +* `names`: An array of identifiers which can be referenced by individual + mappings. + +* `sourceRoot`: Optional. The URL root from which all sources are relative. + +* `sourcesContent`: Optional. An array of contents of the original source files. + +* `mappings`: A string of base64 VLQs which contain the actual mappings. + +* `file`: Optional. The generated filename this source map is associated with. + +```js +var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); +``` + +#### SourceMapConsumer.prototype.computeColumnSpans() + +Compute the last column for each generated mapping. The last column is +inclusive. + +```js +// Before: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] + +consumer.computeColumnSpans(); + +// After: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1, +// lastColumn: 9 }, +// { line: 2, +// column: 10, +// lastColumn: 19 }, +// { line: 2, +// column: 20, +// lastColumn: Infinity } ] + +``` + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +* `line`: The line number in the generated source. Line numbers in + this library are 1-based (note that the underlying source map + specification uses 0-based line numbers -- this library handles the + translation). + +* `column`: The column number in the generated source. Column numbers + in this library are 0-based. + +* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or + `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest + element that is smaller than or greater than the one we are searching for, + respectively, if the exact element cannot be found. Defaults to + `SourceMapConsumer.GREATEST_LOWER_BOUND`. + +and an object is returned with the following properties: + +* `source`: The original source file, or null if this information is not + available. + +* `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. + +* `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. + +* `name`: The original identifier, or null if this information is not available. + +```js +consumer.originalPositionFor({ line: 2, column: 10 }) +// { source: 'foo.coffee', +// line: 2, +// column: 2, +// name: null } + +consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) +// { source: null, +// line: null, +// column: null, +// name: null } +``` + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: The column number in the original source. The column + number is 0-based. + +and an object is returned with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) +// { line: 1, +// column: 56 } +``` + +#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) + +Returns all generated line and column information for the original source, line, +and column provided. If no column is provided, returns all mappings +corresponding to a either the line we are searching for or the next closest line +that has any mappings. Otherwise, returns all mappings corresponding to the +given line and either the column we are searching for or the next closest column +that has any offsets. + +The only argument is an object with the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: Optional. The column number in the original source. The + column number is 0-based. + +and an array of objects is returned, each with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] +``` + +#### SourceMapConsumer.prototype.hasContentsOfAllSources() + +Return true if we have the embedded source content for every source listed in +the source map, false otherwise. + +In other words, if this method returns `true`, then +`consumer.sourceContentFor(s)` will succeed for every source `s` in +`consumer.sources`. + +```js +// ... +if (consumer.hasContentsOfAllSources()) { + consumerReadyCallback(consumer); +} else { + fetchSources(consumer, consumerReadyCallback); +} +// ... +``` + +#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +If the source content for the given source is not found, then an error is +thrown. Optionally, pass `true` as the second param to have `null` returned +instead. + +```js +consumer.sources +// [ "my-cool-lib.clj" ] + +consumer.sourceContentFor("my-cool-lib.clj") +// "..." + +consumer.sourceContentFor("this is not in the source map"); +// Error: "this is not in the source map" is not in the source map + +consumer.sourceContentFor("this is not in the source map", true); +// null +``` + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +* `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, + name }` + +* `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +```js +consumer.eachMapping(function (m) { console.log(m); }) +// ... +// { source: 'illmatic.js', +// generatedLine: 1, +// generatedColumn: 0, +// originalLine: 1, +// originalColumn: 0, +// name: null } +// { source: 'illmatic.js', +// generatedLine: 2, +// generatedColumn: 0, +// originalLine: 2, +// originalColumn: 0, +// name: null } +// ... +``` +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +* `file`: The filename of the generated source that this source map is + associated with. + +* `sourceRoot`: A root for all relative URLs in this source map. + +* `skipValidation`: Optional. When `true`, disables validation of mappings as + they are added. This can improve performance but should be used with + discretion, as a last resort. Even then, one should avoid using this flag when + running tests, if possible. + +```js +var generator = new sourceMap.SourceMapGenerator({ + file: "my-generated-javascript-file.js", + sourceRoot: "http://example.com/app/js/" +}); +``` + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer) + +Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. + +* `sourceMapConsumer` The SourceMap. + +```js +var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); +``` + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +* `generated`: An object with the generated line and column positions. + +* `original`: An object with the original line and column positions. + +* `source`: The original source file (relative to the sourceRoot). + +* `name`: An optional original token name for this mapping. + +```js +generator.addMapping({ + source: "module-one.scm", + original: { line: 128, column: 0 }, + generated: { line: 3, column: 456 } +}) +``` + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +* `sourceFile` the URL of the original source file. + +* `sourceContent` the content of the source file. + +```js +generator.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimum of this map and the supplied map. + +* `sourceMapConsumer`: The SourceMap to be applied. + +* `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +* `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +```js +generator.toString() +// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' +``` + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +* `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. + +* `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number + is 0-based. + +* `source`: The original source's filename; null if no filename is provided. + +* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +* `name`: Optional. The original identifier. + +```js +var node = new SourceNode(1, 2, "a.cpp", [ + new SourceNode(3, 4, "b.cpp", "extern int status;\n"), + new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), + new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), +]); +``` + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +* `code`: The generated code + +* `sourceMapConsumer` The SourceMap for the generated code + +* `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +```js +var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); +var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), + consumer); +``` + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.add(" + "); +node.add(otherNode); +node.add([leftHandOperandNode, " + ", rightHandOperandNode]); +``` + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.prepend("/** Build Id: f783haef86324gf **/\n\n"); +``` + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +* `sourceFile`: The filename of the source file + +* `sourceContent`: The content of the source file + +```js +node.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +* `fn`: The traversal function. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.walk(function (code, loc) { console.log("WALK:", code, loc); }) +// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } +// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } +// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } +// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } +``` + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +* `fn`: The traversal function. + +```js +var a = new SourceNode(1, 2, "a.js", "generated from a"); +a.setSourceContent("a.js", "original a"); +var b = new SourceNode(1, 2, "b.js", "generated from b"); +b.setSourceContent("b.js", "original b"); +var c = new SourceNode(1, 2, "c.js", "generated from c"); +c.setSourceContent("c.js", "original c"); + +var node = new SourceNode(null, null, null, [a, b, c]); +node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) +// WALK: a.js : original a +// WALK: b.js : original b +// WALK: c.js : original c +``` + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +* `sep`: The separator. + +```js +var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); +var operand = new SourceNode(3, 4, "a.rs", "="); +var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); + +var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); +var joinedNode = node.join(" "); +``` + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming white space from the end of a source node, etc. + +* `pattern`: The pattern to replace. + +* `replacement`: The thing to replace the pattern with. + +```js +// Trim trailing white space. +node.replaceRight(/\s*$/, ""); +``` + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toString() +// 'unodostresquatro' +``` + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toStringWithSourceMap({ file: "my-output-file.js" }) +// { code: 'unodostresquatro', +// map: [object SourceMapGenerator] } +``` diff --git a/node_modules/mathjs/examples/node_modules/source-map/dist/source-map.debug.js b/node_modules/mathjs/examples/node_modules/source-map/dist/source-map.debug.js new file mode 100644 index 0000000..aad0620 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/dist/source-map.debug.js @@ -0,0 +1,3234 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vd2VicGFjay91bml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uIiwid2VicGFjazovLy93ZWJwYWNrL2Jvb3RzdHJhcCAxNjI0YzcyOTliODg3ZjdiZGY2NCIsIndlYnBhY2s6Ly8vLi9zb3VyY2UtbWFwLmpzIiwid2VicGFjazovLy8uL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LXZscS5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LmpzIiwid2VicGFjazovLy8uL2xpYi91dGlsLmpzIiwid2VicGFjazovLy8uL2xpYi9hcnJheS1zZXQuanMiLCJ3ZWJwYWNrOi8vLy4vbGliL21hcHBpbmctbGlzdC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW1hcC1jb25zdW1lci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmluYXJ5LXNlYXJjaC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvcXVpY2stc29ydC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW5vZGUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsQ0FBQztBQUNELE87QUNWQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSx1QkFBZTtBQUNmO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOzs7QUFHQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOzs7Ozs7O0FDdENBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUNQQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBLE1BQUs7QUFDTDtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsUUFBTztBQUNQO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLDJDQUEwQyxTQUFTO0FBQ25EO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EscUJBQW9CO0FBQ3BCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7Ozs7OztBQ3hhQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSw0REFBMkQ7QUFDM0QscUJBQW9CO0FBQ3BCO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBRzs7QUFFSDtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7O0FBRUg7QUFDQTtBQUNBOzs7Ozs7O0FDM0lBLGlCQUFnQixvQkFBb0I7QUFDcEM7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGlCQUFnQjtBQUNoQixpQkFBZ0I7O0FBRWhCLG9CQUFtQjtBQUNuQixxQkFBb0I7O0FBRXBCLGlCQUFnQjtBQUNoQixpQkFBZ0I7O0FBRWhCLGlCQUFnQjtBQUNoQixrQkFBaUI7O0FBRWpCO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOzs7Ozs7O0FDbEVBLGlCQUFnQixvQkFBb0I7QUFDcEM7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7QUFDSDtBQUNBLElBQUc7QUFDSDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLCtDQUE4QyxRQUFRO0FBQ3REO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsRUFBQzs7QUFFRDtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQSw0QkFBMkIsUUFBUTtBQUNuQztBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLGNBQWE7QUFDYjs7QUFFQTtBQUNBLGVBQWM7QUFDZDs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHVDQUFzQztBQUN0QztBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOzs7Ozs7O0FDdmVBLGlCQUFnQixvQkFBb0I7QUFDcEM7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHVDQUFzQyxTQUFTO0FBQy9DO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7QUFDSDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBRztBQUNIO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7Ozs7Ozs7QUN4SEEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGlCQUFnQjtBQUNoQjs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxJQUFHO0FBQ0g7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7Ozs7Ozs7QUM5RUEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxFQUFDOztBQUVEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLEVBQUM7O0FBRUQ7QUFDQTtBQUNBO0FBQ0Esb0JBQW1CO0FBQ25COztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFlBQVc7O0FBRVg7QUFDQTtBQUNBLFFBQU87QUFDUDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsWUFBVzs7QUFFWDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsNEJBQTJCLE1BQU07QUFDakM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLOztBQUVMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsSUFBRzs7QUFFSDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBLGNBQWEsa0NBQWtDO0FBQy9DO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7O0FBRUw7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBLHVEQUFzRCxZQUFZO0FBQ2xFO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7O0FBRUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0Esb0NBQW1DO0FBQ25DO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSwwQkFBeUIsY0FBYztBQUN2QztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esd0JBQXVCLHdDQUF3QztBQUMvRDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGdEQUErQyxtQkFBbUIsRUFBRTtBQUNwRTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxrQkFBaUIsb0JBQW9CO0FBQ3JDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSw4QkFBNkIsTUFBTTtBQUNuQztBQUNBLFFBQU87QUFDUDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsUUFBTztBQUNQO0FBQ0E7QUFDQSxJQUFHO0FBQ0g7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBbUIsMkJBQTJCO0FBQzlDLHNCQUFxQiwrQ0FBK0M7QUFDcEU7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7O0FBRUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsUUFBTztBQUNQOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW1CLDJCQUEyQjtBQUM5Qzs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFtQiwyQkFBMkI7QUFDOUM7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW1CLDJCQUEyQjtBQUM5QztBQUNBO0FBQ0Esc0JBQXFCLDRCQUE0QjtBQUNqRDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTs7Ozs7OztBQ3huQ0EsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7Ozs7Ozs7QUM5R0EsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxZQUFXLE1BQU07QUFDakI7QUFDQSxZQUFXLE9BQU87QUFDbEI7QUFDQSxZQUFXLE9BQU87QUFDbEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsWUFBVyxNQUFNO0FBQ2pCO0FBQ0EsWUFBVyxTQUFTO0FBQ3BCO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBbUIsT0FBTztBQUMxQjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsWUFBVyxNQUFNO0FBQ2pCO0FBQ0EsWUFBVyxTQUFTO0FBQ3BCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUNqSEEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSzs7QUFFTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esa0NBQWlDLFFBQVE7QUFDekM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsOENBQTZDLFNBQVM7QUFDdEQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EscUJBQW9CO0FBQ3BCO0FBQ0E7QUFDQSx1Q0FBc0M7QUFDdEM7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0JBQWUsV0FBVztBQUMxQjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0RBQStDLFNBQVM7QUFDeEQ7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQSwwQ0FBeUMsU0FBUztBQUNsRDtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7QUFDSDtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFlBQVc7QUFDWDtBQUNBO0FBQ0E7QUFDQSxZQUFXO0FBQ1g7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0EsNkNBQTRDLGNBQWM7QUFDMUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGNBQWE7QUFDYjtBQUNBO0FBQ0E7QUFDQSxjQUFhO0FBQ2I7QUFDQSxZQUFXO0FBQ1g7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0EsSUFBRztBQUNIO0FBQ0E7QUFDQSxJQUFHOztBQUVILFdBQVU7QUFDVjs7QUFFQSIsImZpbGUiOiJzb3VyY2UtbWFwLmRlYnVnLmpzIiwic291cmNlc0NvbnRlbnQiOlsiKGZ1bmN0aW9uIHdlYnBhY2tVbml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uKHJvb3QsIGZhY3RvcnkpIHtcblx0aWYodHlwZW9mIGV4cG9ydHMgPT09ICdvYmplY3QnICYmIHR5cGVvZiBtb2R1bGUgPT09ICdvYmplY3QnKVxuXHRcdG1vZHVsZS5leHBvcnRzID0gZmFjdG9yeSgpO1xuXHRlbHNlIGlmKHR5cGVvZiBkZWZpbmUgPT09ICdmdW5jdGlvbicgJiYgZGVmaW5lLmFtZClcblx0XHRkZWZpbmUoW10sIGZhY3RvcnkpO1xuXHRlbHNlIGlmKHR5cGVvZiBleHBvcnRzID09PSAnb2JqZWN0Jylcblx0XHRleHBvcnRzW1wic291cmNlTWFwXCJdID0gZmFjdG9yeSgpO1xuXHRlbHNlXG5cdFx0cm9vdFtcInNvdXJjZU1hcFwiXSA9IGZhY3RvcnkoKTtcbn0pKHRoaXMsIGZ1bmN0aW9uKCkge1xucmV0dXJuIFxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyB3ZWJwYWNrL3VuaXZlcnNhbE1vZHVsZURlZmluaXRpb24iLCIgXHQvLyBUaGUgbW9kdWxlIGNhY2hlXG4gXHR2YXIgaW5zdGFsbGVkTW9kdWxlcyA9IHt9O1xuXG4gXHQvLyBUaGUgcmVxdWlyZSBmdW5jdGlvblxuIFx0ZnVuY3Rpb24gX193ZWJwYWNrX3JlcXVpcmVfXyhtb2R1bGVJZCkge1xuXG4gXHRcdC8vIENoZWNrIGlmIG1vZHVsZSBpcyBpbiBjYWNoZVxuIFx0XHRpZihpbnN0YWxsZWRNb2R1bGVzW21vZHVsZUlkXSlcbiBcdFx0XHRyZXR1cm4gaW5zdGFsbGVkTW9kdWxlc1ttb2R1bGVJZF0uZXhwb3J0cztcblxuIFx0XHQvLyBDcmVhdGUgYSBuZXcgbW9kdWxlIChhbmQgcHV0IGl0IGludG8gdGhlIGNhY2hlKVxuIFx0XHR2YXIgbW9kdWxlID0gaW5zdGFsbGVkTW9kdWxlc1ttb2R1bGVJZF0gPSB7XG4gXHRcdFx0ZXhwb3J0czoge30sXG4gXHRcdFx0aWQ6IG1vZHVsZUlkLFxuIFx0XHRcdGxvYWRlZDogZmFsc2VcbiBcdFx0fTtcblxuIFx0XHQvLyBFeGVjdXRlIHRoZSBtb2R1bGUgZnVuY3Rpb25cbiBcdFx0bW9kdWxlc1ttb2R1bGVJZF0uY2FsbChtb2R1bGUuZXhwb3J0cywgbW9kdWxlLCBtb2R1bGUuZXhwb3J0cywgX193ZWJwYWNrX3JlcXVpcmVfXyk7XG5cbiBcdFx0Ly8gRmxhZyB0aGUgbW9kdWxlIGFzIGxvYWRlZFxuIFx0XHRtb2R1bGUubG9hZGVkID0gdHJ1ZTtcblxuIFx0XHQvLyBSZXR1cm4gdGhlIGV4cG9ydHMgb2YgdGhlIG1vZHVsZVxuIFx0XHRyZXR1cm4gbW9kdWxlLmV4cG9ydHM7XG4gXHR9XG5cblxuIFx0Ly8gZXhwb3NlIHRoZSBtb2R1bGVzIG9iamVjdCAoX193ZWJwYWNrX21vZHVsZXNfXylcbiBcdF9fd2VicGFja19yZXF1aXJlX18ubSA9IG1vZHVsZXM7XG5cbiBcdC8vIGV4cG9zZSB0aGUgbW9kdWxlIGNhY2hlXG4gXHRfX3dlYnBhY2tfcmVxdWlyZV9fLmMgPSBpbnN0YWxsZWRNb2R1bGVzO1xuXG4gXHQvLyBfX3dlYnBhY2tfcHVibGljX3BhdGhfX1xuIFx0X193ZWJwYWNrX3JlcXVpcmVfXy5wID0gXCJcIjtcblxuIFx0Ly8gTG9hZCBlbnRyeSBtb2R1bGUgYW5kIHJldHVybiBleHBvcnRzXG4gXHRyZXR1cm4gX193ZWJwYWNrX3JlcXVpcmVfXygwKTtcblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyB3ZWJwYWNrL2Jvb3RzdHJhcCAxNjI0YzcyOTliODg3ZjdiZGY2NCIsIi8qXG4gKiBDb3B5cmlnaHQgMjAwOS0yMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRS50eHQgb3I6XG4gKiBodHRwOi8vb3BlbnNvdXJjZS5vcmcvbGljZW5zZXMvQlNELTMtQ2xhdXNlXG4gKi9cbmV4cG9ydHMuU291cmNlTWFwR2VuZXJhdG9yID0gcmVxdWlyZSgnLi9saWIvc291cmNlLW1hcC1nZW5lcmF0b3InKS5Tb3VyY2VNYXBHZW5lcmF0b3I7XG5leHBvcnRzLlNvdXJjZU1hcENvbnN1bWVyID0gcmVxdWlyZSgnLi9saWIvc291cmNlLW1hcC1jb25zdW1lcicpLlNvdXJjZU1hcENvbnN1bWVyO1xuZXhwb3J0cy5Tb3VyY2VOb2RlID0gcmVxdWlyZSgnLi9saWIvc291cmNlLW5vZGUnKS5Tb3VyY2VOb2RlO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9zb3VyY2UtbWFwLmpzXG4vLyBtb2R1bGUgaWQgPSAwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCIsIi8qIC0qLSBNb2RlOiBqczsganMtaW5kZW50LWxldmVsOiAyOyAtKi0gKi9cbi8qXG4gKiBDb3B5cmlnaHQgMjAxMSBNb3ppbGxhIEZvdW5kYXRpb24gYW5kIGNvbnRyaWJ1dG9yc1xuICogTGljZW5zZWQgdW5kZXIgdGhlIE5ldyBCU0QgbGljZW5zZS4gU2VlIExJQ0VOU0Ugb3I6XG4gKiBodHRwOi8vb3BlbnNvdXJjZS5vcmcvbGljZW5zZXMvQlNELTMtQ2xhdXNlXG4gKi9cblxudmFyIGJhc2U2NFZMUSA9IHJlcXVpcmUoJy4vYmFzZTY0LXZscScpO1xudmFyIHV0aWwgPSByZXF1aXJlKCcuL3V0aWwnKTtcbnZhciBBcnJheVNldCA9IHJlcXVpcmUoJy4vYXJyYXktc2V0JykuQXJyYXlTZXQ7XG52YXIgTWFwcGluZ0xpc3QgPSByZXF1aXJlKCcuL21hcHBpbmctbGlzdCcpLk1hcHBpbmdMaXN0O1xuXG4vKipcbiAqIEFuIGluc3RhbmNlIG9mIHRoZSBTb3VyY2VNYXBHZW5lcmF0b3IgcmVwcmVzZW50cyBhIHNvdXJjZSBtYXAgd2hpY2ggaXNcbiAqIGJlaW5nIGJ1aWx0IGluY3JlbWVudGFsbHkuIFlvdSBtYXkgcGFzcyBhbiBvYmplY3Qgd2l0aCB0aGUgZm9sbG93aW5nXG4gKiBwcm9wZXJ0aWVzOlxuICpcbiAqICAgLSBmaWxlOiBUaGUgZmlsZW5hbWUgb2YgdGhlIGdlbmVyYXRlZCBzb3VyY2UuXG4gKiAgIC0gc291cmNlUm9vdDogQSByb290IGZvciBhbGwgcmVsYXRpdmUgVVJMcyBpbiB0aGlzIHNvdXJjZSBtYXAuXG4gKi9cbmZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcihhQXJncykge1xuICBpZiAoIWFBcmdzKSB7XG4gICAgYUFyZ3MgPSB7fTtcbiAgfVxuICB0aGlzLl9maWxlID0gdXRpbC5nZXRBcmcoYUFyZ3MsICdmaWxlJywgbnVsbCk7XG4gIHRoaXMuX3NvdXJjZVJvb3QgPSB1dGlsLmdldEFyZyhhQXJncywgJ3NvdXJjZVJvb3QnLCBudWxsKTtcbiAgdGhpcy5fc2tpcFZhbGlkYXRpb24gPSB1dGlsLmdldEFyZyhhQXJncywgJ3NraXBWYWxpZGF0aW9uJywgZmFsc2UpO1xuICB0aGlzLl9zb3VyY2VzID0gbmV3IEFycmF5U2V0KCk7XG4gIHRoaXMuX25hbWVzID0gbmV3IEFycmF5U2V0KCk7XG4gIHRoaXMuX21hcHBpbmdzID0gbmV3IE1hcHBpbmdMaXN0KCk7XG4gIHRoaXMuX3NvdXJjZXNDb250ZW50cyA9IG51bGw7XG59XG5cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX3ZlcnNpb24gPSAzO1xuXG4vKipcbiAqIENyZWF0ZXMgYSBuZXcgU291cmNlTWFwR2VuZXJhdG9yIGJhc2VkIG9uIGEgU291cmNlTWFwQ29uc3VtZXJcbiAqXG4gKiBAcGFyYW0gYVNvdXJjZU1hcENvbnN1bWVyIFRoZSBTb3VyY2VNYXAuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5mcm9tU291cmNlTWFwID1cbiAgZnVuY3Rpb24gU291cmNlTWFwR2VuZXJhdG9yX2Zyb21Tb3VyY2VNYXAoYVNvdXJjZU1hcENvbnN1bWVyKSB7XG4gICAgdmFyIHNvdXJjZVJvb3QgPSBhU291cmNlTWFwQ29uc3VtZXIuc291cmNlUm9vdDtcbiAgICB2YXIgZ2VuZXJhdG9yID0gbmV3IFNvdXJjZU1hcEdlbmVyYXRvcih7XG4gICAgICBmaWxlOiBhU291cmNlTWFwQ29uc3VtZXIuZmlsZSxcbiAgICAgIHNvdXJjZVJvb3Q6IHNvdXJjZVJvb3RcbiAgICB9KTtcbiAgICBhU291cmNlTWFwQ29uc3VtZXIuZWFjaE1hcHBpbmcoZnVuY3Rpb24gKG1hcHBpbmcpIHtcbiAgICAgIHZhciBuZXdNYXBwaW5nID0ge1xuICAgICAgICBnZW5lcmF0ZWQ6IHtcbiAgICAgICAgICBsaW5lOiBtYXBwaW5nLmdlbmVyYXRlZExpbmUsXG4gICAgICAgICAgY29sdW1uOiBtYXBwaW5nLmdlbmVyYXRlZENvbHVtblxuICAgICAgICB9XG4gICAgICB9O1xuXG4gICAgICBpZiAobWFwcGluZy5zb3VyY2UgIT0gbnVsbCkge1xuICAgICAgICBuZXdNYXBwaW5nLnNvdXJjZSA9IG1hcHBpbmcuc291cmNlO1xuICAgICAgICBpZiAoc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICAgICAgbmV3TWFwcGluZy5zb3VyY2UgPSB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIG5ld01hcHBpbmcuc291cmNlKTtcbiAgICAgICAgfVxuXG4gICAgICAgIG5ld01hcHBpbmcub3JpZ2luYWwgPSB7XG4gICAgICAgICAgbGluZTogbWFwcGluZy5vcmlnaW5hbExpbmUsXG4gICAgICAgICAgY29sdW1uOiBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uXG4gICAgICAgIH07XG5cbiAgICAgICAgaWYgKG1hcHBpbmcubmFtZSAhPSBudWxsKSB7XG4gICAgICAgICAgbmV3TWFwcGluZy5uYW1lID0gbWFwcGluZy5uYW1lO1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIGdlbmVyYXRvci5hZGRNYXBwaW5nKG5ld01hcHBpbmcpO1xuICAgIH0pO1xuICAgIGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VzLmZvckVhY2goZnVuY3Rpb24gKHNvdXJjZUZpbGUpIHtcbiAgICAgIHZhciBzb3VyY2VSZWxhdGl2ZSA9IHNvdXJjZUZpbGU7XG4gICAgICBpZiAoc291cmNlUm9vdCAhPT0gbnVsbCkge1xuICAgICAgICBzb3VyY2VSZWxhdGl2ZSA9IHV0aWwucmVsYXRpdmUoc291cmNlUm9vdCwgc291cmNlRmlsZSk7XG4gICAgICB9XG5cbiAgICAgIGlmICghZ2VuZXJhdG9yLl9zb3VyY2VzLmhhcyhzb3VyY2VSZWxhdGl2ZSkpIHtcbiAgICAgICAgZ2VuZXJhdG9yLl9zb3VyY2VzLmFkZChzb3VyY2VSZWxhdGl2ZSk7XG4gICAgICB9XG5cbiAgICAgIHZhciBjb250ZW50ID0gYVNvdXJjZU1hcENvbnN1bWVyLnNvdXJjZUNvbnRlbnRGb3Ioc291cmNlRmlsZSk7XG4gICAgICBpZiAoY29udGVudCAhPSBudWxsKSB7XG4gICAgICAgIGdlbmVyYXRvci5zZXRTb3VyY2VDb250ZW50KHNvdXJjZUZpbGUsIGNvbnRlbnQpO1xuICAgICAgfVxuICAgIH0pO1xuICAgIHJldHVybiBnZW5lcmF0b3I7XG4gIH07XG5cbi8qKlxuICogQWRkIGEgc2luZ2xlIG1hcHBpbmcgZnJvbSBvcmlnaW5hbCBzb3VyY2UgbGluZSBhbmQgY29sdW1uIHRvIHRoZSBnZW5lcmF0ZWRcbiAqIHNvdXJjZSdzIGxpbmUgYW5kIGNvbHVtbiBmb3IgdGhpcyBzb3VyY2UgbWFwIGJlaW5nIGNyZWF0ZWQuIFRoZSBtYXBwaW5nXG4gKiBvYmplY3Qgc2hvdWxkIGhhdmUgdGhlIGZvbGxvd2luZyBwcm9wZXJ0aWVzOlxuICpcbiAqICAgLSBnZW5lcmF0ZWQ6IEFuIG9iamVjdCB3aXRoIHRoZSBnZW5lcmF0ZWQgbGluZSBhbmQgY29sdW1uIHBvc2l0aW9ucy5cbiAqICAgLSBvcmlnaW5hbDogQW4gb2JqZWN0IHdpdGggdGhlIG9yaWdpbmFsIGxpbmUgYW5kIGNvbHVtbiBwb3NpdGlvbnMuXG4gKiAgIC0gc291cmNlOiBUaGUgb3JpZ2luYWwgc291cmNlIGZpbGUgKHJlbGF0aXZlIHRvIHRoZSBzb3VyY2VSb290KS5cbiAqICAgLSBuYW1lOiBBbiBvcHRpb25hbCBvcmlnaW5hbCB0b2tlbiBuYW1lIGZvciB0aGlzIG1hcHBpbmcuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuYWRkTWFwcGluZyA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl9hZGRNYXBwaW5nKGFBcmdzKSB7XG4gICAgdmFyIGdlbmVyYXRlZCA9IHV0aWwuZ2V0QXJnKGFBcmdzLCAnZ2VuZXJhdGVkJyk7XG4gICAgdmFyIG9yaWdpbmFsID0gdXRpbC5nZXRBcmcoYUFyZ3MsICdvcmlnaW5hbCcsIG51bGwpO1xuICAgIHZhciBzb3VyY2UgPSB1dGlsLmdldEFyZyhhQXJncywgJ3NvdXJjZScsIG51bGwpO1xuICAgIHZhciBuYW1lID0gdXRpbC5nZXRBcmcoYUFyZ3MsICduYW1lJywgbnVsbCk7XG5cbiAgICBpZiAoIXRoaXMuX3NraXBWYWxpZGF0aW9uKSB7XG4gICAgICB0aGlzLl92YWxpZGF0ZU1hcHBpbmcoZ2VuZXJhdGVkLCBvcmlnaW5hbCwgc291cmNlLCBuYW1lKTtcbiAgICB9XG5cbiAgICBpZiAoc291cmNlICE9IG51bGwpIHtcbiAgICAgIHNvdXJjZSA9IFN0cmluZyhzb3VyY2UpO1xuICAgICAgaWYgKCF0aGlzLl9zb3VyY2VzLmhhcyhzb3VyY2UpKSB7XG4gICAgICAgIHRoaXMuX3NvdXJjZXMuYWRkKHNvdXJjZSk7XG4gICAgICB9XG4gICAgfVxuXG4gICAgaWYgKG5hbWUgIT0gbnVsbCkge1xuICAgICAgbmFtZSA9IFN0cmluZyhuYW1lKTtcbiAgICAgIGlmICghdGhpcy5fbmFtZXMuaGFzKG5hbWUpKSB7XG4gICAgICAgIHRoaXMuX25hbWVzLmFkZChuYW1lKTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICB0aGlzLl9tYXBwaW5ncy5hZGQoe1xuICAgICAgZ2VuZXJhdGVkTGluZTogZ2VuZXJhdGVkLmxpbmUsXG4gICAgICBnZW5lcmF0ZWRDb2x1bW46IGdlbmVyYXRlZC5jb2x1bW4sXG4gICAgICBvcmlnaW5hbExpbmU6IG9yaWdpbmFsICE9IG51bGwgJiYgb3JpZ2luYWwubGluZSxcbiAgICAgIG9yaWdpbmFsQ29sdW1uOiBvcmlnaW5hbCAhPSBudWxsICYmIG9yaWdpbmFsLmNvbHVtbixcbiAgICAgIHNvdXJjZTogc291cmNlLFxuICAgICAgbmFtZTogbmFtZVxuICAgIH0pO1xuICB9O1xuXG4vKipcbiAqIFNldCB0aGUgc291cmNlIGNvbnRlbnQgZm9yIGEgc291cmNlIGZpbGUuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuc2V0U291cmNlQ29udGVudCA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl9zZXRTb3VyY2VDb250ZW50KGFTb3VyY2VGaWxlLCBhU291cmNlQ29udGVudCkge1xuICAgIHZhciBzb3VyY2UgPSBhU291cmNlRmlsZTtcbiAgICBpZiAodGhpcy5fc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICBzb3VyY2UgPSB1dGlsLnJlbGF0aXZlKHRoaXMuX3NvdXJjZVJvb3QsIHNvdXJjZSk7XG4gICAgfVxuXG4gICAgaWYgKGFTb3VyY2VDb250ZW50ICE9IG51bGwpIHtcbiAgICAgIC8vIEFkZCB0aGUgc291cmNlIGNvbnRlbnQgdG8gdGhlIF9zb3VyY2VzQ29udGVudHMgbWFwLlxuICAgICAgLy8gQ3JlYXRlIGEgbmV3IF9zb3VyY2VzQ29udGVudHMgbWFwIGlmIHRoZSBwcm9wZXJ0eSBpcyBudWxsLlxuICAgICAgaWYgKCF0aGlzLl9zb3VyY2VzQ29udGVudHMpIHtcbiAgICAgICAgdGhpcy5fc291cmNlc0NvbnRlbnRzID0gT2JqZWN0LmNyZWF0ZShudWxsKTtcbiAgICAgIH1cbiAgICAgIHRoaXMuX3NvdXJjZXNDb250ZW50c1t1dGlsLnRvU2V0U3RyaW5nKHNvdXJjZSldID0gYVNvdXJjZUNvbnRlbnQ7XG4gICAgfSBlbHNlIGlmICh0aGlzLl9zb3VyY2VzQ29udGVudHMpIHtcbiAgICAgIC8vIFJlbW92ZSB0aGUgc291cmNlIGZpbGUgZnJvbSB0aGUgX3NvdXJjZXNDb250ZW50cyBtYXAuXG4gICAgICAvLyBJZiB0aGUgX3NvdXJjZXNDb250ZW50cyBtYXAgaXMgZW1wdHksIHNldCB0aGUgcHJvcGVydHkgdG8gbnVsbC5cbiAgICAgIGRlbGV0ZSB0aGlzLl9zb3VyY2VzQ29udGVudHNbdXRpbC50b1NldFN0cmluZyhzb3VyY2UpXTtcbiAgICAgIGlmIChPYmplY3Qua2V5cyh0aGlzLl9zb3VyY2VzQ29udGVudHMpLmxlbmd0aCA9PT0gMCkge1xuICAgICAgICB0aGlzLl9zb3VyY2VzQ29udGVudHMgPSBudWxsO1xuICAgICAgfVxuICAgIH1cbiAgfTtcblxuLyoqXG4gKiBBcHBsaWVzIHRoZSBtYXBwaW5ncyBvZiBhIHN1Yi1zb3VyY2UtbWFwIGZvciBhIHNwZWNpZmljIHNvdXJjZSBmaWxlIHRvIHRoZVxuICogc291cmNlIG1hcCBiZWluZyBnZW5lcmF0ZWQuIEVhY2ggbWFwcGluZyB0byB0aGUgc3VwcGxpZWQgc291cmNlIGZpbGUgaXNcbiAqIHJld3JpdHRlbiB1c2luZyB0aGUgc3VwcGxpZWQgc291cmNlIG1hcC4gTm90ZTogVGhlIHJlc29sdXRpb24gZm9yIHRoZVxuICogcmVzdWx0aW5nIG1hcHBpbmdzIGlzIHRoZSBtaW5pbWl1bSBvZiB0aGlzIG1hcCBhbmQgdGhlIHN1cHBsaWVkIG1hcC5cbiAqXG4gKiBAcGFyYW0gYVNvdXJjZU1hcENvbnN1bWVyIFRoZSBzb3VyY2UgbWFwIHRvIGJlIGFwcGxpZWQuXG4gKiBAcGFyYW0gYVNvdXJjZUZpbGUgT3B0aW9uYWwuIFRoZSBmaWxlbmFtZSBvZiB0aGUgc291cmNlIGZpbGUuXG4gKiAgICAgICAgSWYgb21pdHRlZCwgU291cmNlTWFwQ29uc3VtZXIncyBmaWxlIHByb3BlcnR5IHdpbGwgYmUgdXNlZC5cbiAqIEBwYXJhbSBhU291cmNlTWFwUGF0aCBPcHRpb25hbC4gVGhlIGRpcm5hbWUgb2YgdGhlIHBhdGggdG8gdGhlIHNvdXJjZSBtYXBcbiAqICAgICAgICB0byBiZSBhcHBsaWVkLiBJZiByZWxhdGl2ZSwgaXQgaXMgcmVsYXRpdmUgdG8gdGhlIFNvdXJjZU1hcENvbnN1bWVyLlxuICogICAgICAgIFRoaXMgcGFyYW1ldGVyIGlzIG5lZWRlZCB3aGVuIHRoZSB0d28gc291cmNlIG1hcHMgYXJlbid0IGluIHRoZSBzYW1lXG4gKiAgICAgICAgZGlyZWN0b3J5LCBhbmQgdGhlIHNvdXJjZSBtYXAgdG8gYmUgYXBwbGllZCBjb250YWlucyByZWxhdGl2ZSBzb3VyY2VcbiAqICAgICAgICBwYXRocy4gSWYgc28sIHRob3NlIHJlbGF0aXZlIHNvdXJjZSBwYXRocyBuZWVkIHRvIGJlIHJld3JpdHRlblxuICogICAgICAgIHJlbGF0aXZlIHRvIHRoZSBTb3VyY2VNYXBHZW5lcmF0b3IuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuYXBwbHlTb3VyY2VNYXAgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfYXBwbHlTb3VyY2VNYXAoYVNvdXJjZU1hcENvbnN1bWVyLCBhU291cmNlRmlsZSwgYVNvdXJjZU1hcFBhdGgpIHtcbiAgICB2YXIgc291cmNlRmlsZSA9IGFTb3VyY2VGaWxlO1xuICAgIC8vIElmIGFTb3VyY2VGaWxlIGlzIG9taXR0ZWQsIHdlIHdpbGwgdXNlIHRoZSBmaWxlIHByb3BlcnR5IG9mIHRoZSBTb3VyY2VNYXBcbiAgICBpZiAoYVNvdXJjZUZpbGUgPT0gbnVsbCkge1xuICAgICAgaWYgKGFTb3VyY2VNYXBDb25zdW1lci5maWxlID09IG51bGwpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKFxuICAgICAgICAgICdTb3VyY2VNYXBHZW5lcmF0b3IucHJvdG90eXBlLmFwcGx5U291cmNlTWFwIHJlcXVpcmVzIGVpdGhlciBhbiBleHBsaWNpdCBzb3VyY2UgZmlsZSwgJyArXG4gICAgICAgICAgJ29yIHRoZSBzb3VyY2UgbWFwXFwncyBcImZpbGVcIiBwcm9wZXJ0eS4gQm90aCB3ZXJlIG9taXR0ZWQuJ1xuICAgICAgICApO1xuICAgICAgfVxuICAgICAgc291cmNlRmlsZSA9IGFTb3VyY2VNYXBDb25zdW1lci5maWxlO1xuICAgIH1cbiAgICB2YXIgc291cmNlUm9vdCA9IHRoaXMuX3NvdXJjZVJvb3Q7XG4gICAgLy8gTWFrZSBcInNvdXJjZUZpbGVcIiByZWxhdGl2ZSBpZiBhbiBhYnNvbHV0ZSBVcmwgaXMgcGFzc2VkLlxuICAgIGlmIChzb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgIHNvdXJjZUZpbGUgPSB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIHNvdXJjZUZpbGUpO1xuICAgIH1cbiAgICAvLyBBcHBseWluZyB0aGUgU291cmNlTWFwIGNhbiBhZGQgYW5kIHJlbW92ZSBpdGVtcyBmcm9tIHRoZSBzb3VyY2VzIGFuZFxuICAgIC8vIHRoZSBuYW1lcyBhcnJheS5cbiAgICB2YXIgbmV3U291cmNlcyA9IG5ldyBBcnJheVNldCgpO1xuICAgIHZhciBuZXdOYW1lcyA9IG5ldyBBcnJheVNldCgpO1xuXG4gICAgLy8gRmluZCBtYXBwaW5ncyBmb3IgdGhlIFwic291cmNlRmlsZVwiXG4gICAgdGhpcy5fbWFwcGluZ3MudW5zb3J0ZWRGb3JFYWNoKGZ1bmN0aW9uIChtYXBwaW5nKSB7XG4gICAgICBpZiAobWFwcGluZy5zb3VyY2UgPT09IHNvdXJjZUZpbGUgJiYgbWFwcGluZy5vcmlnaW5hbExpbmUgIT0gbnVsbCkge1xuICAgICAgICAvLyBDaGVjayBpZiBpdCBjYW4gYmUgbWFwcGVkIGJ5IHRoZSBzb3VyY2UgbWFwLCB0aGVuIHVwZGF0ZSB0aGUgbWFwcGluZy5cbiAgICAgICAgdmFyIG9yaWdpbmFsID0gYVNvdXJjZU1hcENvbnN1bWVyLm9yaWdpbmFsUG9zaXRpb25Gb3Ioe1xuICAgICAgICAgIGxpbmU6IG1hcHBpbmcub3JpZ2luYWxMaW5lLFxuICAgICAgICAgIGNvbHVtbjogbWFwcGluZy5vcmlnaW5hbENvbHVtblxuICAgICAgICB9KTtcbiAgICAgICAgaWYgKG9yaWdpbmFsLnNvdXJjZSAhPSBudWxsKSB7XG4gICAgICAgICAgLy8gQ29weSBtYXBwaW5nXG4gICAgICAgICAgbWFwcGluZy5zb3VyY2UgPSBvcmlnaW5hbC5zb3VyY2U7XG4gICAgICAgICAgaWYgKGFTb3VyY2VNYXBQYXRoICE9IG51bGwpIHtcbiAgICAgICAgICAgIG1hcHBpbmcuc291cmNlID0gdXRpbC5qb2luKGFTb3VyY2VNYXBQYXRoLCBtYXBwaW5nLnNvdXJjZSlcbiAgICAgICAgICB9XG4gICAgICAgICAgaWYgKHNvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgICAgICAgICAgbWFwcGluZy5zb3VyY2UgPSB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIG1hcHBpbmcuc291cmNlKTtcbiAgICAgICAgICB9XG4gICAgICAgICAgbWFwcGluZy5vcmlnaW5hbExpbmUgPSBvcmlnaW5hbC5saW5lO1xuICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxDb2x1bW4gPSBvcmlnaW5hbC5jb2x1bW47XG4gICAgICAgICAgaWYgKG9yaWdpbmFsLm5hbWUgIT0gbnVsbCkge1xuICAgICAgICAgICAgbWFwcGluZy5uYW1lID0gb3JpZ2luYWwubmFtZTtcbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgdmFyIHNvdXJjZSA9IG1hcHBpbmcuc291cmNlO1xuICAgICAgaWYgKHNvdXJjZSAhPSBudWxsICYmICFuZXdTb3VyY2VzLmhhcyhzb3VyY2UpKSB7XG4gICAgICAgIG5ld1NvdXJjZXMuYWRkKHNvdXJjZSk7XG4gICAgICB9XG5cbiAgICAgIHZhciBuYW1lID0gbWFwcGluZy5uYW1lO1xuICAgICAgaWYgKG5hbWUgIT0gbnVsbCAmJiAhbmV3TmFtZXMuaGFzKG5hbWUpKSB7XG4gICAgICAgIG5ld05hbWVzLmFkZChuYW1lKTtcbiAgICAgIH1cblxuICAgIH0sIHRoaXMpO1xuICAgIHRoaXMuX3NvdXJjZXMgPSBuZXdTb3VyY2VzO1xuICAgIHRoaXMuX25hbWVzID0gbmV3TmFtZXM7XG5cbiAgICAvLyBDb3B5IHNvdXJjZXNDb250ZW50cyBvZiBhcHBsaWVkIG1hcC5cbiAgICBhU291cmNlTWFwQ29uc3VtZXIuc291cmNlcy5mb3JFYWNoKGZ1bmN0aW9uIChzb3VyY2VGaWxlKSB7XG4gICAgICB2YXIgY29udGVudCA9IGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKHNvdXJjZUZpbGUpO1xuICAgICAgaWYgKGNvbnRlbnQgIT0gbnVsbCkge1xuICAgICAgICBpZiAoYVNvdXJjZU1hcFBhdGggIT0gbnVsbCkge1xuICAgICAgICAgIHNvdXJjZUZpbGUgPSB1dGlsLmpvaW4oYVNvdXJjZU1hcFBhdGgsIHNvdXJjZUZpbGUpO1xuICAgICAgICB9XG4gICAgICAgIGlmIChzb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgICAgICBzb3VyY2VGaWxlID0gdXRpbC5yZWxhdGl2ZShzb3VyY2VSb290LCBzb3VyY2VGaWxlKTtcbiAgICAgICAgfVxuICAgICAgICB0aGlzLnNldFNvdXJjZUNvbnRlbnQoc291cmNlRmlsZSwgY29udGVudCk7XG4gICAgICB9XG4gICAgfSwgdGhpcyk7XG4gIH07XG5cbi8qKlxuICogQSBtYXBwaW5nIGNhbiBoYXZlIG9uZSBvZiB0aGUgdGhyZWUgbGV2ZWxzIG9mIGRhdGE6XG4gKlxuICogICAxLiBKdXN0IHRoZSBnZW5lcmF0ZWQgcG9zaXRpb24uXG4gKiAgIDIuIFRoZSBHZW5lcmF0ZWQgcG9zaXRpb24sIG9yaWdpbmFsIHBvc2l0aW9uLCBhbmQgb3JpZ2luYWwgc291cmNlLlxuICogICAzLiBHZW5lcmF0ZWQgYW5kIG9yaWdpbmFsIHBvc2l0aW9uLCBvcmlnaW5hbCBzb3VyY2UsIGFzIHdlbGwgYXMgYSBuYW1lXG4gKiAgICAgIHRva2VuLlxuICpcbiAqIFRvIG1haW50YWluIGNvbnNpc3RlbmN5LCB3ZSB2YWxpZGF0ZSB0aGF0IGFueSBuZXcgbWFwcGluZyBiZWluZyBhZGRlZCBmYWxsc1xuICogaW4gdG8gb25lIG9mIHRoZXNlIGNhdGVnb3JpZXMuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX3ZhbGlkYXRlTWFwcGluZyA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl92YWxpZGF0ZU1hcHBpbmcoYUdlbmVyYXRlZCwgYU9yaWdpbmFsLCBhU291cmNlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGFOYW1lKSB7XG4gICAgLy8gV2hlbiBhT3JpZ2luYWwgaXMgdHJ1dGh5IGJ1dCBoYXMgZW1wdHkgdmFsdWVzIGZvciAubGluZSBhbmQgLmNvbHVtbixcbiAgICAvLyBpdCBpcyBtb3N0IGxpa2VseSBhIHByb2dyYW1tZXIgZXJyb3IuIEluIHRoaXMgY2FzZSB3ZSB0aHJvdyBhIHZlcnlcbiAgICAvLyBzcGVjaWZpYyBlcnJvciBtZXNzYWdlIHRvIHRyeSB0byBndWlkZSB0aGVtIHRoZSByaWdodCB3YXkuXG4gICAgLy8gRm9yIGV4YW1wbGU6IGh0dHBzOi8vZ2l0aHViLmNvbS9Qb2x5bWVyL3BvbHltZXItYnVuZGxlci9wdWxsLzUxOVxuICAgIGlmIChhT3JpZ2luYWwgJiYgdHlwZW9mIGFPcmlnaW5hbC5saW5lICE9PSAnbnVtYmVyJyAmJiB0eXBlb2YgYU9yaWdpbmFsLmNvbHVtbiAhPT0gJ251bWJlcicpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKFxuICAgICAgICAgICAgJ29yaWdpbmFsLmxpbmUgYW5kIG9yaWdpbmFsLmNvbHVtbiBhcmUgbm90IG51bWJlcnMgLS0geW91IHByb2JhYmx5IG1lYW50IHRvIG9taXQgJyArXG4gICAgICAgICAgICAndGhlIG9yaWdpbmFsIG1hcHBpbmcgZW50aXJlbHkgYW5kIG9ubHkgbWFwIHRoZSBnZW5lcmF0ZWQgcG9zaXRpb24uIElmIHNvLCBwYXNzICcgK1xuICAgICAgICAgICAgJ251bGwgZm9yIHRoZSBvcmlnaW5hbCBtYXBwaW5nIGluc3RlYWQgb2YgYW4gb2JqZWN0IHdpdGggZW1wdHkgb3IgbnVsbCB2YWx1ZXMuJ1xuICAgICAgICApO1xuICAgIH1cblxuICAgIGlmIChhR2VuZXJhdGVkICYmICdsaW5lJyBpbiBhR2VuZXJhdGVkICYmICdjb2x1bW4nIGluIGFHZW5lcmF0ZWRcbiAgICAgICAgJiYgYUdlbmVyYXRlZC5saW5lID4gMCAmJiBhR2VuZXJhdGVkLmNvbHVtbiA+PSAwXG4gICAgICAgICYmICFhT3JpZ2luYWwgJiYgIWFTb3VyY2UgJiYgIWFOYW1lKSB7XG4gICAgICAvLyBDYXNlIDEuXG4gICAgICByZXR1cm47XG4gICAgfVxuICAgIGVsc2UgaWYgKGFHZW5lcmF0ZWQgJiYgJ2xpbmUnIGluIGFHZW5lcmF0ZWQgJiYgJ2NvbHVtbicgaW4gYUdlbmVyYXRlZFxuICAgICAgICAgICAgICYmIGFPcmlnaW5hbCAmJiAnbGluZScgaW4gYU9yaWdpbmFsICYmICdjb2x1bW4nIGluIGFPcmlnaW5hbFxuICAgICAgICAgICAgICYmIGFHZW5lcmF0ZWQubGluZSA+IDAgJiYgYUdlbmVyYXRlZC5jb2x1bW4gPj0gMFxuICAgICAgICAgICAgICYmIGFPcmlnaW5hbC5saW5lID4gMCAmJiBhT3JpZ2luYWwuY29sdW1uID49IDBcbiAgICAgICAgICAgICAmJiBhU291cmNlKSB7XG4gICAgICAvLyBDYXNlcyAyIGFuZCAzLlxuICAgICAgcmV0dXJuO1xuICAgIH1cbiAgICBlbHNlIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignSW52YWxpZCBtYXBwaW5nOiAnICsgSlNPTi5zdHJpbmdpZnkoe1xuICAgICAgICBnZW5lcmF0ZWQ6IGFHZW5lcmF0ZWQsXG4gICAgICAgIHNvdXJjZTogYVNvdXJjZSxcbiAgICAgICAgb3JpZ2luYWw6IGFPcmlnaW5hbCxcbiAgICAgICAgbmFtZTogYU5hbWVcbiAgICAgIH0pKTtcbiAgICB9XG4gIH07XG5cbi8qKlxuICogU2VyaWFsaXplIHRoZSBhY2N1bXVsYXRlZCBtYXBwaW5ncyBpbiB0byB0aGUgc3RyZWFtIG9mIGJhc2UgNjQgVkxRc1xuICogc3BlY2lmaWVkIGJ5IHRoZSBzb3VyY2UgbWFwIGZvcm1hdC5cbiAqL1xuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS5fc2VyaWFsaXplTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3Jfc2VyaWFsaXplTWFwcGluZ3MoKSB7XG4gICAgdmFyIHByZXZpb3VzR2VuZXJhdGVkQ29sdW1uID0gMDtcbiAgICB2YXIgcHJldmlvdXNHZW5lcmF0ZWRMaW5lID0gMTtcbiAgICB2YXIgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IDA7XG4gICAgdmFyIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gMDtcbiAgICB2YXIgcHJldmlvdXNOYW1lID0gMDtcbiAgICB2YXIgcHJldmlvdXNTb3VyY2UgPSAwO1xuICAgIHZhciByZXN1bHQgPSAnJztcbiAgICB2YXIgbmV4dDtcbiAgICB2YXIgbWFwcGluZztcbiAgICB2YXIgbmFtZUlkeDtcbiAgICB2YXIgc291cmNlSWR4O1xuXG4gICAgdmFyIG1hcHBpbmdzID0gdGhpcy5fbWFwcGluZ3MudG9BcnJheSgpO1xuICAgIGZvciAodmFyIGkgPSAwLCBsZW4gPSBtYXBwaW5ncy5sZW5ndGg7IGkgPCBsZW47IGkrKykge1xuICAgICAgbWFwcGluZyA9IG1hcHBpbmdzW2ldO1xuICAgICAgbmV4dCA9ICcnXG5cbiAgICAgIGlmIChtYXBwaW5nLmdlbmVyYXRlZExpbmUgIT09IHByZXZpb3VzR2VuZXJhdGVkTGluZSkge1xuICAgICAgICBwcmV2aW91c0dlbmVyYXRlZENvbHVtbiA9IDA7XG4gICAgICAgIHdoaWxlIChtYXBwaW5nLmdlbmVyYXRlZExpbmUgIT09IHByZXZpb3VzR2VuZXJhdGVkTGluZSkge1xuICAgICAgICAgIG5leHQgKz0gJzsnO1xuICAgICAgICAgIHByZXZpb3VzR2VuZXJhdGVkTGluZSsrO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgICBlbHNlIHtcbiAgICAgICAgaWYgKGkgPiAwKSB7XG4gICAgICAgICAgaWYgKCF1dGlsLmNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0luZmxhdGVkKG1hcHBpbmcsIG1hcHBpbmdzW2kgLSAxXSkpIHtcbiAgICAgICAgICAgIGNvbnRpbnVlO1xuICAgICAgICAgIH1cbiAgICAgICAgICBuZXh0ICs9ICcsJztcbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5nZW5lcmF0ZWRDb2x1bW5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgaWYgKG1hcHBpbmcuc291cmNlICE9IG51bGwpIHtcbiAgICAgICAgc291cmNlSWR4ID0gdGhpcy5fc291cmNlcy5pbmRleE9mKG1hcHBpbmcuc291cmNlKTtcbiAgICAgICAgbmV4dCArPSBiYXNlNjRWTFEuZW5jb2RlKHNvdXJjZUlkeCAtIHByZXZpb3VzU291cmNlKTtcbiAgICAgICAgcHJldmlvdXNTb3VyY2UgPSBzb3VyY2VJZHg7XG5cbiAgICAgICAgLy8gbGluZXMgYXJlIHN0b3JlZCAwLWJhc2VkIGluIFNvdXJjZU1hcCBzcGVjIHZlcnNpb24gM1xuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbExpbmUgLSAxXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNPcmlnaW5hbExpbmUpO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsTGluZSA9IG1hcHBpbmcub3JpZ2luYWxMaW5lIC0gMTtcblxuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbENvbHVtblxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtIHByZXZpb3VzT3JpZ2luYWxDb2x1bW4pO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsQ29sdW1uID0gbWFwcGluZy5vcmlnaW5hbENvbHVtbjtcblxuICAgICAgICBpZiAobWFwcGluZy5uYW1lICE9IG51bGwpIHtcbiAgICAgICAgICBuYW1lSWR4ID0gdGhpcy5fbmFtZXMuaW5kZXhPZihtYXBwaW5nLm5hbWUpO1xuICAgICAgICAgIG5leHQgKz0gYmFzZTY0VkxRLmVuY29kZShuYW1lSWR4IC0gcHJldmlvdXNOYW1lKTtcbiAgICAgICAgICBwcmV2aW91c05hbWUgPSBuYW1lSWR4O1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIHJlc3VsdCArPSBuZXh0O1xuICAgIH1cblxuICAgIHJldHVybiByZXN1bHQ7XG4gIH07XG5cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX2dlbmVyYXRlU291cmNlc0NvbnRlbnQgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfZ2VuZXJhdGVTb3VyY2VzQ29udGVudChhU291cmNlcywgYVNvdXJjZVJvb3QpIHtcbiAgICByZXR1cm4gYVNvdXJjZXMubWFwKGZ1bmN0aW9uIChzb3VyY2UpIHtcbiAgICAgIGlmICghdGhpcy5fc291cmNlc0NvbnRlbnRzKSB7XG4gICAgICAgIHJldHVybiBudWxsO1xuICAgICAgfVxuICAgICAgaWYgKGFTb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgICAgc291cmNlID0gdXRpbC5yZWxhdGl2ZShhU291cmNlUm9vdCwgc291cmNlKTtcbiAgICAgIH1cbiAgICAgIHZhciBrZXkgPSB1dGlsLnRvU2V0U3RyaW5nKHNvdXJjZSk7XG4gICAgICByZXR1cm4gT2JqZWN0LnByb3RvdHlwZS5oYXNPd25Qcm9wZXJ0eS5jYWxsKHRoaXMuX3NvdXJjZXNDb250ZW50cywga2V5KVxuICAgICAgICA/IHRoaXMuX3NvdXJjZXNDb250ZW50c1trZXldXG4gICAgICAgIDogbnVsbDtcbiAgICB9LCB0aGlzKTtcbiAgfTtcblxuLyoqXG4gKiBFeHRlcm5hbGl6ZSB0aGUgc291cmNlIG1hcC5cbiAqL1xuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS50b0pTT04gPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfdG9KU09OKCkge1xuICAgIHZhciBtYXAgPSB7XG4gICAgICB2ZXJzaW9uOiB0aGlzLl92ZXJzaW9uLFxuICAgICAgc291cmNlczogdGhpcy5fc291cmNlcy50b0FycmF5KCksXG4gICAgICBuYW1lczogdGhpcy5fbmFtZXMudG9BcnJheSgpLFxuICAgICAgbWFwcGluZ3M6IHRoaXMuX3NlcmlhbGl6ZU1hcHBpbmdzKClcbiAgICB9O1xuICAgIGlmICh0aGlzLl9maWxlICE9IG51bGwpIHtcbiAgICAgIG1hcC5maWxlID0gdGhpcy5fZmlsZTtcbiAgICB9XG4gICAgaWYgKHRoaXMuX3NvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgICAgbWFwLnNvdXJjZVJvb3QgPSB0aGlzLl9zb3VyY2VSb290O1xuICAgIH1cbiAgICBpZiAodGhpcy5fc291cmNlc0NvbnRlbnRzKSB7XG4gICAgICBtYXAuc291cmNlc0NvbnRlbnQgPSB0aGlzLl9nZW5lcmF0ZVNvdXJjZXNDb250ZW50KG1hcC5zb3VyY2VzLCBtYXAuc291cmNlUm9vdCk7XG4gICAgfVxuXG4gICAgcmV0dXJuIG1hcDtcbiAgfTtcblxuLyoqXG4gKiBSZW5kZXIgdGhlIHNvdXJjZSBtYXAgYmVpbmcgZ2VuZXJhdGVkIHRvIGEgc3RyaW5nLlxuICovXG5Tb3VyY2VNYXBHZW5lcmF0b3IucHJvdG90eXBlLnRvU3RyaW5nID1cbiAgZnVuY3Rpb24gU291cmNlTWFwR2VuZXJhdG9yX3RvU3RyaW5nKCkge1xuICAgIHJldHVybiBKU09OLnN0cmluZ2lmeSh0aGlzLnRvSlNPTigpKTtcbiAgfTtcblxuZXhwb3J0cy5Tb3VyY2VNYXBHZW5lcmF0b3IgPSBTb3VyY2VNYXBHZW5lcmF0b3I7XG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvci5qc1xuLy8gbW9kdWxlIGlkID0gMVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICpcbiAqIEJhc2VkIG9uIHRoZSBCYXNlIDY0IFZMUSBpbXBsZW1lbnRhdGlvbiBpbiBDbG9zdXJlIENvbXBpbGVyOlxuICogaHR0cHM6Ly9jb2RlLmdvb2dsZS5jb20vcC9jbG9zdXJlLWNvbXBpbGVyL3NvdXJjZS9icm93c2UvdHJ1bmsvc3JjL2NvbS9nb29nbGUvZGVidWdnaW5nL3NvdXJjZW1hcC9CYXNlNjRWTFEuamF2YVxuICpcbiAqIENvcHlyaWdodCAyMDExIFRoZSBDbG9zdXJlIENvbXBpbGVyIEF1dGhvcnMuIEFsbCByaWdodHMgcmVzZXJ2ZWQuXG4gKiBSZWRpc3RyaWJ1dGlvbiBhbmQgdXNlIGluIHNvdXJjZSBhbmQgYmluYXJ5IGZvcm1zLCB3aXRoIG9yIHdpdGhvdXRcbiAqIG1vZGlmaWNhdGlvbiwgYXJlIHBlcm1pdHRlZCBwcm92aWRlZCB0aGF0IHRoZSBmb2xsb3dpbmcgY29uZGl0aW9ucyBhcmVcbiAqIG1ldDpcbiAqXG4gKiAgKiBSZWRpc3RyaWJ1dGlvbnMgb2Ygc291cmNlIGNvZGUgbXVzdCByZXRhaW4gdGhlIGFib3ZlIGNvcHlyaWdodFxuICogICAgbm90aWNlLCB0aGlzIGxpc3Qgb2YgY29uZGl0aW9ucyBhbmQgdGhlIGZvbGxvd2luZyBkaXNjbGFpbWVyLlxuICogICogUmVkaXN0cmlidXRpb25zIGluIGJpbmFyeSBmb3JtIG11c3QgcmVwcm9kdWNlIHRoZSBhYm92ZVxuICogICAgY29weXJpZ2h0IG5vdGljZSwgdGhpcyBsaXN0IG9mIGNvbmRpdGlvbnMgYW5kIHRoZSBmb2xsb3dpbmdcbiAqICAgIGRpc2NsYWltZXIgaW4gdGhlIGRvY3VtZW50YXRpb24gYW5kL29yIG90aGVyIG1hdGVyaWFscyBwcm92aWRlZFxuICogICAgd2l0aCB0aGUgZGlzdHJpYnV0aW9uLlxuICogICogTmVpdGhlciB0aGUgbmFtZSBvZiBHb29nbGUgSW5jLiBub3IgdGhlIG5hbWVzIG9mIGl0c1xuICogICAgY29udHJpYnV0b3JzIG1heSBiZSB1c2VkIHRvIGVuZG9yc2Ugb3IgcHJvbW90ZSBwcm9kdWN0cyBkZXJpdmVkXG4gKiAgICBmcm9tIHRoaXMgc29mdHdhcmUgd2l0aG91dCBzcGVjaWZpYyBwcmlvciB3cml0dGVuIHBlcm1pc3Npb24uXG4gKlxuICogVEhJUyBTT0ZUV0FSRSBJUyBQUk9WSURFRCBCWSBUSEUgQ09QWVJJR0hUIEhPTERFUlMgQU5EIENPTlRSSUJVVE9SU1xuICogXCJBUyBJU1wiIEFORCBBTlkgRVhQUkVTUyBPUiBJTVBMSUVEIFdBUlJBTlRJRVMsIElOQ0xVRElORywgQlVUIE5PVFxuICogTElNSVRFRCBUTywgVEhFIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkgQU5EIEZJVE5FU1MgRk9SXG4gKiBBIFBBUlRJQ1VMQVIgUFVSUE9TRSBBUkUgRElTQ0xBSU1FRC4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIENPUFlSSUdIVFxuICogT1dORVIgT1IgQ09OVFJJQlVUT1JTIEJFIExJQUJMRSBGT1IgQU5ZIERJUkVDVCwgSU5ESVJFQ1QsIElOQ0lERU5UQUwsXG4gKiBTUEVDSUFMLCBFWEVNUExBUlksIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyAoSU5DTFVESU5HLCBCVVQgTk9UXG4gKiBMSU1JVEVEIFRPLCBQUk9DVVJFTUVOVCBPRiBTVUJTVElUVVRFIEdPT0RTIE9SIFNFUlZJQ0VTOyBMT1NTIE9GIFVTRSxcbiAqIERBVEEsIE9SIFBST0ZJVFM7IE9SIEJVU0lORVNTIElOVEVSUlVQVElPTikgSE9XRVZFUiBDQVVTRUQgQU5EIE9OIEFOWVxuICogVEhFT1JZIE9GIExJQUJJTElUWSwgV0hFVEhFUiBJTiBDT05UUkFDVCwgU1RSSUNUIExJQUJJTElUWSwgT1IgVE9SVFxuICogKElOQ0xVRElORyBORUdMSUdFTkNFIE9SIE9USEVSV0lTRSkgQVJJU0lORyBJTiBBTlkgV0FZIE9VVCBPRiBUSEUgVVNFXG4gKiBPRiBUSElTIFNPRlRXQVJFLCBFVkVOIElGIEFEVklTRUQgT0YgVEhFIFBPU1NJQklMSVRZIE9GIFNVQ0ggREFNQUdFLlxuICovXG5cbnZhciBiYXNlNjQgPSByZXF1aXJlKCcuL2Jhc2U2NCcpO1xuXG4vLyBBIHNpbmdsZSBiYXNlIDY0IGRpZ2l0IGNhbiBjb250YWluIDYgYml0cyBvZiBkYXRhLiBGb3IgdGhlIGJhc2UgNjQgdmFyaWFibGVcbi8vIGxlbmd0aCBxdWFudGl0aWVzIHdlIHVzZSBpbiB0aGUgc291cmNlIG1hcCBzcGVjLCB0aGUgZmlyc3QgYml0IGlzIHRoZSBzaWduLFxuLy8gdGhlIG5leHQgZm91ciBiaXRzIGFyZSB0aGUgYWN0dWFsIHZhbHVlLCBhbmQgdGhlIDZ0aCBiaXQgaXMgdGhlXG4vLyBjb250aW51YXRpb24gYml0LiBUaGUgY29udGludWF0aW9uIGJpdCB0ZWxscyB1cyB3aGV0aGVyIHRoZXJlIGFyZSBtb3JlXG4vLyBkaWdpdHMgaW4gdGhpcyB2YWx1ZSBmb2xsb3dpbmcgdGhpcyBkaWdpdC5cbi8vXG4vLyAgIENvbnRpbnVhdGlvblxuLy8gICB8ICAgIFNpZ25cbi8vICAgfCAgICB8XG4vLyAgIFYgICAgVlxuLy8gICAxMDEwMTFcblxudmFyIFZMUV9CQVNFX1NISUZUID0gNTtcblxuLy8gYmluYXJ5OiAxMDAwMDBcbnZhciBWTFFfQkFTRSA9IDEgPDwgVkxRX0JBU0VfU0hJRlQ7XG5cbi8vIGJpbmFyeTogMDExMTExXG52YXIgVkxRX0JBU0VfTUFTSyA9IFZMUV9CQVNFIC0gMTtcblxuLy8gYmluYXJ5OiAxMDAwMDBcbnZhciBWTFFfQ09OVElOVUFUSU9OX0JJVCA9IFZMUV9CQVNFO1xuXG4vKipcbiAqIENvbnZlcnRzIGZyb20gYSB0d28tY29tcGxlbWVudCB2YWx1ZSB0byBhIHZhbHVlIHdoZXJlIHRoZSBzaWduIGJpdCBpc1xuICogcGxhY2VkIGluIHRoZSBsZWFzdCBzaWduaWZpY2FudCBiaXQuICBGb3IgZXhhbXBsZSwgYXMgZGVjaW1hbHM6XG4gKiAgIDEgYmVjb21lcyAyICgxMCBiaW5hcnkpLCAtMSBiZWNvbWVzIDMgKDExIGJpbmFyeSlcbiAqICAgMiBiZWNvbWVzIDQgKDEwMCBiaW5hcnkpLCAtMiBiZWNvbWVzIDUgKDEwMSBiaW5hcnkpXG4gKi9cbmZ1bmN0aW9uIHRvVkxRU2lnbmVkKGFWYWx1ZSkge1xuICByZXR1cm4gYVZhbHVlIDwgMFxuICAgID8gKCgtYVZhbHVlKSA8PCAxKSArIDFcbiAgICA6IChhVmFsdWUgPDwgMSkgKyAwO1xufVxuXG4vKipcbiAqIENvbnZlcnRzIHRvIGEgdHdvLWNvbXBsZW1lbnQgdmFsdWUgZnJvbSBhIHZhbHVlIHdoZXJlIHRoZSBzaWduIGJpdCBpc1xuICogcGxhY2VkIGluIHRoZSBsZWFzdCBzaWduaWZpY2FudCBiaXQuICBGb3IgZXhhbXBsZSwgYXMgZGVjaW1hbHM6XG4gKiAgIDIgKDEwIGJpbmFyeSkgYmVjb21lcyAxLCAzICgxMSBiaW5hcnkpIGJlY29tZXMgLTFcbiAqICAgNCAoMTAwIGJpbmFyeSkgYmVjb21lcyAyLCA1ICgxMDEgYmluYXJ5KSBiZWNvbWVzIC0yXG4gKi9cbmZ1bmN0aW9uIGZyb21WTFFTaWduZWQoYVZhbHVlKSB7XG4gIHZhciBpc05lZ2F0aXZlID0gKGFWYWx1ZSAmIDEpID09PSAxO1xuICB2YXIgc2hpZnRlZCA9IGFWYWx1ZSA+PiAxO1xuICByZXR1cm4gaXNOZWdhdGl2ZVxuICAgID8gLXNoaWZ0ZWRcbiAgICA6IHNoaWZ0ZWQ7XG59XG5cbi8qKlxuICogUmV0dXJucyB0aGUgYmFzZSA2NCBWTFEgZW5jb2RlZCB2YWx1ZS5cbiAqL1xuZXhwb3J0cy5lbmNvZGUgPSBmdW5jdGlvbiBiYXNlNjRWTFFfZW5jb2RlKGFWYWx1ZSkge1xuICB2YXIgZW5jb2RlZCA9IFwiXCI7XG4gIHZhciBkaWdpdDtcblxuICB2YXIgdmxxID0gdG9WTFFTaWduZWQoYVZhbHVlKTtcblxuICBkbyB7XG4gICAgZGlnaXQgPSB2bHEgJiBWTFFfQkFTRV9NQVNLO1xuICAgIHZscSA+Pj49IFZMUV9CQVNFX1NISUZUO1xuICAgIGlmICh2bHEgPiAwKSB7XG4gICAgICAvLyBUaGVyZSBhcmUgc3RpbGwgbW9yZSBkaWdpdHMgaW4gdGhpcyB2YWx1ZSwgc28gd2UgbXVzdCBtYWtlIHN1cmUgdGhlXG4gICAgICAvLyBjb250aW51YXRpb24gYml0IGlzIG1hcmtlZC5cbiAgICAgIGRpZ2l0IHw9IFZMUV9DT05USU5VQVRJT05fQklUO1xuICAgIH1cbiAgICBlbmNvZGVkICs9IGJhc2U2NC5lbmNvZGUoZGlnaXQpO1xuICB9IHdoaWxlICh2bHEgPiAwKTtcblxuICByZXR1cm4gZW5jb2RlZDtcbn07XG5cbi8qKlxuICogRGVjb2RlcyB0aGUgbmV4dCBiYXNlIDY0IFZMUSB2YWx1ZSBmcm9tIHRoZSBnaXZlbiBzdHJpbmcgYW5kIHJldHVybnMgdGhlXG4gKiB2YWx1ZSBhbmQgdGhlIHJlc3Qgb2YgdGhlIHN0cmluZyB2aWEgdGhlIG91dCBwYXJhbWV0ZXIuXG4gKi9cbmV4cG9ydHMuZGVjb2RlID0gZnVuY3Rpb24gYmFzZTY0VkxRX2RlY29kZShhU3RyLCBhSW5kZXgsIGFPdXRQYXJhbSkge1xuICB2YXIgc3RyTGVuID0gYVN0ci5sZW5ndGg7XG4gIHZhciByZXN1bHQgPSAwO1xuICB2YXIgc2hpZnQgPSAwO1xuICB2YXIgY29udGludWF0aW9uLCBkaWdpdDtcblxuICBkbyB7XG4gICAgaWYgKGFJbmRleCA+PSBzdHJMZW4pIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcihcIkV4cGVjdGVkIG1vcmUgZGlnaXRzIGluIGJhc2UgNjQgVkxRIHZhbHVlLlwiKTtcbiAgICB9XG5cbiAgICBkaWdpdCA9IGJhc2U2NC5kZWNvZGUoYVN0ci5jaGFyQ29kZUF0KGFJbmRleCsrKSk7XG4gICAgaWYgKGRpZ2l0ID09PSAtMSkge1xuICAgICAgdGhyb3cgbmV3IEVycm9yKFwiSW52YWxpZCBiYXNlNjQgZGlnaXQ6IFwiICsgYVN0ci5jaGFyQXQoYUluZGV4IC0gMSkpO1xuICAgIH1cblxuICAgIGNvbnRpbnVhdGlvbiA9ICEhKGRpZ2l0ICYgVkxRX0NPTlRJTlVBVElPTl9CSVQpO1xuICAgIGRpZ2l0ICY9IFZMUV9CQVNFX01BU0s7XG4gICAgcmVzdWx0ID0gcmVzdWx0ICsgKGRpZ2l0IDw8IHNoaWZ0KTtcbiAgICBzaGlmdCArPSBWTFFfQkFTRV9TSElGVDtcbiAgfSB3aGlsZSAoY29udGludWF0aW9uKTtcblxuICBhT3V0UGFyYW0udmFsdWUgPSBmcm9tVkxRU2lnbmVkKHJlc3VsdCk7XG4gIGFPdXRQYXJhbS5yZXN0ID0gYUluZGV4O1xufTtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL2Jhc2U2NC12bHEuanNcbi8vIG1vZHVsZSBpZCA9IDJcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgaW50VG9DaGFyTWFwID0gJ0FCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU2Nzg5Ky8nLnNwbGl0KCcnKTtcblxuLyoqXG4gKiBFbmNvZGUgYW4gaW50ZWdlciBpbiB0aGUgcmFuZ2Ugb2YgMCB0byA2MyB0byBhIHNpbmdsZSBiYXNlIDY0IGRpZ2l0LlxuICovXG5leHBvcnRzLmVuY29kZSA9IGZ1bmN0aW9uIChudW1iZXIpIHtcbiAgaWYgKDAgPD0gbnVtYmVyICYmIG51bWJlciA8IGludFRvQ2hhck1hcC5sZW5ndGgpIHtcbiAgICByZXR1cm4gaW50VG9DaGFyTWFwW251bWJlcl07XG4gIH1cbiAgdGhyb3cgbmV3IFR5cGVFcnJvcihcIk11c3QgYmUgYmV0d2VlbiAwIGFuZCA2MzogXCIgKyBudW1iZXIpO1xufTtcblxuLyoqXG4gKiBEZWNvZGUgYSBzaW5nbGUgYmFzZSA2NCBjaGFyYWN0ZXIgY29kZSBkaWdpdCB0byBhbiBpbnRlZ2VyLiBSZXR1cm5zIC0xIG9uXG4gKiBmYWlsdXJlLlxuICovXG5leHBvcnRzLmRlY29kZSA9IGZ1bmN0aW9uIChjaGFyQ29kZSkge1xuICB2YXIgYmlnQSA9IDY1OyAgICAgLy8gJ0EnXG4gIHZhciBiaWdaID0gOTA7ICAgICAvLyAnWidcblxuICB2YXIgbGl0dGxlQSA9IDk3OyAgLy8gJ2EnXG4gIHZhciBsaXR0bGVaID0gMTIyOyAvLyAneidcblxuICB2YXIgemVybyA9IDQ4OyAgICAgLy8gJzAnXG4gIHZhciBuaW5lID0gNTc7ICAgICAvLyAnOSdcblxuICB2YXIgcGx1cyA9IDQzOyAgICAgLy8gJysnXG4gIHZhciBzbGFzaCA9IDQ3OyAgICAvLyAnLydcblxuICB2YXIgbGl0dGxlT2Zmc2V0ID0gMjY7XG4gIHZhciBudW1iZXJPZmZzZXQgPSA1MjtcblxuICAvLyAwIC0gMjU6IEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaXG4gIGlmIChiaWdBIDw9IGNoYXJDb2RlICYmIGNoYXJDb2RlIDw9IGJpZ1opIHtcbiAgICByZXR1cm4gKGNoYXJDb2RlIC0gYmlnQSk7XG4gIH1cblxuICAvLyAyNiAtIDUxOiBhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5elxuICBpZiAobGl0dGxlQSA8PSBjaGFyQ29kZSAmJiBjaGFyQ29kZSA8PSBsaXR0bGVaKSB7XG4gICAgcmV0dXJuIChjaGFyQ29kZSAtIGxpdHRsZUEgKyBsaXR0bGVPZmZzZXQpO1xuICB9XG5cbiAgLy8gNTIgLSA2MTogMDEyMzQ1Njc4OVxuICBpZiAoemVybyA8PSBjaGFyQ29kZSAmJiBjaGFyQ29kZSA8PSBuaW5lKSB7XG4gICAgcmV0dXJuIChjaGFyQ29kZSAtIHplcm8gKyBudW1iZXJPZmZzZXQpO1xuICB9XG5cbiAgLy8gNjI6ICtcbiAgaWYgKGNoYXJDb2RlID09IHBsdXMpIHtcbiAgICByZXR1cm4gNjI7XG4gIH1cblxuICAvLyA2MzogL1xuICBpZiAoY2hhckNvZGUgPT0gc2xhc2gpIHtcbiAgICByZXR1cm4gNjM7XG4gIH1cblxuICAvLyBJbnZhbGlkIGJhc2U2NCBkaWdpdC5cbiAgcmV0dXJuIC0xO1xufTtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL2Jhc2U2NC5qc1xuLy8gbW9kdWxlIGlkID0gM1xuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbi8qKlxuICogVGhpcyBpcyBhIGhlbHBlciBmdW5jdGlvbiBmb3IgZ2V0dGluZyB2YWx1ZXMgZnJvbSBwYXJhbWV0ZXIvb3B0aW9uc1xuICogb2JqZWN0cy5cbiAqXG4gKiBAcGFyYW0gYXJncyBUaGUgb2JqZWN0IHdlIGFyZSBleHRyYWN0aW5nIHZhbHVlcyBmcm9tXG4gKiBAcGFyYW0gbmFtZSBUaGUgbmFtZSBvZiB0aGUgcHJvcGVydHkgd2UgYXJlIGdldHRpbmcuXG4gKiBAcGFyYW0gZGVmYXVsdFZhbHVlIEFuIG9wdGlvbmFsIHZhbHVlIHRvIHJldHVybiBpZiB0aGUgcHJvcGVydHkgaXMgbWlzc2luZ1xuICogZnJvbSB0aGUgb2JqZWN0LiBJZiB0aGlzIGlzIG5vdCBzcGVjaWZpZWQgYW5kIHRoZSBwcm9wZXJ0eSBpcyBtaXNzaW5nLCBhblxuICogZXJyb3Igd2lsbCBiZSB0aHJvd24uXG4gKi9cbmZ1bmN0aW9uIGdldEFyZyhhQXJncywgYU5hbWUsIGFEZWZhdWx0VmFsdWUpIHtcbiAgaWYgKGFOYW1lIGluIGFBcmdzKSB7XG4gICAgcmV0dXJuIGFBcmdzW2FOYW1lXTtcbiAgfSBlbHNlIGlmIChhcmd1bWVudHMubGVuZ3RoID09PSAzKSB7XG4gICAgcmV0dXJuIGFEZWZhdWx0VmFsdWU7XG4gIH0gZWxzZSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKCdcIicgKyBhTmFtZSArICdcIiBpcyBhIHJlcXVpcmVkIGFyZ3VtZW50LicpO1xuICB9XG59XG5leHBvcnRzLmdldEFyZyA9IGdldEFyZztcblxudmFyIHVybFJlZ2V4cCA9IC9eKD86KFtcXHcrXFwtLl0rKTopP1xcL1xcLyg/OihcXHcrOlxcdyspQCk/KFtcXHcuLV0qKSg/OjooXFxkKykpPyguKikkLztcbnZhciBkYXRhVXJsUmVnZXhwID0gL15kYXRhOi4rXFwsLiskLztcblxuZnVuY3Rpb24gdXJsUGFyc2UoYVVybCkge1xuICB2YXIgbWF0Y2ggPSBhVXJsLm1hdGNoKHVybFJlZ2V4cCk7XG4gIGlmICghbWF0Y2gpIHtcbiAgICByZXR1cm4gbnVsbDtcbiAgfVxuICByZXR1cm4ge1xuICAgIHNjaGVtZTogbWF0Y2hbMV0sXG4gICAgYXV0aDogbWF0Y2hbMl0sXG4gICAgaG9zdDogbWF0Y2hbM10sXG4gICAgcG9ydDogbWF0Y2hbNF0sXG4gICAgcGF0aDogbWF0Y2hbNV1cbiAgfTtcbn1cbmV4cG9ydHMudXJsUGFyc2UgPSB1cmxQYXJzZTtcblxuZnVuY3Rpb24gdXJsR2VuZXJhdGUoYVBhcnNlZFVybCkge1xuICB2YXIgdXJsID0gJyc7XG4gIGlmIChhUGFyc2VkVXJsLnNjaGVtZSkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLnNjaGVtZSArICc6JztcbiAgfVxuICB1cmwgKz0gJy8vJztcbiAgaWYgKGFQYXJzZWRVcmwuYXV0aCkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLmF1dGggKyAnQCc7XG4gIH1cbiAgaWYgKGFQYXJzZWRVcmwuaG9zdCkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLmhvc3Q7XG4gIH1cbiAgaWYgKGFQYXJzZWRVcmwucG9ydCkge1xuICAgIHVybCArPSBcIjpcIiArIGFQYXJzZWRVcmwucG9ydFxuICB9XG4gIGlmIChhUGFyc2VkVXJsLnBhdGgpIHtcbiAgICB1cmwgKz0gYVBhcnNlZFVybC5wYXRoO1xuICB9XG4gIHJldHVybiB1cmw7XG59XG5leHBvcnRzLnVybEdlbmVyYXRlID0gdXJsR2VuZXJhdGU7XG5cbi8qKlxuICogTm9ybWFsaXplcyBhIHBhdGgsIG9yIHRoZSBwYXRoIHBvcnRpb24gb2YgYSBVUkw6XG4gKlxuICogLSBSZXBsYWNlcyBjb25zZWN1dGl2ZSBzbGFzaGVzIHdpdGggb25lIHNsYXNoLlxuICogLSBSZW1vdmVzIHVubmVjZXNzYXJ5ICcuJyBwYXJ0cy5cbiAqIC0gUmVtb3ZlcyB1bm5lY2Vzc2FyeSAnPGRpcj4vLi4nIHBhcnRzLlxuICpcbiAqIEJhc2VkIG9uIGNvZGUgaW4gdGhlIE5vZGUuanMgJ3BhdGgnIGNvcmUgbW9kdWxlLlxuICpcbiAqIEBwYXJhbSBhUGF0aCBUaGUgcGF0aCBvciB1cmwgdG8gbm9ybWFsaXplLlxuICovXG5mdW5jdGlvbiBub3JtYWxpemUoYVBhdGgpIHtcbiAgdmFyIHBhdGggPSBhUGF0aDtcbiAgdmFyIHVybCA9IHVybFBhcnNlKGFQYXRoKTtcbiAgaWYgKHVybCkge1xuICAgIGlmICghdXJsLnBhdGgpIHtcbiAgICAgIHJldHVybiBhUGF0aDtcbiAgICB9XG4gICAgcGF0aCA9IHVybC5wYXRoO1xuICB9XG4gIHZhciBpc0Fic29sdXRlID0gZXhwb3J0cy5pc0Fic29sdXRlKHBhdGgpO1xuXG4gIHZhciBwYXJ0cyA9IHBhdGguc3BsaXQoL1xcLysvKTtcbiAgZm9yICh2YXIgcGFydCwgdXAgPSAwLCBpID0gcGFydHMubGVuZ3RoIC0gMTsgaSA+PSAwOyBpLS0pIHtcbiAgICBwYXJ0ID0gcGFydHNbaV07XG4gICAgaWYgKHBhcnQgPT09ICcuJykge1xuICAgICAgcGFydHMuc3BsaWNlKGksIDEpO1xuICAgIH0gZWxzZSBpZiAocGFydCA9PT0gJy4uJykge1xuICAgICAgdXArKztcbiAgICB9IGVsc2UgaWYgKHVwID4gMCkge1xuICAgICAgaWYgKHBhcnQgPT09ICcnKSB7XG4gICAgICAgIC8vIFRoZSBmaXJzdCBwYXJ0IGlzIGJsYW5rIGlmIHRoZSBwYXRoIGlzIGFic29sdXRlLiBUcnlpbmcgdG8gZ29cbiAgICAgICAgLy8gYWJvdmUgdGhlIHJvb3QgaXMgYSBuby1vcC4gVGhlcmVmb3JlIHdlIGNhbiByZW1vdmUgYWxsICcuLicgcGFydHNcbiAgICAgICAgLy8gZGlyZWN0bHkgYWZ0ZXIgdGhlIHJvb3QuXG4gICAgICAgIHBhcnRzLnNwbGljZShpICsgMSwgdXApO1xuICAgICAgICB1cCA9IDA7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBwYXJ0cy5zcGxpY2UoaSwgMik7XG4gICAgICAgIHVwLS07XG4gICAgICB9XG4gICAgfVxuICB9XG4gIHBhdGggPSBwYXJ0cy5qb2luKCcvJyk7XG5cbiAgaWYgKHBhdGggPT09ICcnKSB7XG4gICAgcGF0aCA9IGlzQWJzb2x1dGUgPyAnLycgOiAnLic7XG4gIH1cblxuICBpZiAodXJsKSB7XG4gICAgdXJsLnBhdGggPSBwYXRoO1xuICAgIHJldHVybiB1cmxHZW5lcmF0ZSh1cmwpO1xuICB9XG4gIHJldHVybiBwYXRoO1xufVxuZXhwb3J0cy5ub3JtYWxpemUgPSBub3JtYWxpemU7XG5cbi8qKlxuICogSm9pbnMgdHdvIHBhdGhzL1VSTHMuXG4gKlxuICogQHBhcmFtIGFSb290IFRoZSByb290IHBhdGggb3IgVVJMLlxuICogQHBhcmFtIGFQYXRoIFRoZSBwYXRoIG9yIFVSTCB0byBiZSBqb2luZWQgd2l0aCB0aGUgcm9vdC5cbiAqXG4gKiAtIElmIGFQYXRoIGlzIGEgVVJMIG9yIGEgZGF0YSBVUkksIGFQYXRoIGlzIHJldHVybmVkLCB1bmxlc3MgYVBhdGggaXMgYVxuICogICBzY2hlbWUtcmVsYXRpdmUgVVJMOiBUaGVuIHRoZSBzY2hlbWUgb2YgYVJvb3QsIGlmIGFueSwgaXMgcHJlcGVuZGVkXG4gKiAgIGZpcnN0LlxuICogLSBPdGhlcndpc2UgYVBhdGggaXMgYSBwYXRoLiBJZiBhUm9vdCBpcyBhIFVSTCwgdGhlbiBpdHMgcGF0aCBwb3J0aW9uXG4gKiAgIGlzIHVwZGF0ZWQgd2l0aCB0aGUgcmVzdWx0IGFuZCBhUm9vdCBpcyByZXR1cm5lZC4gT3RoZXJ3aXNlIHRoZSByZXN1bHRcbiAqICAgaXMgcmV0dXJuZWQuXG4gKiAgIC0gSWYgYVBhdGggaXMgYWJzb2x1dGUsIHRoZSByZXN1bHQgaXMgYVBhdGguXG4gKiAgIC0gT3RoZXJ3aXNlIHRoZSB0d28gcGF0aHMgYXJlIGpvaW5lZCB3aXRoIGEgc2xhc2guXG4gKiAtIEpvaW5pbmcgZm9yIGV4YW1wbGUgJ2h0dHA6Ly8nIGFuZCAnd3d3LmV4YW1wbGUuY29tJyBpcyBhbHNvIHN1cHBvcnRlZC5cbiAqL1xuZnVuY3Rpb24gam9pbihhUm9vdCwgYVBhdGgpIHtcbiAgaWYgKGFSb290ID09PSBcIlwiKSB7XG4gICAgYVJvb3QgPSBcIi5cIjtcbiAgfVxuICBpZiAoYVBhdGggPT09IFwiXCIpIHtcbiAgICBhUGF0aCA9IFwiLlwiO1xuICB9XG4gIHZhciBhUGF0aFVybCA9IHVybFBhcnNlKGFQYXRoKTtcbiAgdmFyIGFSb290VXJsID0gdXJsUGFyc2UoYVJvb3QpO1xuICBpZiAoYVJvb3RVcmwpIHtcbiAgICBhUm9vdCA9IGFSb290VXJsLnBhdGggfHwgJy8nO1xuICB9XG5cbiAgLy8gYGpvaW4oZm9vLCAnLy93d3cuZXhhbXBsZS5vcmcnKWBcbiAgaWYgKGFQYXRoVXJsICYmICFhUGF0aFVybC5zY2hlbWUpIHtcbiAgICBpZiAoYVJvb3RVcmwpIHtcbiAgICAgIGFQYXRoVXJsLnNjaGVtZSA9IGFSb290VXJsLnNjaGVtZTtcbiAgICB9XG4gICAgcmV0dXJuIHVybEdlbmVyYXRlKGFQYXRoVXJsKTtcbiAgfVxuXG4gIGlmIChhUGF0aFVybCB8fCBhUGF0aC5tYXRjaChkYXRhVXJsUmVnZXhwKSkge1xuICAgIHJldHVybiBhUGF0aDtcbiAgfVxuXG4gIC8vIGBqb2luKCdodHRwOi8vJywgJ3d3dy5leGFtcGxlLmNvbScpYFxuICBpZiAoYVJvb3RVcmwgJiYgIWFSb290VXJsLmhvc3QgJiYgIWFSb290VXJsLnBhdGgpIHtcbiAgICBhUm9vdFVybC5ob3N0ID0gYVBhdGg7XG4gICAgcmV0dXJuIHVybEdlbmVyYXRlKGFSb290VXJsKTtcbiAgfVxuXG4gIHZhciBqb2luZWQgPSBhUGF0aC5jaGFyQXQoMCkgPT09ICcvJ1xuICAgID8gYVBhdGhcbiAgICA6IG5vcm1hbGl6ZShhUm9vdC5yZXBsYWNlKC9cXC8rJC8sICcnKSArICcvJyArIGFQYXRoKTtcblxuICBpZiAoYVJvb3RVcmwpIHtcbiAgICBhUm9vdFVybC5wYXRoID0gam9pbmVkO1xuICAgIHJldHVybiB1cmxHZW5lcmF0ZShhUm9vdFVybCk7XG4gIH1cbiAgcmV0dXJuIGpvaW5lZDtcbn1cbmV4cG9ydHMuam9pbiA9IGpvaW47XG5cbmV4cG9ydHMuaXNBYnNvbHV0ZSA9IGZ1bmN0aW9uIChhUGF0aCkge1xuICByZXR1cm4gYVBhdGguY2hhckF0KDApID09PSAnLycgfHwgdXJsUmVnZXhwLnRlc3QoYVBhdGgpO1xufTtcblxuLyoqXG4gKiBNYWtlIGEgcGF0aCByZWxhdGl2ZSB0byBhIFVSTCBvciBhbm90aGVyIHBhdGguXG4gKlxuICogQHBhcmFtIGFSb290IFRoZSByb290IHBhdGggb3IgVVJMLlxuICogQHBhcmFtIGFQYXRoIFRoZSBwYXRoIG9yIFVSTCB0byBiZSBtYWRlIHJlbGF0aXZlIHRvIGFSb290LlxuICovXG5mdW5jdGlvbiByZWxhdGl2ZShhUm9vdCwgYVBhdGgpIHtcbiAgaWYgKGFSb290ID09PSBcIlwiKSB7XG4gICAgYVJvb3QgPSBcIi5cIjtcbiAgfVxuXG4gIGFSb290ID0gYVJvb3QucmVwbGFjZSgvXFwvJC8sICcnKTtcblxuICAvLyBJdCBpcyBwb3NzaWJsZSBmb3IgdGhlIHBhdGggdG8gYmUgYWJvdmUgdGhlIHJvb3QuIEluIHRoaXMgY2FzZSwgc2ltcGx5XG4gIC8vIGNoZWNraW5nIHdoZXRoZXIgdGhlIHJvb3QgaXMgYSBwcmVmaXggb2YgdGhlIHBhdGggd29uJ3Qgd29yay4gSW5zdGVhZCwgd2VcbiAgLy8gbmVlZCB0byByZW1vdmUgY29tcG9uZW50cyBmcm9tIHRoZSByb290IG9uZSBieSBvbmUsIHVudGlsIGVpdGhlciB3ZSBmaW5kXG4gIC8vIGEgcHJlZml4IHRoYXQgZml0cywgb3Igd2UgcnVuIG91dCBvZiBjb21wb25lbnRzIHRvIHJlbW92ZS5cbiAgdmFyIGxldmVsID0gMDtcbiAgd2hpbGUgKGFQYXRoLmluZGV4T2YoYVJvb3QgKyAnLycpICE9PSAwKSB7XG4gICAgdmFyIGluZGV4ID0gYVJvb3QubGFzdEluZGV4T2YoXCIvXCIpO1xuICAgIGlmIChpbmRleCA8IDApIHtcbiAgICAgIHJldHVybiBhUGF0aDtcbiAgICB9XG5cbiAgICAvLyBJZiB0aGUgb25seSBwYXJ0IG9mIHRoZSByb290IHRoYXQgaXMgbGVmdCBpcyB0aGUgc2NoZW1lIChpLmUuIGh0dHA6Ly8sXG4gICAgLy8gZmlsZTovLy8sIGV0Yy4pLCBvbmUgb3IgbW9yZSBzbGFzaGVzICgvKSwgb3Igc2ltcGx5IG5vdGhpbmcgYXQgYWxsLCB3ZVxuICAgIC8vIGhhdmUgZXhoYXVzdGVkIGFsbCBjb21wb25lbnRzLCBzbyB0aGUgcGF0aCBpcyBub3QgcmVsYXRpdmUgdG8gdGhlIHJvb3QuXG4gICAgYVJvb3QgPSBhUm9vdC5zbGljZSgwLCBpbmRleCk7XG4gICAgaWYgKGFSb290Lm1hdGNoKC9eKFteXFwvXSs6XFwvKT9cXC8qJC8pKSB7XG4gICAgICByZXR1cm4gYVBhdGg7XG4gICAgfVxuXG4gICAgKytsZXZlbDtcbiAgfVxuXG4gIC8vIE1ha2Ugc3VyZSB3ZSBhZGQgYSBcIi4uL1wiIGZvciBlYWNoIGNvbXBvbmVudCB3ZSByZW1vdmVkIGZyb20gdGhlIHJvb3QuXG4gIHJldHVybiBBcnJheShsZXZlbCArIDEpLmpvaW4oXCIuLi9cIikgKyBhUGF0aC5zdWJzdHIoYVJvb3QubGVuZ3RoICsgMSk7XG59XG5leHBvcnRzLnJlbGF0aXZlID0gcmVsYXRpdmU7XG5cbnZhciBzdXBwb3J0c051bGxQcm90byA9IChmdW5jdGlvbiAoKSB7XG4gIHZhciBvYmogPSBPYmplY3QuY3JlYXRlKG51bGwpO1xuICByZXR1cm4gISgnX19wcm90b19fJyBpbiBvYmopO1xufSgpKTtcblxuZnVuY3Rpb24gaWRlbnRpdHkgKHMpIHtcbiAgcmV0dXJuIHM7XG59XG5cbi8qKlxuICogQmVjYXVzZSBiZWhhdmlvciBnb2VzIHdhY2t5IHdoZW4geW91IHNldCBgX19wcm90b19fYCBvbiBvYmplY3RzLCB3ZVxuICogaGF2ZSB0byBwcmVmaXggYWxsIHRoZSBzdHJpbmdzIGluIG91ciBzZXQgd2l0aCBhbiBhcmJpdHJhcnkgY2hhcmFjdGVyLlxuICpcbiAqIFNlZSBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL3B1bGwvMzEgYW5kXG4gKiBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL2lzc3Vlcy8zMFxuICpcbiAqIEBwYXJhbSBTdHJpbmcgYVN0clxuICovXG5mdW5jdGlvbiB0b1NldFN0cmluZyhhU3RyKSB7XG4gIGlmIChpc1Byb3RvU3RyaW5nKGFTdHIpKSB7XG4gICAgcmV0dXJuICckJyArIGFTdHI7XG4gIH1cblxuICByZXR1cm4gYVN0cjtcbn1cbmV4cG9ydHMudG9TZXRTdHJpbmcgPSBzdXBwb3J0c051bGxQcm90byA/IGlkZW50aXR5IDogdG9TZXRTdHJpbmc7XG5cbmZ1bmN0aW9uIGZyb21TZXRTdHJpbmcoYVN0cikge1xuICBpZiAoaXNQcm90b1N0cmluZyhhU3RyKSkge1xuICAgIHJldHVybiBhU3RyLnNsaWNlKDEpO1xuICB9XG5cbiAgcmV0dXJuIGFTdHI7XG59XG5leHBvcnRzLmZyb21TZXRTdHJpbmcgPSBzdXBwb3J0c051bGxQcm90byA/IGlkZW50aXR5IDogZnJvbVNldFN0cmluZztcblxuZnVuY3Rpb24gaXNQcm90b1N0cmluZyhzKSB7XG4gIGlmICghcykge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIHZhciBsZW5ndGggPSBzLmxlbmd0aDtcblxuICBpZiAobGVuZ3RoIDwgOSAvKiBcIl9fcHJvdG9fX1wiLmxlbmd0aCAqLykge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIGlmIChzLmNoYXJDb2RlQXQobGVuZ3RoIC0gMSkgIT09IDk1ICAvKiAnXycgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSAyKSAhPT0gOTUgIC8qICdfJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDMpICE9PSAxMTEgLyogJ28nICovIHx8XG4gICAgICBzLmNoYXJDb2RlQXQobGVuZ3RoIC0gNCkgIT09IDExNiAvKiAndCcgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSA1KSAhPT0gMTExIC8qICdvJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDYpICE9PSAxMTQgLyogJ3InICovIHx8XG4gICAgICBzLmNoYXJDb2RlQXQobGVuZ3RoIC0gNykgIT09IDExMiAvKiAncCcgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSA4KSAhPT0gOTUgIC8qICdfJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDkpICE9PSA5NSAgLyogJ18nICovKSB7XG4gICAgcmV0dXJuIGZhbHNlO1xuICB9XG5cbiAgZm9yICh2YXIgaSA9IGxlbmd0aCAtIDEwOyBpID49IDA7IGktLSkge1xuICAgIGlmIChzLmNoYXJDb2RlQXQoaSkgIT09IDM2IC8qICckJyAqLykge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB0cnVlO1xufVxuXG4vKipcbiAqIENvbXBhcmF0b3IgYmV0d2VlbiB0d28gbWFwcGluZ3Mgd2hlcmUgdGhlIG9yaWdpbmFsIHBvc2l0aW9ucyBhcmUgY29tcGFyZWQuXG4gKlxuICogT3B0aW9uYWxseSBwYXNzIGluIGB0cnVlYCBhcyBgb25seUNvbXBhcmVHZW5lcmF0ZWRgIHRvIGNvbnNpZGVyIHR3b1xuICogbWFwcGluZ3Mgd2l0aCB0aGUgc2FtZSBvcmlnaW5hbCBzb3VyY2UvbGluZS9jb2x1bW4sIGJ1dCBkaWZmZXJlbnQgZ2VuZXJhdGVkXG4gKiBsaW5lIGFuZCBjb2x1bW4gdGhlIHNhbWUuIFVzZWZ1bCB3aGVuIHNlYXJjaGluZyBmb3IgYSBtYXBwaW5nIHdpdGggYVxuICogc3R1YmJlZCBvdXQgbWFwcGluZy5cbiAqL1xuZnVuY3Rpb24gY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnMobWFwcGluZ0EsIG1hcHBpbmdCLCBvbmx5Q29tcGFyZU9yaWdpbmFsKSB7XG4gIHZhciBjbXAgPSBzdHJjbXAobWFwcGluZ0Euc291cmNlLCBtYXBwaW5nQi5zb3VyY2UpO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsTGluZSAtIG1hcHBpbmdCLm9yaWdpbmFsTGluZTtcbiAgaWYgKGNtcCAhPT0gMCkge1xuICAgIHJldHVybiBjbXA7XG4gIH1cblxuICBjbXAgPSBtYXBwaW5nQS5vcmlnaW5hbENvbHVtbiAtIG1hcHBpbmdCLm9yaWdpbmFsQ29sdW1uO1xuICBpZiAoY21wICE9PSAwIHx8IG9ubHlDb21wYXJlT3JpZ2luYWwpIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkQ29sdW1uIC0gbWFwcGluZ0IuZ2VuZXJhdGVkQ29sdW1uO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLmdlbmVyYXRlZExpbmUgLSBtYXBwaW5nQi5nZW5lcmF0ZWRMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIHJldHVybiBzdHJjbXAobWFwcGluZ0EubmFtZSwgbWFwcGluZ0IubmFtZSk7XG59XG5leHBvcnRzLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zID0gY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnM7XG5cbi8qKlxuICogQ29tcGFyYXRvciBiZXR3ZWVuIHR3byBtYXBwaW5ncyB3aXRoIGRlZmxhdGVkIHNvdXJjZSBhbmQgbmFtZSBpbmRpY2VzIHdoZXJlXG4gKiB0aGUgZ2VuZXJhdGVkIHBvc2l0aW9ucyBhcmUgY29tcGFyZWQuXG4gKlxuICogT3B0aW9uYWxseSBwYXNzIGluIGB0cnVlYCBhcyBgb25seUNvbXBhcmVHZW5lcmF0ZWRgIHRvIGNvbnNpZGVyIHR3b1xuICogbWFwcGluZ3Mgd2l0aCB0aGUgc2FtZSBnZW5lcmF0ZWQgbGluZSBhbmQgY29sdW1uLCBidXQgZGlmZmVyZW50XG4gKiBzb3VyY2UvbmFtZS9vcmlnaW5hbCBsaW5lIGFuZCBjb2x1bW4gdGhlIHNhbWUuIFVzZWZ1bCB3aGVuIHNlYXJjaGluZyBmb3IgYVxuICogbWFwcGluZyB3aXRoIGEgc3R1YmJlZCBvdXQgbWFwcGluZy5cbiAqL1xuZnVuY3Rpb24gY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zRGVmbGF0ZWQobWFwcGluZ0EsIG1hcHBpbmdCLCBvbmx5Q29tcGFyZUdlbmVyYXRlZCkge1xuICB2YXIgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkTGluZSAtIG1hcHBpbmdCLmdlbmVyYXRlZExpbmU7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkQ29sdW1uIC0gbWFwcGluZ0IuZ2VuZXJhdGVkQ29sdW1uO1xuICBpZiAoY21wICE9PSAwIHx8IG9ubHlDb21wYXJlR2VuZXJhdGVkKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IHN0cmNtcChtYXBwaW5nQS5zb3VyY2UsIG1hcHBpbmdCLnNvdXJjZSk7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0Eub3JpZ2luYWxMaW5lIC0gbWFwcGluZ0Iub3JpZ2luYWxMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsQ29sdW1uIC0gbWFwcGluZ0Iub3JpZ2luYWxDb2x1bW47XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgcmV0dXJuIHN0cmNtcChtYXBwaW5nQS5uYW1lLCBtYXBwaW5nQi5uYW1lKTtcbn1cbmV4cG9ydHMuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zRGVmbGF0ZWQgPSBjb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNEZWZsYXRlZDtcblxuZnVuY3Rpb24gc3RyY21wKGFTdHIxLCBhU3RyMikge1xuICBpZiAoYVN0cjEgPT09IGFTdHIyKSB7XG4gICAgcmV0dXJuIDA7XG4gIH1cblxuICBpZiAoYVN0cjEgPT09IG51bGwpIHtcbiAgICByZXR1cm4gMTsgLy8gYVN0cjIgIT09IG51bGxcbiAgfVxuXG4gIGlmIChhU3RyMiA9PT0gbnVsbCkge1xuICAgIHJldHVybiAtMTsgLy8gYVN0cjEgIT09IG51bGxcbiAgfVxuXG4gIGlmIChhU3RyMSA+IGFTdHIyKSB7XG4gICAgcmV0dXJuIDE7XG4gIH1cblxuICByZXR1cm4gLTE7XG59XG5cbi8qKlxuICogQ29tcGFyYXRvciBiZXR3ZWVuIHR3byBtYXBwaW5ncyB3aXRoIGluZmxhdGVkIHNvdXJjZSBhbmQgbmFtZSBzdHJpbmdzIHdoZXJlXG4gKiB0aGUgZ2VuZXJhdGVkIHBvc2l0aW9ucyBhcmUgY29tcGFyZWQuXG4gKi9cbmZ1bmN0aW9uIGNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0luZmxhdGVkKG1hcHBpbmdBLCBtYXBwaW5nQikge1xuICB2YXIgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkTGluZSAtIG1hcHBpbmdCLmdlbmVyYXRlZExpbmU7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkQ29sdW1uIC0gbWFwcGluZ0IuZ2VuZXJhdGVkQ29sdW1uO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IHN0cmNtcChtYXBwaW5nQS5zb3VyY2UsIG1hcHBpbmdCLnNvdXJjZSk7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0Eub3JpZ2luYWxMaW5lIC0gbWFwcGluZ0Iub3JpZ2luYWxMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsQ29sdW1uIC0gbWFwcGluZ0Iub3JpZ2luYWxDb2x1bW47XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgcmV0dXJuIHN0cmNtcChtYXBwaW5nQS5uYW1lLCBtYXBwaW5nQi5uYW1lKTtcbn1cbmV4cG9ydHMuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zSW5mbGF0ZWQgPSBjb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZDtcblxuLyoqXG4gKiBTdHJpcCBhbnkgSlNPTiBYU1NJIGF2b2lkYW5jZSBwcmVmaXggZnJvbSB0aGUgc3RyaW5nIChhcyBkb2N1bWVudGVkXG4gKiBpbiB0aGUgc291cmNlIG1hcHMgc3BlY2lmaWNhdGlvbiksIGFuZCB0aGVuIHBhcnNlIHRoZSBzdHJpbmcgYXNcbiAqIEpTT04uXG4gKi9cbmZ1bmN0aW9uIHBhcnNlU291cmNlTWFwSW5wdXQoc3RyKSB7XG4gIHJldHVybiBKU09OLnBhcnNlKHN0ci5yZXBsYWNlKC9eXFwpXX0nW15cXG5dKlxcbi8sICcnKSk7XG59XG5leHBvcnRzLnBhcnNlU291cmNlTWFwSW5wdXQgPSBwYXJzZVNvdXJjZU1hcElucHV0O1xuXG4vKipcbiAqIENvbXB1dGUgdGhlIFVSTCBvZiBhIHNvdXJjZSBnaXZlbiB0aGUgdGhlIHNvdXJjZSByb290LCB0aGUgc291cmNlJ3NcbiAqIFVSTCwgYW5kIHRoZSBzb3VyY2UgbWFwJ3MgVVJMLlxuICovXG5mdW5jdGlvbiBjb21wdXRlU291cmNlVVJMKHNvdXJjZVJvb3QsIHNvdXJjZVVSTCwgc291cmNlTWFwVVJMKSB7XG4gIHNvdXJjZVVSTCA9IHNvdXJjZVVSTCB8fCAnJztcblxuICBpZiAoc291cmNlUm9vdCkge1xuICAgIC8vIFRoaXMgZm9sbG93cyB3aGF0IENocm9tZSBkb2VzLlxuICAgIGlmIChzb3VyY2VSb290W3NvdXJjZVJvb3QubGVuZ3RoIC0gMV0gIT09ICcvJyAmJiBzb3VyY2VVUkxbMF0gIT09ICcvJykge1xuICAgICAgc291cmNlUm9vdCArPSAnLyc7XG4gICAgfVxuICAgIC8vIFRoZSBzcGVjIHNheXM6XG4gICAgLy8gICBMaW5lIDQ6IEFuIG9wdGlvbmFsIHNvdXJjZSByb290LCB1c2VmdWwgZm9yIHJlbG9jYXRpbmcgc291cmNlXG4gICAgLy8gICBmaWxlcyBvbiBhIHNlcnZlciBvciByZW1vdmluZyByZXBlYXRlZCB2YWx1ZXMgaW4gdGhlXG4gICAgLy8gICDigJxzb3VyY2Vz4oCdIGVudHJ5LiAgVGhpcyB2YWx1ZSBpcyBwcmVwZW5kZWQgdG8gdGhlIGluZGl2aWR1YWxcbiAgICAvLyAgIGVudHJpZXMgaW4gdGhlIOKAnHNvdXJjZeKAnSBmaWVsZC5cbiAgICBzb3VyY2VVUkwgPSBzb3VyY2VSb290ICsgc291cmNlVVJMO1xuICB9XG5cbiAgLy8gSGlzdG9yaWNhbGx5LCBTb3VyY2VNYXBDb25zdW1lciBkaWQgbm90IHRha2UgdGhlIHNvdXJjZU1hcFVSTCBhc1xuICAvLyBhIHBhcmFtZXRlci4gIFRoaXMgbW9kZSBpcyBzdGlsbCBzb21ld2hhdCBzdXBwb3J0ZWQsIHdoaWNoIGlzIHdoeVxuICAvLyB0aGlzIGNvZGUgYmxvY2sgaXMgY29uZGl0aW9uYWwuICBIb3dldmVyLCBpdCdzIHByZWZlcmFibGUgdG8gcGFzc1xuICAvLyB0aGUgc291cmNlIG1hcCBVUkwgdG8gU291cmNlTWFwQ29uc3VtZXIsIHNvIHRoYXQgdGhpcyBmdW5jdGlvblxuICAvLyBjYW4gaW1wbGVtZW50IHRoZSBzb3VyY2UgVVJMIHJlc29sdXRpb24gYWxnb3JpdGhtIGFzIG91dGxpbmVkIGluXG4gIC8vIHRoZSBzcGVjLiAgVGhpcyBibG9jayBpcyBiYXNpY2FsbHkgdGhlIGVxdWl2YWxlbnQgb2Y6XG4gIC8vICAgIG5ldyBVUkwoc291cmNlVVJMLCBzb3VyY2VNYXBVUkwpLnRvU3RyaW5nKClcbiAgLy8gLi4uIGV4Y2VwdCBpdCBhdm9pZHMgdXNpbmcgVVJMLCB3aGljaCB3YXNuJ3QgYXZhaWxhYmxlIGluIHRoZVxuICAvLyBvbGRlciByZWxlYXNlcyBvZiBub2RlIHN0aWxsIHN1cHBvcnRlZCBieSB0aGlzIGxpYnJhcnkuXG4gIC8vXG4gIC8vIFRoZSBzcGVjIHNheXM6XG4gIC8vICAgSWYgdGhlIHNvdXJjZXMgYXJlIG5vdCBhYnNvbHV0ZSBVUkxzIGFmdGVyIHByZXBlbmRpbmcgb2YgdGhlXG4gIC8vICAg4oCcc291cmNlUm9vdOKAnSwgdGhlIHNvdXJjZXMgYXJlIHJlc29sdmVkIHJlbGF0aXZlIHRvIHRoZVxuICAvLyAgIFNvdXJjZU1hcCAobGlrZSByZXNvbHZpbmcgc2NyaXB0IHNyYyBpbiBhIGh0bWwgZG9jdW1lbnQpLlxuICBpZiAoc291cmNlTWFwVVJMKSB7XG4gICAgdmFyIHBhcnNlZCA9IHVybFBhcnNlKHNvdXJjZU1hcFVSTCk7XG4gICAgaWYgKCFwYXJzZWQpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcihcInNvdXJjZU1hcFVSTCBjb3VsZCBub3QgYmUgcGFyc2VkXCIpO1xuICAgIH1cbiAgICBpZiAocGFyc2VkLnBhdGgpIHtcbiAgICAgIC8vIFN0cmlwIHRoZSBsYXN0IHBhdGggY29tcG9uZW50LCBidXQga2VlcCB0aGUgXCIvXCIuXG4gICAgICB2YXIgaW5kZXggPSBwYXJzZWQucGF0aC5sYXN0SW5kZXhPZignLycpO1xuICAgICAgaWYgKGluZGV4ID49IDApIHtcbiAgICAgICAgcGFyc2VkLnBhdGggPSBwYXJzZWQucGF0aC5zdWJzdHJpbmcoMCwgaW5kZXggKyAxKTtcbiAgICAgIH1cbiAgICB9XG4gICAgc291cmNlVVJMID0gam9pbih1cmxHZW5lcmF0ZShwYXJzZWQpLCBzb3VyY2VVUkwpO1xuICB9XG5cbiAgcmV0dXJuIG5vcm1hbGl6ZShzb3VyY2VVUkwpO1xufVxuZXhwb3J0cy5jb21wdXRlU291cmNlVVJMID0gY29tcHV0ZVNvdXJjZVVSTDtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL3V0aWwuanNcbi8vIG1vZHVsZSBpZCA9IDRcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgdXRpbCA9IHJlcXVpcmUoJy4vdXRpbCcpO1xudmFyIGhhcyA9IE9iamVjdC5wcm90b3R5cGUuaGFzT3duUHJvcGVydHk7XG52YXIgaGFzTmF0aXZlTWFwID0gdHlwZW9mIE1hcCAhPT0gXCJ1bmRlZmluZWRcIjtcblxuLyoqXG4gKiBBIGRhdGEgc3RydWN0dXJlIHdoaWNoIGlzIGEgY29tYmluYXRpb24gb2YgYW4gYXJyYXkgYW5kIGEgc2V0LiBBZGRpbmcgYSBuZXdcbiAqIG1lbWJlciBpcyBPKDEpLCB0ZXN0aW5nIGZvciBtZW1iZXJzaGlwIGlzIE8oMSksIGFuZCBmaW5kaW5nIHRoZSBpbmRleCBvZiBhblxuICogZWxlbWVudCBpcyBPKDEpLiBSZW1vdmluZyBlbGVtZW50cyBmcm9tIHRoZSBzZXQgaXMgbm90IHN1cHBvcnRlZC4gT25seVxuICogc3RyaW5ncyBhcmUgc3VwcG9ydGVkIGZvciBtZW1iZXJzaGlwLlxuICovXG5mdW5jdGlvbiBBcnJheVNldCgpIHtcbiAgdGhpcy5fYXJyYXkgPSBbXTtcbiAgdGhpcy5fc2V0ID0gaGFzTmF0aXZlTWFwID8gbmV3IE1hcCgpIDogT2JqZWN0LmNyZWF0ZShudWxsKTtcbn1cblxuLyoqXG4gKiBTdGF0aWMgbWV0aG9kIGZvciBjcmVhdGluZyBBcnJheVNldCBpbnN0YW5jZXMgZnJvbSBhbiBleGlzdGluZyBhcnJheS5cbiAqL1xuQXJyYXlTZXQuZnJvbUFycmF5ID0gZnVuY3Rpb24gQXJyYXlTZXRfZnJvbUFycmF5KGFBcnJheSwgYUFsbG93RHVwbGljYXRlcykge1xuICB2YXIgc2V0ID0gbmV3IEFycmF5U2V0KCk7XG4gIGZvciAodmFyIGkgPSAwLCBsZW4gPSBhQXJyYXkubGVuZ3RoOyBpIDwgbGVuOyBpKyspIHtcbiAgICBzZXQuYWRkKGFBcnJheVtpXSwgYUFsbG93RHVwbGljYXRlcyk7XG4gIH1cbiAgcmV0dXJuIHNldDtcbn07XG5cbi8qKlxuICogUmV0dXJuIGhvdyBtYW55IHVuaXF1ZSBpdGVtcyBhcmUgaW4gdGhpcyBBcnJheVNldC4gSWYgZHVwbGljYXRlcyBoYXZlIGJlZW5cbiAqIGFkZGVkLCB0aGFuIHRob3NlIGRvIG5vdCBjb3VudCB0b3dhcmRzIHRoZSBzaXplLlxuICpcbiAqIEByZXR1cm5zIE51bWJlclxuICovXG5BcnJheVNldC5wcm90b3R5cGUuc2l6ZSA9IGZ1bmN0aW9uIEFycmF5U2V0X3NpemUoKSB7XG4gIHJldHVybiBoYXNOYXRpdmVNYXAgPyB0aGlzLl9zZXQuc2l6ZSA6IE9iamVjdC5nZXRPd25Qcm9wZXJ0eU5hbWVzKHRoaXMuX3NldCkubGVuZ3RoO1xufTtcblxuLyoqXG4gKiBBZGQgdGhlIGdpdmVuIHN0cmluZyB0byB0aGlzIHNldC5cbiAqXG4gKiBAcGFyYW0gU3RyaW5nIGFTdHJcbiAqL1xuQXJyYXlTZXQucHJvdG90eXBlLmFkZCA9IGZ1bmN0aW9uIEFycmF5U2V0X2FkZChhU3RyLCBhQWxsb3dEdXBsaWNhdGVzKSB7XG4gIHZhciBzU3RyID0gaGFzTmF0aXZlTWFwID8gYVN0ciA6IHV0aWwudG9TZXRTdHJpbmcoYVN0cik7XG4gIHZhciBpc0R1cGxpY2F0ZSA9IGhhc05hdGl2ZU1hcCA/IHRoaXMuaGFzKGFTdHIpIDogaGFzLmNhbGwodGhpcy5fc2V0LCBzU3RyKTtcbiAgdmFyIGlkeCA9IHRoaXMuX2FycmF5Lmxlbmd0aDtcbiAgaWYgKCFpc0R1cGxpY2F0ZSB8fCBhQWxsb3dEdXBsaWNhdGVzKSB7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhU3RyKTtcbiAgfVxuICBpZiAoIWlzRHVwbGljYXRlKSB7XG4gICAgaWYgKGhhc05hdGl2ZU1hcCkge1xuICAgICAgdGhpcy5fc2V0LnNldChhU3RyLCBpZHgpO1xuICAgIH0gZWxzZSB7XG4gICAgICB0aGlzLl9zZXRbc1N0cl0gPSBpZHg7XG4gICAgfVxuICB9XG59O1xuXG4vKipcbiAqIElzIHRoZSBnaXZlbiBzdHJpbmcgYSBtZW1iZXIgb2YgdGhpcyBzZXQ/XG4gKlxuICogQHBhcmFtIFN0cmluZyBhU3RyXG4gKi9cbkFycmF5U2V0LnByb3RvdHlwZS5oYXMgPSBmdW5jdGlvbiBBcnJheVNldF9oYXMoYVN0cikge1xuICBpZiAoaGFzTmF0aXZlTWFwKSB7XG4gICAgcmV0dXJuIHRoaXMuX3NldC5oYXMoYVN0cik7XG4gIH0gZWxzZSB7XG4gICAgdmFyIHNTdHIgPSB1dGlsLnRvU2V0U3RyaW5nKGFTdHIpO1xuICAgIHJldHVybiBoYXMuY2FsbCh0aGlzLl9zZXQsIHNTdHIpO1xuICB9XG59O1xuXG4vKipcbiAqIFdoYXQgaXMgdGhlIGluZGV4IG9mIHRoZSBnaXZlbiBzdHJpbmcgaW4gdGhlIGFycmF5P1xuICpcbiAqIEBwYXJhbSBTdHJpbmcgYVN0clxuICovXG5BcnJheVNldC5wcm90b3R5cGUuaW5kZXhPZiA9IGZ1bmN0aW9uIEFycmF5U2V0X2luZGV4T2YoYVN0cikge1xuICBpZiAoaGFzTmF0aXZlTWFwKSB7XG4gICAgdmFyIGlkeCA9IHRoaXMuX3NldC5nZXQoYVN0cik7XG4gICAgaWYgKGlkeCA+PSAwKSB7XG4gICAgICAgIHJldHVybiBpZHg7XG4gICAgfVxuICB9IGVsc2Uge1xuICAgIHZhciBzU3RyID0gdXRpbC50b1NldFN0cmluZyhhU3RyKTtcbiAgICBpZiAoaGFzLmNhbGwodGhpcy5fc2V0LCBzU3RyKSkge1xuICAgICAgcmV0dXJuIHRoaXMuX3NldFtzU3RyXTtcbiAgICB9XG4gIH1cblxuICB0aHJvdyBuZXcgRXJyb3IoJ1wiJyArIGFTdHIgKyAnXCIgaXMgbm90IGluIHRoZSBzZXQuJyk7XG59O1xuXG4vKipcbiAqIFdoYXQgaXMgdGhlIGVsZW1lbnQgYXQgdGhlIGdpdmVuIGluZGV4P1xuICpcbiAqIEBwYXJhbSBOdW1iZXIgYUlkeFxuICovXG5BcnJheVNldC5wcm90b3R5cGUuYXQgPSBmdW5jdGlvbiBBcnJheVNldF9hdChhSWR4KSB7XG4gIGlmIChhSWR4ID49IDAgJiYgYUlkeCA8IHRoaXMuX2FycmF5Lmxlbmd0aCkge1xuICAgIHJldHVybiB0aGlzLl9hcnJheVthSWR4XTtcbiAgfVxuICB0aHJvdyBuZXcgRXJyb3IoJ05vIGVsZW1lbnQgaW5kZXhlZCBieSAnICsgYUlkeCk7XG59O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIGFycmF5IHJlcHJlc2VudGF0aW9uIG9mIHRoaXMgc2V0ICh3aGljaCBoYXMgdGhlIHByb3BlciBpbmRpY2VzXG4gKiBpbmRpY2F0ZWQgYnkgaW5kZXhPZikuIE5vdGUgdGhhdCB0aGlzIGlzIGEgY29weSBvZiB0aGUgaW50ZXJuYWwgYXJyYXkgdXNlZFxuICogZm9yIHN0b3JpbmcgdGhlIG1lbWJlcnMgc28gdGhhdCBubyBvbmUgY2FuIG1lc3Mgd2l0aCBpbnRlcm5hbCBzdGF0ZS5cbiAqL1xuQXJyYXlTZXQucHJvdG90eXBlLnRvQXJyYXkgPSBmdW5jdGlvbiBBcnJheVNldF90b0FycmF5KCkge1xuICByZXR1cm4gdGhpcy5fYXJyYXkuc2xpY2UoKTtcbn07XG5cbmV4cG9ydHMuQXJyYXlTZXQgPSBBcnJheVNldDtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL2FycmF5LXNldC5qc1xuLy8gbW9kdWxlIGlkID0gNVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTQgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbnZhciB1dGlsID0gcmVxdWlyZSgnLi91dGlsJyk7XG5cbi8qKlxuICogRGV0ZXJtaW5lIHdoZXRoZXIgbWFwcGluZ0IgaXMgYWZ0ZXIgbWFwcGluZ0Egd2l0aCByZXNwZWN0IHRvIGdlbmVyYXRlZFxuICogcG9zaXRpb24uXG4gKi9cbmZ1bmN0aW9uIGdlbmVyYXRlZFBvc2l0aW9uQWZ0ZXIobWFwcGluZ0EsIG1hcHBpbmdCKSB7XG4gIC8vIE9wdGltaXplZCBmb3IgbW9zdCBjb21tb24gY2FzZVxuICB2YXIgbGluZUEgPSBtYXBwaW5nQS5nZW5lcmF0ZWRMaW5lO1xuICB2YXIgbGluZUIgPSBtYXBwaW5nQi5nZW5lcmF0ZWRMaW5lO1xuICB2YXIgY29sdW1uQSA9IG1hcHBpbmdBLmdlbmVyYXRlZENvbHVtbjtcbiAgdmFyIGNvbHVtbkIgPSBtYXBwaW5nQi5nZW5lcmF0ZWRDb2x1bW47XG4gIHJldHVybiBsaW5lQiA+IGxpbmVBIHx8IGxpbmVCID09IGxpbmVBICYmIGNvbHVtbkIgPj0gY29sdW1uQSB8fFxuICAgICAgICAgdXRpbC5jb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZChtYXBwaW5nQSwgbWFwcGluZ0IpIDw9IDA7XG59XG5cbi8qKlxuICogQSBkYXRhIHN0cnVjdHVyZSB0byBwcm92aWRlIGEgc29ydGVkIHZpZXcgb2YgYWNjdW11bGF0ZWQgbWFwcGluZ3MgaW4gYVxuICogcGVyZm9ybWFuY2UgY29uc2Npb3VzIG1hbm5lci4gSXQgdHJhZGVzIGEgbmVnbGliYWJsZSBvdmVyaGVhZCBpbiBnZW5lcmFsXG4gKiBjYXNlIGZvciBhIGxhcmdlIHNwZWVkdXAgaW4gY2FzZSBvZiBtYXBwaW5ncyBiZWluZyBhZGRlZCBpbiBvcmRlci5cbiAqL1xuZnVuY3Rpb24gTWFwcGluZ0xpc3QoKSB7XG4gIHRoaXMuX2FycmF5ID0gW107XG4gIHRoaXMuX3NvcnRlZCA9IHRydWU7XG4gIC8vIFNlcnZlcyBhcyBpbmZpbXVtXG4gIHRoaXMuX2xhc3QgPSB7Z2VuZXJhdGVkTGluZTogLTEsIGdlbmVyYXRlZENvbHVtbjogMH07XG59XG5cbi8qKlxuICogSXRlcmF0ZSB0aHJvdWdoIGludGVybmFsIGl0ZW1zLiBUaGlzIG1ldGhvZCB0YWtlcyB0aGUgc2FtZSBhcmd1bWVudHMgdGhhdFxuICogYEFycmF5LnByb3RvdHlwZS5mb3JFYWNoYCB0YWtlcy5cbiAqXG4gKiBOT1RFOiBUaGUgb3JkZXIgb2YgdGhlIG1hcHBpbmdzIGlzIE5PVCBndWFyYW50ZWVkLlxuICovXG5NYXBwaW5nTGlzdC5wcm90b3R5cGUudW5zb3J0ZWRGb3JFYWNoID1cbiAgZnVuY3Rpb24gTWFwcGluZ0xpc3RfZm9yRWFjaChhQ2FsbGJhY2ssIGFUaGlzQXJnKSB7XG4gICAgdGhpcy5fYXJyYXkuZm9yRWFjaChhQ2FsbGJhY2ssIGFUaGlzQXJnKTtcbiAgfTtcblxuLyoqXG4gKiBBZGQgdGhlIGdpdmVuIHNvdXJjZSBtYXBwaW5nLlxuICpcbiAqIEBwYXJhbSBPYmplY3QgYU1hcHBpbmdcbiAqL1xuTWFwcGluZ0xpc3QucHJvdG90eXBlLmFkZCA9IGZ1bmN0aW9uIE1hcHBpbmdMaXN0X2FkZChhTWFwcGluZykge1xuICBpZiAoZ2VuZXJhdGVkUG9zaXRpb25BZnRlcih0aGlzLl9sYXN0LCBhTWFwcGluZykpIHtcbiAgICB0aGlzLl9sYXN0ID0gYU1hcHBpbmc7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhTWFwcGluZyk7XG4gIH0gZWxzZSB7XG4gICAgdGhpcy5fc29ydGVkID0gZmFsc2U7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhTWFwcGluZyk7XG4gIH1cbn07XG5cbi8qKlxuICogUmV0dXJucyB0aGUgZmxhdCwgc29ydGVkIGFycmF5IG9mIG1hcHBpbmdzLiBUaGUgbWFwcGluZ3MgYXJlIHNvcnRlZCBieVxuICogZ2VuZXJhdGVkIHBvc2l0aW9uLlxuICpcbiAqIFdBUk5JTkc6IFRoaXMgbWV0aG9kIHJldHVybnMgaW50ZXJuYWwgZGF0YSB3aXRob3V0IGNvcHlpbmcsIGZvclxuICogcGVyZm9ybWFuY2UuIFRoZSByZXR1cm4gdmFsdWUgbXVzdCBOT1QgYmUgbXV0YXRlZCwgYW5kIHNob3VsZCBiZSB0cmVhdGVkIGFzXG4gKiBhbiBpbW11dGFibGUgYm9ycm93LiBJZiB5b3Ugd2FudCB0byB0YWtlIG93bmVyc2hpcCwgeW91IG11c3QgbWFrZSB5b3VyIG93blxuICogY29weS5cbiAqL1xuTWFwcGluZ0xpc3QucHJvdG90eXBlLnRvQXJyYXkgPSBmdW5jdGlvbiBNYXBwaW5nTGlzdF90b0FycmF5KCkge1xuICBpZiAoIXRoaXMuX3NvcnRlZCkge1xuICAgIHRoaXMuX2FycmF5LnNvcnQodXRpbC5jb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZCk7XG4gICAgdGhpcy5fc29ydGVkID0gdHJ1ZTtcbiAgfVxuICByZXR1cm4gdGhpcy5fYXJyYXk7XG59O1xuXG5leHBvcnRzLk1hcHBpbmdMaXN0ID0gTWFwcGluZ0xpc3Q7XG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2xpYi9tYXBwaW5nLWxpc3QuanNcbi8vIG1vZHVsZSBpZCA9IDZcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgdXRpbCA9IHJlcXVpcmUoJy4vdXRpbCcpO1xudmFyIGJpbmFyeVNlYXJjaCA9IHJlcXVpcmUoJy4vYmluYXJ5LXNlYXJjaCcpO1xudmFyIEFycmF5U2V0ID0gcmVxdWlyZSgnLi9hcnJheS1zZXQnKS5BcnJheVNldDtcbnZhciBiYXNlNjRWTFEgPSByZXF1aXJlKCcuL2Jhc2U2NC12bHEnKTtcbnZhciBxdWlja1NvcnQgPSByZXF1aXJlKCcuL3F1aWNrLXNvcnQnKS5xdWlja1NvcnQ7XG5cbmZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgdmFyIHNvdXJjZU1hcCA9IGFTb3VyY2VNYXA7XG4gIGlmICh0eXBlb2YgYVNvdXJjZU1hcCA9PT0gJ3N0cmluZycpIHtcbiAgICBzb3VyY2VNYXAgPSB1dGlsLnBhcnNlU291cmNlTWFwSW5wdXQoYVNvdXJjZU1hcCk7XG4gIH1cblxuICByZXR1cm4gc291cmNlTWFwLnNlY3Rpb25zICE9IG51bGxcbiAgICA/IG5ldyBJbmRleGVkU291cmNlTWFwQ29uc3VtZXIoc291cmNlTWFwLCBhU291cmNlTWFwVVJMKVxuICAgIDogbmV3IEJhc2ljU291cmNlTWFwQ29uc3VtZXIoc291cmNlTWFwLCBhU291cmNlTWFwVVJMKTtcbn1cblxuU291cmNlTWFwQ29uc3VtZXIuZnJvbVNvdXJjZU1hcCA9IGZ1bmN0aW9uKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgcmV0dXJuIEJhc2ljU291cmNlTWFwQ29uc3VtZXIuZnJvbVNvdXJjZU1hcChhU291cmNlTWFwLCBhU291cmNlTWFwVVJMKTtcbn1cblxuLyoqXG4gKiBUaGUgdmVyc2lvbiBvZiB0aGUgc291cmNlIG1hcHBpbmcgc3BlYyB0aGF0IHdlIGFyZSBjb25zdW1pbmcuXG4gKi9cblNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8vIGBfX2dlbmVyYXRlZE1hcHBpbmdzYCBhbmQgYF9fb3JpZ2luYWxNYXBwaW5nc2AgYXJlIGFycmF5cyB0aGF0IGhvbGQgdGhlXG4vLyBwYXJzZWQgbWFwcGluZyBjb29yZGluYXRlcyBmcm9tIHRoZSBzb3VyY2UgbWFwJ3MgXCJtYXBwaW5nc1wiIGF0dHJpYnV0ZS4gVGhleVxuLy8gYXJlIGxhemlseSBpbnN0YW50aWF0ZWQsIGFjY2Vzc2VkIHZpYSB0aGUgYF9nZW5lcmF0ZWRNYXBwaW5nc2AgYW5kXG4vLyBgX29yaWdpbmFsTWFwcGluZ3NgIGdldHRlcnMgcmVzcGVjdGl2ZWx5LCBhbmQgd2Ugb25seSBwYXJzZSB0aGUgbWFwcGluZ3Ncbi8vIGFuZCBjcmVhdGUgdGhlc2UgYXJyYXlzIG9uY2UgcXVlcmllZCBmb3IgYSBzb3VyY2UgbG9jYXRpb24uIFdlIGp1bXAgdGhyb3VnaFxuLy8gdGhlc2UgaG9vcHMgYmVjYXVzZSB0aGVyZSBjYW4gYmUgbWFueSB0aG91c2FuZHMgb2YgbWFwcGluZ3MsIGFuZCBwYXJzaW5nXG4vLyB0aGVtIGlzIGV4cGVuc2l2ZSwgc28gd2Ugb25seSB3YW50IHRvIGRvIGl0IGlmIHdlIG11c3QuXG4vL1xuLy8gRWFjaCBvYmplY3QgaW4gdGhlIGFycmF5cyBpcyBvZiB0aGUgZm9ybTpcbi8vXG4vLyAgICAge1xuLy8gICAgICAgZ2VuZXJhdGVkTGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgY29kZSxcbi8vICAgICAgIGdlbmVyYXRlZENvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIGdlbmVyYXRlZCBjb2RlLFxuLy8gICAgICAgc291cmNlOiBUaGUgcGF0aCB0byB0aGUgb3JpZ2luYWwgc291cmNlIGZpbGUgdGhhdCBnZW5lcmF0ZWQgdGhpc1xuLy8gICAgICAgICAgICAgICBjaHVuayBvZiBjb2RlLFxuLy8gICAgICAgb3JpZ2luYWxMaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZSB0aGF0XG4vLyAgICAgICAgICAgICAgICAgICAgIGNvcnJlc3BvbmRzIHRvIHRoaXMgY2h1bmsgb2YgZ2VuZXJhdGVkIGNvZGUsXG4vLyAgICAgICBvcmlnaW5hbENvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZSB0aGF0XG4vLyAgICAgICAgICAgICAgICAgICAgICAgY29ycmVzcG9uZHMgdG8gdGhpcyBjaHVuayBvZiBnZW5lcmF0ZWQgY29kZSxcbi8vICAgICAgIG5hbWU6IFRoZSBuYW1lIG9mIHRoZSBvcmlnaW5hbCBzeW1ib2wgd2hpY2ggZ2VuZXJhdGVkIHRoaXMgY2h1bmsgb2Zcbi8vICAgICAgICAgICAgIGNvZGUuXG4vLyAgICAgfVxuLy9cbi8vIEFsbCBwcm9wZXJ0aWVzIGV4Y2VwdCBmb3IgYGdlbmVyYXRlZExpbmVgIGFuZCBgZ2VuZXJhdGVkQ29sdW1uYCBjYW4gYmVcbi8vIGBudWxsYC5cbi8vXG4vLyBgX2dlbmVyYXRlZE1hcHBpbmdzYCBpcyBvcmRlcmVkIGJ5IHRoZSBnZW5lcmF0ZWQgcG9zaXRpb25zLlxuLy9cbi8vIGBfb3JpZ2luYWxNYXBwaW5nc2AgaXMgb3JkZXJlZCBieSB0aGUgb3JpZ2luYWwgcG9zaXRpb25zLlxuXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX19nZW5lcmF0ZWRNYXBwaW5ncyA9IG51bGw7XG5PYmplY3QuZGVmaW5lUHJvcGVydHkoU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLCAnX2dlbmVyYXRlZE1hcHBpbmdzJywge1xuICBjb25maWd1cmFibGU6IHRydWUsXG4gIGVudW1lcmFibGU6IHRydWUsXG4gIGdldDogZnVuY3Rpb24gKCkge1xuICAgIGlmICghdGhpcy5fX2dlbmVyYXRlZE1hcHBpbmdzKSB7XG4gICAgICB0aGlzLl9wYXJzZU1hcHBpbmdzKHRoaXMuX21hcHBpbmdzLCB0aGlzLnNvdXJjZVJvb3QpO1xuICAgIH1cblxuICAgIHJldHVybiB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3M7XG4gIH1cbn0pO1xuXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX19vcmlnaW5hbE1hcHBpbmdzID0gbnVsbDtcbk9iamVjdC5kZWZpbmVQcm9wZXJ0eShTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUsICdfb3JpZ2luYWxNYXBwaW5ncycsIHtcbiAgY29uZmlndXJhYmxlOiB0cnVlLFxuICBlbnVtZXJhYmxlOiB0cnVlLFxuICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICBpZiAoIXRoaXMuX19vcmlnaW5hbE1hcHBpbmdzKSB7XG4gICAgICB0aGlzLl9wYXJzZU1hcHBpbmdzKHRoaXMuX21hcHBpbmdzLCB0aGlzLnNvdXJjZVJvb3QpO1xuICAgIH1cblxuICAgIHJldHVybiB0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncztcbiAgfVxufSk7XG5cblNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fY2hhcklzTWFwcGluZ1NlcGFyYXRvciA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2NoYXJJc01hcHBpbmdTZXBhcmF0b3IoYVN0ciwgaW5kZXgpIHtcbiAgICB2YXIgYyA9IGFTdHIuY2hhckF0KGluZGV4KTtcbiAgICByZXR1cm4gYyA9PT0gXCI7XCIgfHwgYyA9PT0gXCIsXCI7XG4gIH07XG5cbi8qKlxuICogUGFyc2UgdGhlIG1hcHBpbmdzIGluIGEgc3RyaW5nIGluIHRvIGEgZGF0YSBzdHJ1Y3R1cmUgd2hpY2ggd2UgY2FuIGVhc2lseVxuICogcXVlcnkgKHRoZSBvcmRlcmVkIGFycmF5cyBpbiB0aGUgYHRoaXMuX19nZW5lcmF0ZWRNYXBwaW5nc2AgYW5kXG4gKiBgdGhpcy5fX29yaWdpbmFsTWFwcGluZ3NgIHByb3BlcnRpZXMpLlxuICovXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX3BhcnNlTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9wYXJzZU1hcHBpbmdzKGFTdHIsIGFTb3VyY2VSb290KSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKFwiU3ViY2xhc3NlcyBtdXN0IGltcGxlbWVudCBfcGFyc2VNYXBwaW5nc1wiKTtcbiAgfTtcblxuU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSID0gMTtcblNvdXJjZU1hcENvbnN1bWVyLk9SSUdJTkFMX09SREVSID0gMjtcblxuU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQgPSAxO1xuU291cmNlTWFwQ29uc3VtZXIuTEVBU1RfVVBQRVJfQk9VTkQgPSAyO1xuXG4vKipcbiAqIEl0ZXJhdGUgb3ZlciBlYWNoIG1hcHBpbmcgYmV0d2VlbiBhbiBvcmlnaW5hbCBzb3VyY2UvbGluZS9jb2x1bW4gYW5kIGFcbiAqIGdlbmVyYXRlZCBsaW5lL2NvbHVtbiBpbiB0aGlzIHNvdXJjZSBtYXAuXG4gKlxuICogQHBhcmFtIEZ1bmN0aW9uIGFDYWxsYmFja1xuICogICAgICAgIFRoZSBmdW5jdGlvbiB0aGF0IGlzIGNhbGxlZCB3aXRoIGVhY2ggbWFwcGluZy5cbiAqIEBwYXJhbSBPYmplY3QgYUNvbnRleHRcbiAqICAgICAgICBPcHRpb25hbC4gSWYgc3BlY2lmaWVkLCB0aGlzIG9iamVjdCB3aWxsIGJlIHRoZSB2YWx1ZSBvZiBgdGhpc2AgZXZlcnlcbiAqICAgICAgICB0aW1lIHRoYXQgYGFDYWxsYmFja2AgaXMgY2FsbGVkLlxuICogQHBhcmFtIGFPcmRlclxuICogICAgICAgIEVpdGhlciBgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSYCBvclxuICogICAgICAgIGBTb3VyY2VNYXBDb25zdW1lci5PUklHSU5BTF9PUkRFUmAuIFNwZWNpZmllcyB3aGV0aGVyIHlvdSB3YW50IHRvXG4gKiAgICAgICAgaXRlcmF0ZSBvdmVyIHRoZSBtYXBwaW5ncyBzb3J0ZWQgYnkgdGhlIGdlbmVyYXRlZCBmaWxlJ3MgbGluZS9jb2x1bW5cbiAqICAgICAgICBvcmRlciBvciB0aGUgb3JpZ2luYWwncyBzb3VyY2UvbGluZS9jb2x1bW4gb3JkZXIsIHJlc3BlY3RpdmVseS4gRGVmYXVsdHMgdG9cbiAqICAgICAgICBgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSYC5cbiAqL1xuU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmVhY2hNYXBwaW5nID1cbiAgZnVuY3Rpb24gU291cmNlTWFwQ29uc3VtZXJfZWFjaE1hcHBpbmcoYUNhbGxiYWNrLCBhQ29udGV4dCwgYU9yZGVyKSB7XG4gICAgdmFyIGNvbnRleHQgPSBhQ29udGV4dCB8fCBudWxsO1xuICAgIHZhciBvcmRlciA9IGFPcmRlciB8fCBTb3VyY2VNYXBDb25zdW1lci5HRU5FUkFURURfT1JERVI7XG5cbiAgICB2YXIgbWFwcGluZ3M7XG4gICAgc3dpdGNoIChvcmRlcikge1xuICAgIGNhc2UgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSOlxuICAgICAgbWFwcGluZ3MgPSB0aGlzLl9nZW5lcmF0ZWRNYXBwaW5ncztcbiAgICAgIGJyZWFrO1xuICAgIGNhc2UgU291cmNlTWFwQ29uc3VtZXIuT1JJR0lOQUxfT1JERVI6XG4gICAgICBtYXBwaW5ncyA9IHRoaXMuX29yaWdpbmFsTWFwcGluZ3M7XG4gICAgICBicmVhaztcbiAgICBkZWZhdWx0OlxuICAgICAgdGhyb3cgbmV3IEVycm9yKFwiVW5rbm93biBvcmRlciBvZiBpdGVyYXRpb24uXCIpO1xuICAgIH1cblxuICAgIHZhciBzb3VyY2VSb290ID0gdGhpcy5zb3VyY2VSb290O1xuICAgIG1hcHBpbmdzLm1hcChmdW5jdGlvbiAobWFwcGluZykge1xuICAgICAgdmFyIHNvdXJjZSA9IG1hcHBpbmcuc291cmNlID09PSBudWxsID8gbnVsbCA6IHRoaXMuX3NvdXJjZXMuYXQobWFwcGluZy5zb3VyY2UpO1xuICAgICAgc291cmNlID0gdXRpbC5jb21wdXRlU291cmNlVVJMKHNvdXJjZVJvb3QsIHNvdXJjZSwgdGhpcy5fc291cmNlTWFwVVJMKTtcbiAgICAgIHJldHVybiB7XG4gICAgICAgIHNvdXJjZTogc291cmNlLFxuICAgICAgICBnZW5lcmF0ZWRMaW5lOiBtYXBwaW5nLmdlbmVyYXRlZExpbmUsXG4gICAgICAgIGdlbmVyYXRlZENvbHVtbjogbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4sXG4gICAgICAgIG9yaWdpbmFsTGluZTogbWFwcGluZy5vcmlnaW5hbExpbmUsXG4gICAgICAgIG9yaWdpbmFsQ29sdW1uOiBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uLFxuICAgICAgICBuYW1lOiBtYXBwaW5nLm5hbWUgPT09IG51bGwgPyBudWxsIDogdGhpcy5fbmFtZXMuYXQobWFwcGluZy5uYW1lKVxuICAgICAgfTtcbiAgICB9LCB0aGlzKS5mb3JFYWNoKGFDYWxsYmFjaywgY29udGV4dCk7XG4gIH07XG5cbi8qKlxuICogUmV0dXJucyBhbGwgZ2VuZXJhdGVkIGxpbmUgYW5kIGNvbHVtbiBpbmZvcm1hdGlvbiBmb3IgdGhlIG9yaWdpbmFsIHNvdXJjZSxcbiAqIGxpbmUsIGFuZCBjb2x1bW4gcHJvdmlkZWQuIElmIG5vIGNvbHVtbiBpcyBwcm92aWRlZCwgcmV0dXJucyBhbGwgbWFwcGluZ3NcbiAqIGNvcnJlc3BvbmRpbmcgdG8gYSBlaXRoZXIgdGhlIGxpbmUgd2UgYXJlIHNlYXJjaGluZyBmb3Igb3IgdGhlIG5leHRcbiAqIGNsb3Nlc3QgbGluZSB0aGF0IGhhcyBhbnkgbWFwcGluZ3MuIE90aGVyd2lzZSwgcmV0dXJucyBhbGwgbWFwcGluZ3NcbiAqIGNvcnJlc3BvbmRpbmcgdG8gdGhlIGdpdmVuIGxpbmUgYW5kIGVpdGhlciB0aGUgY29sdW1uIHdlIGFyZSBzZWFyY2hpbmcgZm9yXG4gKiBvciB0aGUgbmV4dCBjbG9zZXN0IGNvbHVtbiB0aGF0IGhhcyBhbnkgb2Zmc2V0cy5cbiAqXG4gKiBUaGUgb25seSBhcmd1bWVudCBpcyBhbiBvYmplY3Qgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIHNvdXJjZTogVGhlIGZpbGVuYW1lIG9mIHRoZSBvcmlnaW5hbCBzb3VyY2UuXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UuICBUaGUgbGluZSBudW1iZXIgaXMgMS1iYXNlZC5cbiAqICAgLSBjb2x1bW46IE9wdGlvbmFsLiB0aGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLlxuICogICAgVGhlIGNvbHVtbiBudW1iZXIgaXMgMC1iYXNlZC5cbiAqXG4gKiBhbmQgYW4gYXJyYXkgb2Ygb2JqZWN0cyBpcyByZXR1cm5lZCwgZWFjaCB3aXRoIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLCBvciBudWxsLiAgVGhlXG4gKiAgICBsaW5lIG51bWJlciBpcyAxLWJhc2VkLlxuICogICAtIGNvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIGdlbmVyYXRlZCBzb3VyY2UsIG9yIG51bGwuXG4gKiAgICBUaGUgY29sdW1uIG51bWJlciBpcyAwLWJhc2VkLlxuICovXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuYWxsR2VuZXJhdGVkUG9zaXRpb25zRm9yID1cbiAgZnVuY3Rpb24gU291cmNlTWFwQ29uc3VtZXJfYWxsR2VuZXJhdGVkUG9zaXRpb25zRm9yKGFBcmdzKSB7XG4gICAgdmFyIGxpbmUgPSB1dGlsLmdldEFyZyhhQXJncywgJ2xpbmUnKTtcblxuICAgIC8vIFdoZW4gdGhlcmUgaXMgbm8gZXhhY3QgbWF0Y2gsIEJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLl9maW5kTWFwcGluZ1xuICAgIC8vIHJldHVybnMgdGhlIGluZGV4IG9mIHRoZSBjbG9zZXN0IG1hcHBpbmcgbGVzcyB0aGFuIHRoZSBuZWVkbGUuIEJ5XG4gICAgLy8gc2V0dGluZyBuZWVkbGUub3JpZ2luYWxDb2x1bW4gdG8gMCwgd2UgdGh1cyBmaW5kIHRoZSBsYXN0IG1hcHBpbmcgZm9yXG4gICAgLy8gdGhlIGdpdmVuIGxpbmUsIHByb3ZpZGVkIHN1Y2ggYSBtYXBwaW5nIGV4aXN0cy5cbiAgICB2YXIgbmVlZGxlID0ge1xuICAgICAgc291cmNlOiB1dGlsLmdldEFyZyhhQXJncywgJ3NvdXJjZScpLFxuICAgICAgb3JpZ2luYWxMaW5lOiBsaW5lLFxuICAgICAgb3JpZ2luYWxDb2x1bW46IHV0aWwuZ2V0QXJnKGFBcmdzLCAnY29sdW1uJywgMClcbiAgICB9O1xuXG4gICAgbmVlZGxlLnNvdXJjZSA9IHRoaXMuX2ZpbmRTb3VyY2VJbmRleChuZWVkbGUuc291cmNlKTtcbiAgICBpZiAobmVlZGxlLnNvdXJjZSA8IDApIHtcbiAgICAgIHJldHVybiBbXTtcbiAgICB9XG5cbiAgICB2YXIgbWFwcGluZ3MgPSBbXTtcblxuICAgIHZhciBpbmRleCA9IHRoaXMuX2ZpbmRNYXBwaW5nKG5lZWRsZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFwib3JpZ2luYWxMaW5lXCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJvcmlnaW5hbENvbHVtblwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHV0aWwuY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnMsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgYmluYXJ5U2VhcmNoLkxFQVNUX1VQUEVSX0JPVU5EKTtcbiAgICBpZiAoaW5kZXggPj0gMCkge1xuICAgICAgdmFyIG1hcHBpbmcgPSB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzW2luZGV4XTtcblxuICAgICAgaWYgKGFBcmdzLmNvbHVtbiA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIHZhciBvcmlnaW5hbExpbmUgPSBtYXBwaW5nLm9yaWdpbmFsTGluZTtcblxuICAgICAgICAvLyBJdGVyYXRlIHVudGlsIGVpdGhlciB3ZSBydW4gb3V0IG9mIG1hcHBpbmdzLCBvciB3ZSBydW4gaW50b1xuICAgICAgICAvLyBhIG1hcHBpbmcgZm9yIGEgZGlmZmVyZW50IGxpbmUgdGhhbiB0aGUgb25lIHdlIGZvdW5kLiBTaW5jZVxuICAgICAgICAvLyBtYXBwaW5ncyBhcmUgc29ydGVkLCB0aGlzIGlzIGd1YXJhbnRlZWQgdG8gZmluZCBhbGwgbWFwcGluZ3MgZm9yXG4gICAgICAgIC8vIHRoZSBsaW5lIHdlIGZvdW5kLlxuICAgICAgICB3aGlsZSAobWFwcGluZyAmJiBtYXBwaW5nLm9yaWdpbmFsTGluZSA9PT0gb3JpZ2luYWxMaW5lKSB7XG4gICAgICAgICAgbWFwcGluZ3MucHVzaCh7XG4gICAgICAgICAgICBsaW5lOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkTGluZScsIG51bGwpLFxuICAgICAgICAgICAgY29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkQ29sdW1uJywgbnVsbCksXG4gICAgICAgICAgICBsYXN0Q29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnbGFzdEdlbmVyYXRlZENvbHVtbicsIG51bGwpXG4gICAgICAgICAgfSk7XG5cbiAgICAgICAgICBtYXBwaW5nID0gdGhpcy5fb3JpZ2luYWxNYXBwaW5nc1srK2luZGV4XTtcbiAgICAgICAgfVxuICAgICAgfSBlbHNlIHtcbiAgICAgICAgdmFyIG9yaWdpbmFsQ29sdW1uID0gbWFwcGluZy5vcmlnaW5hbENvbHVtbjtcblxuICAgICAgICAvLyBJdGVyYXRlIHVudGlsIGVpdGhlciB3ZSBydW4gb3V0IG9mIG1hcHBpbmdzLCBvciB3ZSBydW4gaW50b1xuICAgICAgICAvLyBhIG1hcHBpbmcgZm9yIGEgZGlmZmVyZW50IGxpbmUgdGhhbiB0aGUgb25lIHdlIHdlcmUgc2VhcmNoaW5nIGZvci5cbiAgICAgICAgLy8gU2luY2UgbWFwcGluZ3MgYXJlIHNvcnRlZCwgdGhpcyBpcyBndWFyYW50ZWVkIHRvIGZpbmQgYWxsIG1hcHBpbmdzIGZvclxuICAgICAgICAvLyB0aGUgbGluZSB3ZSBhcmUgc2VhcmNoaW5nIGZvci5cbiAgICAgICAgd2hpbGUgKG1hcHBpbmcgJiZcbiAgICAgICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxMaW5lID09PSBsaW5lICYmXG4gICAgICAgICAgICAgICBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uID09IG9yaWdpbmFsQ29sdW1uKSB7XG4gICAgICAgICAgbWFwcGluZ3MucHVzaCh7XG4gICAgICAgICAgICBsaW5lOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkTGluZScsIG51bGwpLFxuICAgICAgICAgICAgY29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkQ29sdW1uJywgbnVsbCksXG4gICAgICAgICAgICBsYXN0Q29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnbGFzdEdlbmVyYXRlZENvbHVtbicsIG51bGwpXG4gICAgICAgICAgfSk7XG5cbiAgICAgICAgICBtYXBwaW5nID0gdGhpcy5fb3JpZ2luYWxNYXBwaW5nc1srK2luZGV4XTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiBtYXBwaW5ncztcbiAgfTtcblxuZXhwb3J0cy5Tb3VyY2VNYXBDb25zdW1lciA9IFNvdXJjZU1hcENvbnN1bWVyO1xuXG4vKipcbiAqIEEgQmFzaWNTb3VyY2VNYXBDb25zdW1lciBpbnN0YW5jZSByZXByZXNlbnRzIGEgcGFyc2VkIHNvdXJjZSBtYXAgd2hpY2ggd2UgY2FuXG4gKiBxdWVyeSBmb3IgaW5mb3JtYXRpb24gYWJvdXQgdGhlIG9yaWdpbmFsIGZpbGUgcG9zaXRpb25zIGJ5IGdpdmluZyBpdCBhIGZpbGVcbiAqIHBvc2l0aW9uIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLlxuICpcbiAqIFRoZSBmaXJzdCBwYXJhbWV0ZXIgaXMgdGhlIHJhdyBzb3VyY2UgbWFwIChlaXRoZXIgYXMgYSBKU09OIHN0cmluZywgb3JcbiAqIGFscmVhZHkgcGFyc2VkIHRvIGFuIG9iamVjdCkuIEFjY29yZGluZyB0byB0aGUgc3BlYywgc291cmNlIG1hcHMgaGF2ZSB0aGVcbiAqIGZvbGxvd2luZyBhdHRyaWJ1dGVzOlxuICpcbiAqICAgLSB2ZXJzaW9uOiBXaGljaCB2ZXJzaW9uIG9mIHRoZSBzb3VyY2UgbWFwIHNwZWMgdGhpcyBtYXAgaXMgZm9sbG93aW5nLlxuICogICAtIHNvdXJjZXM6IEFuIGFycmF5IG9mIFVSTHMgdG8gdGhlIG9yaWdpbmFsIHNvdXJjZSBmaWxlcy5cbiAqICAgLSBuYW1lczogQW4gYXJyYXkgb2YgaWRlbnRpZmllcnMgd2hpY2ggY2FuIGJlIHJlZmVycmVuY2VkIGJ5IGluZGl2aWR1YWwgbWFwcGluZ3MuXG4gKiAgIC0gc291cmNlUm9vdDogT3B0aW9uYWwuIFRoZSBVUkwgcm9vdCBmcm9tIHdoaWNoIGFsbCBzb3VyY2VzIGFyZSByZWxhdGl2ZS5cbiAqICAgLSBzb3VyY2VzQ29udGVudDogT3B0aW9uYWwuIEFuIGFycmF5IG9mIGNvbnRlbnRzIG9mIHRoZSBvcmlnaW5hbCBzb3VyY2UgZmlsZXMuXG4gKiAgIC0gbWFwcGluZ3M6IEEgc3RyaW5nIG9mIGJhc2U2NCBWTFFzIHdoaWNoIGNvbnRhaW4gdGhlIGFjdHVhbCBtYXBwaW5ncy5cbiAqICAgLSBmaWxlOiBPcHRpb25hbC4gVGhlIGdlbmVyYXRlZCBmaWxlIHRoaXMgc291cmNlIG1hcCBpcyBhc3NvY2lhdGVkIHdpdGguXG4gKlxuICogSGVyZSBpcyBhbiBleGFtcGxlIHNvdXJjZSBtYXAsIHRha2VuIGZyb20gdGhlIHNvdXJjZSBtYXAgc3BlY1swXTpcbiAqXG4gKiAgICAge1xuICogICAgICAgdmVyc2lvbiA6IDMsXG4gKiAgICAgICBmaWxlOiBcIm91dC5qc1wiLFxuICogICAgICAgc291cmNlUm9vdCA6IFwiXCIsXG4gKiAgICAgICBzb3VyY2VzOiBbXCJmb28uanNcIiwgXCJiYXIuanNcIl0sXG4gKiAgICAgICBuYW1lczogW1wic3JjXCIsIFwibWFwc1wiLCBcImFyZVwiLCBcImZ1blwiXSxcbiAqICAgICAgIG1hcHBpbmdzOiBcIkFBLEFCOztBQkNERTtcIlxuICogICAgIH1cbiAqXG4gKiBUaGUgc2Vjb25kIHBhcmFtZXRlciwgaWYgZ2l2ZW4sIGlzIGEgc3RyaW5nIHdob3NlIHZhbHVlIGlzIHRoZSBVUkxcbiAqIGF0IHdoaWNoIHRoZSBzb3VyY2UgbWFwIHdhcyBmb3VuZC4gIFRoaXMgVVJMIGlzIHVzZWQgdG8gY29tcHV0ZSB0aGVcbiAqIHNvdXJjZXMgYXJyYXkuXG4gKlxuICogWzBdOiBodHRwczovL2RvY3MuZ29vZ2xlLmNvbS9kb2N1bWVudC9kLzFVMVJHQWVoUXdSeXBVVG92RjFLUmxwaU9GemUwYi1fMmdjNmZBSDBLWTBrL2VkaXQ/cGxpPTEjXG4gKi9cbmZ1bmN0aW9uIEJhc2ljU291cmNlTWFwQ29uc3VtZXIoYVNvdXJjZU1hcCwgYVNvdXJjZU1hcFVSTCkge1xuICB2YXIgc291cmNlTWFwID0gYVNvdXJjZU1hcDtcbiAgaWYgKHR5cGVvZiBhU291cmNlTWFwID09PSAnc3RyaW5nJykge1xuICAgIHNvdXJjZU1hcCA9IHV0aWwucGFyc2VTb3VyY2VNYXBJbnB1dChhU291cmNlTWFwKTtcbiAgfVxuXG4gIHZhciB2ZXJzaW9uID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAndmVyc2lvbicpO1xuICB2YXIgc291cmNlcyA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ3NvdXJjZXMnKTtcbiAgLy8gU2FzcyAzLjMgbGVhdmVzIG91dCB0aGUgJ25hbWVzJyBhcnJheSwgc28gd2UgZGV2aWF0ZSBmcm9tIHRoZSBzcGVjICh3aGljaFxuICAvLyByZXF1aXJlcyB0aGUgYXJyYXkpIHRvIHBsYXkgbmljZSBoZXJlLlxuICB2YXIgbmFtZXMgPSB1dGlsLmdldEFyZyhzb3VyY2VNYXAsICduYW1lcycsIFtdKTtcbiAgdmFyIHNvdXJjZVJvb3QgPSB1dGlsLmdldEFyZyhzb3VyY2VNYXAsICdzb3VyY2VSb290JywgbnVsbCk7XG4gIHZhciBzb3VyY2VzQ29udGVudCA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ3NvdXJjZXNDb250ZW50JywgbnVsbCk7XG4gIHZhciBtYXBwaW5ncyA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ21hcHBpbmdzJyk7XG4gIHZhciBmaWxlID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAnZmlsZScsIG51bGwpO1xuXG4gIC8vIE9uY2UgYWdhaW4sIFNhc3MgZGV2aWF0ZXMgZnJvbSB0aGUgc3BlYyBhbmQgc3VwcGxpZXMgdGhlIHZlcnNpb24gYXMgYVxuICAvLyBzdHJpbmcgcmF0aGVyIHRoYW4gYSBudW1iZXIsIHNvIHdlIHVzZSBsb29zZSBlcXVhbGl0eSBjaGVja2luZyBoZXJlLlxuICBpZiAodmVyc2lvbiAhPSB0aGlzLl92ZXJzaW9uKSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKCdVbnN1cHBvcnRlZCB2ZXJzaW9uOiAnICsgdmVyc2lvbik7XG4gIH1cblxuICBpZiAoc291cmNlUm9vdCkge1xuICAgIHNvdXJjZVJvb3QgPSB1dGlsLm5vcm1hbGl6ZShzb3VyY2VSb290KTtcbiAgfVxuXG4gIHNvdXJjZXMgPSBzb3VyY2VzXG4gICAgLm1hcChTdHJpbmcpXG4gICAgLy8gU29tZSBzb3VyY2UgbWFwcyBwcm9kdWNlIHJlbGF0aXZlIHNvdXJjZSBwYXRocyBsaWtlIFwiLi9mb28uanNcIiBpbnN0ZWFkIG9mXG4gICAgLy8gXCJmb28uanNcIi4gIE5vcm1hbGl6ZSB0aGVzZSBmaXJzdCBzbyB0aGF0IGZ1dHVyZSBjb21wYXJpc29ucyB3aWxsIHN1Y2NlZWQuXG4gICAgLy8gU2VlIGJ1Z3ppbC5sYS8xMDkwNzY4LlxuICAgIC5tYXAodXRpbC5ub3JtYWxpemUpXG4gICAgLy8gQWx3YXlzIGVuc3VyZSB0aGF0IGFic29sdXRlIHNvdXJjZXMgYXJlIGludGVybmFsbHkgc3RvcmVkIHJlbGF0aXZlIHRvXG4gICAgLy8gdGhlIHNvdXJjZSByb290LCBpZiB0aGUgc291cmNlIHJvb3QgaXMgYWJzb2x1dGUuIE5vdCBkb2luZyB0aGlzIHdvdWxkXG4gICAgLy8gYmUgcGFydGljdWxhcmx5IHByb2JsZW1hdGljIHdoZW4gdGhlIHNvdXJjZSByb290IGlzIGEgcHJlZml4IG9mIHRoZVxuICAgIC8vIHNvdXJjZSAodmFsaWQsIGJ1dCB3aHk/PykuIFNlZSBnaXRodWIgaXNzdWUgIzE5OSBhbmQgYnVnemlsLmxhLzExODg5ODIuXG4gICAgLm1hcChmdW5jdGlvbiAoc291cmNlKSB7XG4gICAgICByZXR1cm4gc291cmNlUm9vdCAmJiB1dGlsLmlzQWJzb2x1dGUoc291cmNlUm9vdCkgJiYgdXRpbC5pc0Fic29sdXRlKHNvdXJjZSlcbiAgICAgICAgPyB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIHNvdXJjZSlcbiAgICAgICAgOiBzb3VyY2U7XG4gICAgfSk7XG5cbiAgLy8gUGFzcyBgdHJ1ZWAgYmVsb3cgdG8gYWxsb3cgZHVwbGljYXRlIG5hbWVzIGFuZCBzb3VyY2VzLiBXaGlsZSBzb3VyY2UgbWFwc1xuICAvLyBhcmUgaW50ZW5kZWQgdG8gYmUgY29tcHJlc3NlZCBhbmQgZGVkdXBsaWNhdGVkLCB0aGUgVHlwZVNjcmlwdCBjb21waWxlclxuICAvLyBzb21ldGltZXMgZ2VuZXJhdGVzIHNvdXJjZSBtYXBzIHdpdGggZHVwbGljYXRlcyBpbiB0aGVtLiBTZWUgR2l0aHViIGlzc3VlXG4gIC8vICM3MiBhbmQgYnVnemlsLmxhLzg4OTQ5Mi5cbiAgdGhpcy5fbmFtZXMgPSBBcnJheVNldC5mcm9tQXJyYXkobmFtZXMubWFwKFN0cmluZyksIHRydWUpO1xuICB0aGlzLl9zb3VyY2VzID0gQXJyYXlTZXQuZnJvbUFycmF5KHNvdXJjZXMsIHRydWUpO1xuXG4gIHRoaXMuX2Fic29sdXRlU291cmNlcyA9IHRoaXMuX3NvdXJjZXMudG9BcnJheSgpLm1hcChmdW5jdGlvbiAocykge1xuICAgIHJldHVybiB1dGlsLmNvbXB1dGVTb3VyY2VVUkwoc291cmNlUm9vdCwgcywgYVNvdXJjZU1hcFVSTCk7XG4gIH0pO1xuXG4gIHRoaXMuc291cmNlUm9vdCA9IHNvdXJjZVJvb3Q7XG4gIHRoaXMuc291cmNlc0NvbnRlbnQgPSBzb3VyY2VzQ29udGVudDtcbiAgdGhpcy5fbWFwcGluZ3MgPSBtYXBwaW5ncztcbiAgdGhpcy5fc291cmNlTWFwVVJMID0gYVNvdXJjZU1hcFVSTDtcbiAgdGhpcy5maWxlID0gZmlsZTtcbn1cblxuQmFzaWNTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUgPSBPYmplY3QuY3JlYXRlKFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZSk7XG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5jb25zdW1lciA9IFNvdXJjZU1hcENvbnN1bWVyO1xuXG4vKipcbiAqIFV0aWxpdHkgZnVuY3Rpb24gdG8gZmluZCB0aGUgaW5kZXggb2YgYSBzb3VyY2UuICBSZXR1cm5zIC0xIGlmIG5vdFxuICogZm91bmQuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLl9maW5kU291cmNlSW5kZXggPSBmdW5jdGlvbihhU291cmNlKSB7XG4gIHZhciByZWxhdGl2ZVNvdXJjZSA9IGFTb3VyY2U7XG4gIGlmICh0aGlzLnNvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgIHJlbGF0aXZlU291cmNlID0gdXRpbC5yZWxhdGl2ZSh0aGlzLnNvdXJjZVJvb3QsIHJlbGF0aXZlU291cmNlKTtcbiAgfVxuXG4gIGlmICh0aGlzLl9zb3VyY2VzLmhhcyhyZWxhdGl2ZVNvdXJjZSkpIHtcbiAgICByZXR1cm4gdGhpcy5fc291cmNlcy5pbmRleE9mKHJlbGF0aXZlU291cmNlKTtcbiAgfVxuXG4gIC8vIE1heWJlIGFTb3VyY2UgaXMgYW4gYWJzb2x1dGUgVVJMIGFzIHJldHVybmVkIGJ5IHxzb3VyY2VzfC4gIEluXG4gIC8vIHRoaXMgY2FzZSB3ZSBjYW4ndCBzaW1wbHkgdW5kbyB0aGUgdHJhbnNmb3JtLlxuICB2YXIgaTtcbiAgZm9yIChpID0gMDsgaSA8IHRoaXMuX2Fic29sdXRlU291cmNlcy5sZW5ndGg7ICsraSkge1xuICAgIGlmICh0aGlzLl9hYnNvbHV0ZVNvdXJjZXNbaV0gPT0gYVNvdXJjZSkge1xuICAgICAgcmV0dXJuIGk7XG4gICAgfVxuICB9XG5cbiAgcmV0dXJuIC0xO1xufTtcblxuLyoqXG4gKiBDcmVhdGUgYSBCYXNpY1NvdXJjZU1hcENvbnN1bWVyIGZyb20gYSBTb3VyY2VNYXBHZW5lcmF0b3IuXG4gKlxuICogQHBhcmFtIFNvdXJjZU1hcEdlbmVyYXRvciBhU291cmNlTWFwXG4gKiAgICAgICAgVGhlIHNvdXJjZSBtYXAgdGhhdCB3aWxsIGJlIGNvbnN1bWVkLlxuICogQHBhcmFtIFN0cmluZyBhU291cmNlTWFwVVJMXG4gKiAgICAgICAgVGhlIFVSTCBhdCB3aGljaCB0aGUgc291cmNlIG1hcCBjYW4gYmUgZm91bmQgKG9wdGlvbmFsKVxuICogQHJldHVybnMgQmFzaWNTb3VyY2VNYXBDb25zdW1lclxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLmZyb21Tb3VyY2VNYXAgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9mcm9tU291cmNlTWFwKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgICB2YXIgc21jID0gT2JqZWN0LmNyZWF0ZShCYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZSk7XG5cbiAgICB2YXIgbmFtZXMgPSBzbWMuX25hbWVzID0gQXJyYXlTZXQuZnJvbUFycmF5KGFTb3VyY2VNYXAuX25hbWVzLnRvQXJyYXkoKSwgdHJ1ZSk7XG4gICAgdmFyIHNvdXJjZXMgPSBzbWMuX3NvdXJjZXMgPSBBcnJheVNldC5mcm9tQXJyYXkoYVNvdXJjZU1hcC5fc291cmNlcy50b0FycmF5KCksIHRydWUpO1xuICAgIHNtYy5zb3VyY2VSb290ID0gYVNvdXJjZU1hcC5fc291cmNlUm9vdDtcbiAgICBzbWMuc291cmNlc0NvbnRlbnQgPSBhU291cmNlTWFwLl9nZW5lcmF0ZVNvdXJjZXNDb250ZW50KHNtYy5fc291cmNlcy50b0FycmF5KCksXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBzbWMuc291cmNlUm9vdCk7XG4gICAgc21jLmZpbGUgPSBhU291cmNlTWFwLl9maWxlO1xuICAgIHNtYy5fc291cmNlTWFwVVJMID0gYVNvdXJjZU1hcFVSTDtcbiAgICBzbWMuX2Fic29sdXRlU291cmNlcyA9IHNtYy5fc291cmNlcy50b0FycmF5KCkubWFwKGZ1bmN0aW9uIChzKSB7XG4gICAgICByZXR1cm4gdXRpbC5jb21wdXRlU291cmNlVVJMKHNtYy5zb3VyY2VSb290LCBzLCBhU291cmNlTWFwVVJMKTtcbiAgICB9KTtcblxuICAgIC8vIEJlY2F1c2Ugd2UgYXJlIG1vZGlmeWluZyB0aGUgZW50cmllcyAoYnkgY29udmVydGluZyBzdHJpbmcgc291cmNlcyBhbmRcbiAgICAvLyBuYW1lcyB0byBpbmRpY2VzIGludG8gdGhlIHNvdXJjZXMgYW5kIG5hbWVzIEFycmF5U2V0cyksIHdlIGhhdmUgdG8gbWFrZVxuICAgIC8vIGEgY29weSBvZiB0aGUgZW50cnkgb3IgZWxzZSBiYWQgdGhpbmdzIGhhcHBlbi4gU2hhcmVkIG11dGFibGUgc3RhdGVcbiAgICAvLyBzdHJpa2VzIGFnYWluISBTZWUgZ2l0aHViIGlzc3VlICMxOTEuXG5cbiAgICB2YXIgZ2VuZXJhdGVkTWFwcGluZ3MgPSBhU291cmNlTWFwLl9tYXBwaW5ncy50b0FycmF5KCkuc2xpY2UoKTtcbiAgICB2YXIgZGVzdEdlbmVyYXRlZE1hcHBpbmdzID0gc21jLl9fZ2VuZXJhdGVkTWFwcGluZ3MgPSBbXTtcbiAgICB2YXIgZGVzdE9yaWdpbmFsTWFwcGluZ3MgPSBzbWMuX19vcmlnaW5hbE1hcHBpbmdzID0gW107XG5cbiAgICBmb3IgKHZhciBpID0gMCwgbGVuZ3RoID0gZ2VuZXJhdGVkTWFwcGluZ3MubGVuZ3RoOyBpIDwgbGVuZ3RoOyBpKyspIHtcbiAgICAgIHZhciBzcmNNYXBwaW5nID0gZ2VuZXJhdGVkTWFwcGluZ3NbaV07XG4gICAgICB2YXIgZGVzdE1hcHBpbmcgPSBuZXcgTWFwcGluZztcbiAgICAgIGRlc3RNYXBwaW5nLmdlbmVyYXRlZExpbmUgPSBzcmNNYXBwaW5nLmdlbmVyYXRlZExpbmU7XG4gICAgICBkZXN0TWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4gPSBzcmNNYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgaWYgKHNyY01hcHBpbmcuc291cmNlKSB7XG4gICAgICAgIGRlc3RNYXBwaW5nLnNvdXJjZSA9IHNvdXJjZXMuaW5kZXhPZihzcmNNYXBwaW5nLnNvdXJjZSk7XG4gICAgICAgIGRlc3RNYXBwaW5nLm9yaWdpbmFsTGluZSA9IHNyY01hcHBpbmcub3JpZ2luYWxMaW5lO1xuICAgICAgICBkZXN0TWFwcGluZy5vcmlnaW5hbENvbHVtbiA9IHNyY01hcHBpbmcub3JpZ2luYWxDb2x1bW47XG5cbiAgICAgICAgaWYgKHNyY01hcHBpbmcubmFtZSkge1xuICAgICAgICAgIGRlc3RNYXBwaW5nLm5hbWUgPSBuYW1lcy5pbmRleE9mKHNyY01hcHBpbmcubmFtZSk7XG4gICAgICAgIH1cblxuICAgICAgICBkZXN0T3JpZ2luYWxNYXBwaW5ncy5wdXNoKGRlc3RNYXBwaW5nKTtcbiAgICAgIH1cblxuICAgICAgZGVzdEdlbmVyYXRlZE1hcHBpbmdzLnB1c2goZGVzdE1hcHBpbmcpO1xuICAgIH1cblxuICAgIHF1aWNrU29ydChzbWMuX19vcmlnaW5hbE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zKTtcblxuICAgIHJldHVybiBzbWM7XG4gIH07XG5cbi8qKlxuICogVGhlIHZlcnNpb24gb2YgdGhlIHNvdXJjZSBtYXBwaW5nIHNwZWMgdGhhdCB3ZSBhcmUgY29uc3VtaW5nLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8qKlxuICogVGhlIGxpc3Qgb2Ygb3JpZ2luYWwgc291cmNlcy5cbiAqL1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KEJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLCAnc291cmNlcycsIHtcbiAgZ2V0OiBmdW5jdGlvbiAoKSB7XG4gICAgcmV0dXJuIHRoaXMuX2Fic29sdXRlU291cmNlcy5zbGljZSgpO1xuICB9XG59KTtcblxuLyoqXG4gKiBQcm92aWRlIHRoZSBKSVQgd2l0aCBhIG5pY2Ugc2hhcGUgLyBoaWRkZW4gY2xhc3MuXG4gKi9cbmZ1bmN0aW9uIE1hcHBpbmcoKSB7XG4gIHRoaXMuZ2VuZXJhdGVkTGluZSA9IDA7XG4gIHRoaXMuZ2VuZXJhdGVkQ29sdW1uID0gMDtcbiAgdGhpcy5zb3VyY2UgPSBudWxsO1xuICB0aGlzLm9yaWdpbmFsTGluZSA9IG51bGw7XG4gIHRoaXMub3JpZ2luYWxDb2x1bW4gPSBudWxsO1xuICB0aGlzLm5hbWUgPSBudWxsO1xufVxuXG4vKipcbiAqIFBhcnNlIHRoZSBtYXBwaW5ncyBpbiBhIHN0cmluZyBpbiB0byBhIGRhdGEgc3RydWN0dXJlIHdoaWNoIHdlIGNhbiBlYXNpbHlcbiAqIHF1ZXJ5ICh0aGUgb3JkZXJlZCBhcnJheXMgaW4gdGhlIGB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3NgIGFuZFxuICogYHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzYCBwcm9wZXJ0aWVzKS5cbiAqL1xuQmFzaWNTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX3BhcnNlTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9wYXJzZU1hcHBpbmdzKGFTdHIsIGFTb3VyY2VSb290KSB7XG4gICAgdmFyIGdlbmVyYXRlZExpbmUgPSAxO1xuICAgIHZhciBwcmV2aW91c0dlbmVyYXRlZENvbHVtbiA9IDA7XG4gICAgdmFyIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gMDtcbiAgICB2YXIgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IDA7XG4gICAgdmFyIHByZXZpb3VzU291cmNlID0gMDtcbiAgICB2YXIgcHJldmlvdXNOYW1lID0gMDtcbiAgICB2YXIgbGVuZ3RoID0gYVN0ci5sZW5ndGg7XG4gICAgdmFyIGluZGV4ID0gMDtcbiAgICB2YXIgY2FjaGVkU2VnbWVudHMgPSB7fTtcbiAgICB2YXIgdGVtcCA9IHt9O1xuICAgIHZhciBvcmlnaW5hbE1hcHBpbmdzID0gW107XG4gICAgdmFyIGdlbmVyYXRlZE1hcHBpbmdzID0gW107XG4gICAgdmFyIG1hcHBpbmcsIHN0ciwgc2VnbWVudCwgZW5kLCB2YWx1ZTtcblxuICAgIHdoaWxlIChpbmRleCA8IGxlbmd0aCkge1xuICAgICAgaWYgKGFTdHIuY2hhckF0KGluZGV4KSA9PT0gJzsnKSB7XG4gICAgICAgIGdlbmVyYXRlZExpbmUrKztcbiAgICAgICAgaW5kZXgrKztcbiAgICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSAwO1xuICAgICAgfVxuICAgICAgZWxzZSBpZiAoYVN0ci5jaGFyQXQoaW5kZXgpID09PSAnLCcpIHtcbiAgICAgICAgaW5kZXgrKztcbiAgICAgIH1cbiAgICAgIGVsc2Uge1xuICAgICAgICBtYXBwaW5nID0gbmV3IE1hcHBpbmcoKTtcbiAgICAgICAgbWFwcGluZy5nZW5lcmF0ZWRMaW5lID0gZ2VuZXJhdGVkTGluZTtcblxuICAgICAgICAvLyBCZWNhdXNlIGVhY2ggb2Zmc2V0IGlzIGVuY29kZWQgcmVsYXRpdmUgdG8gdGhlIHByZXZpb3VzIG9uZSxcbiAgICAgICAgLy8gbWFueSBzZWdtZW50cyBvZnRlbiBoYXZlIHRoZSBzYW1lIGVuY29kaW5nLiBXZSBjYW4gZXhwbG9pdCB0aGlzXG4gICAgICAgIC8vIGZhY3QgYnkgY2FjaGluZyB0aGUgcGFyc2VkIHZhcmlhYmxlIGxlbmd0aCBmaWVsZHMgb2YgZWFjaCBzZWdtZW50LFxuICAgICAgICAvLyBhbGxvd2luZyB1cyB0byBhdm9pZCBhIHNlY29uZCBwYXJzZSBpZiB3ZSBlbmNvdW50ZXIgdGhlIHNhbWVcbiAgICAgICAgLy8gc2VnbWVudCBhZ2Fpbi5cbiAgICAgICAgZm9yIChlbmQgPSBpbmRleDsgZW5kIDwgbGVuZ3RoOyBlbmQrKykge1xuICAgICAgICAgIGlmICh0aGlzLl9jaGFySXNNYXBwaW5nU2VwYXJhdG9yKGFTdHIsIGVuZCkpIHtcbiAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBzdHIgPSBhU3RyLnNsaWNlKGluZGV4LCBlbmQpO1xuXG4gICAgICAgIHNlZ21lbnQgPSBjYWNoZWRTZWdtZW50c1tzdHJdO1xuICAgICAgICBpZiAoc2VnbWVudCkge1xuICAgICAgICAgIGluZGV4ICs9IHN0ci5sZW5ndGg7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgc2VnbWVudCA9IFtdO1xuICAgICAgICAgIHdoaWxlIChpbmRleCA8IGVuZCkge1xuICAgICAgICAgICAgYmFzZTY0VkxRLmRlY29kZShhU3RyLCBpbmRleCwgdGVtcCk7XG4gICAgICAgICAgICB2YWx1ZSA9IHRlbXAudmFsdWU7XG4gICAgICAgICAgICBpbmRleCA9IHRlbXAucmVzdDtcbiAgICAgICAgICAgIHNlZ21lbnQucHVzaCh2YWx1ZSk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAyKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlLCBidXQgbm8gbGluZSBhbmQgY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAzKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlIGFuZCBsaW5lLCBidXQgbm8gY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgY2FjaGVkU2VnbWVudHNbc3RyXSA9IHNlZ21lbnQ7XG4gICAgICAgIH1cblxuICAgICAgICAvLyBHZW5lcmF0ZWQgY29sdW1uLlxuICAgICAgICBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbiA9IHByZXZpb3VzR2VuZXJhdGVkQ29sdW1uICsgc2VnbWVudFswXTtcbiAgICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgICBpZiAoc2VnbWVudC5sZW5ndGggPiAxKSB7XG4gICAgICAgICAgLy8gT3JpZ2luYWwgc291cmNlLlxuICAgICAgICAgIG1hcHBpbmcuc291cmNlID0gcHJldmlvdXNTb3VyY2UgKyBzZWdtZW50WzFdO1xuICAgICAgICAgIHByZXZpb3VzU291cmNlICs9IHNlZ21lbnRbMV07XG5cbiAgICAgICAgICAvLyBPcmlnaW5hbCBsaW5lLlxuICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxMaW5lID0gcHJldmlvdXNPcmlnaW5hbExpbmUgKyBzZWdtZW50WzJdO1xuICAgICAgICAgIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gbWFwcGluZy5vcmlnaW5hbExpbmU7XG4gICAgICAgICAgLy8gTGluZXMgYXJlIHN0b3JlZCAwLWJhc2VkXG4gICAgICAgICAgbWFwcGluZy5vcmlnaW5hbExpbmUgKz0gMTtcblxuICAgICAgICAgIC8vIE9yaWdpbmFsIGNvbHVtbi5cbiAgICAgICAgICBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uID0gcHJldmlvdXNPcmlnaW5hbENvbHVtbiArIHNlZ21lbnRbM107XG4gICAgICAgICAgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IG1hcHBpbmcub3JpZ2luYWxDb2x1bW47XG5cbiAgICAgICAgICBpZiAoc2VnbWVudC5sZW5ndGggPiA0KSB7XG4gICAgICAgICAgICAvLyBPcmlnaW5hbCBuYW1lLlxuICAgICAgICAgICAgbWFwcGluZy5uYW1lID0gcHJldmlvdXNOYW1lICsgc2VnbWVudFs0XTtcbiAgICAgICAgICAgIHByZXZpb3VzTmFtZSArPSBzZWdtZW50WzRdO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuXG4gICAgICAgIGdlbmVyYXRlZE1hcHBpbmdzLnB1c2gobWFwcGluZyk7XG4gICAgICAgIGlmICh0eXBlb2YgbWFwcGluZy5vcmlnaW5hbExpbmUgPT09ICdudW1iZXInKSB7XG4gICAgICAgICAgb3JpZ2luYWxNYXBwaW5ncy5wdXNoKG1hcHBpbmcpO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfVxuXG4gICAgcXVpY2tTb3J0KGdlbmVyYXRlZE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0RlZmxhdGVkKTtcbiAgICB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3MgPSBnZW5lcmF0ZWRNYXBwaW5ncztcblxuICAgIHF1aWNrU29ydChvcmlnaW5hbE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zKTtcbiAgICB0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncyA9IG9yaWdpbmFsTWFwcGluZ3M7XG4gIH07XG5cbi8qKlxuICogRmluZCB0aGUgbWFwcGluZyB0aGF0IGJlc3QgbWF0Y2hlcyB0aGUgaHlwb3RoZXRpY2FsIFwibmVlZGxlXCIgbWFwcGluZyB0aGF0XG4gKiB3ZSBhcmUgc2VhcmNoaW5nIGZvciBpbiB0aGUgZ2l2ZW4gXCJoYXlzdGFja1wiIG9mIG1hcHBpbmdzLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fZmluZE1hcHBpbmcgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9maW5kTWFwcGluZyhhTmVlZGxlLCBhTWFwcGluZ3MsIGFMaW5lTmFtZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgYUNvbHVtbk5hbWUsIGFDb21wYXJhdG9yLCBhQmlhcykge1xuICAgIC8vIFRvIHJldHVybiB0aGUgcG9zaXRpb24gd2UgYXJlIHNlYXJjaGluZyBmb3IsIHdlIG11c3QgZmlyc3QgZmluZCB0aGVcbiAgICAvLyBtYXBwaW5nIGZvciB0aGUgZ2l2ZW4gcG9zaXRpb24gYW5kIHRoZW4gcmV0dXJuIHRoZSBvcHBvc2l0ZSBwb3NpdGlvbiBpdFxuICAgIC8vIHBvaW50cyB0by4gQmVjYXVzZSB0aGUgbWFwcGluZ3MgYXJlIHNvcnRlZCwgd2UgY2FuIHVzZSBiaW5hcnkgc2VhcmNoIHRvXG4gICAgLy8gZmluZCB0aGUgYmVzdCBtYXBwaW5nLlxuXG4gICAgaWYgKGFOZWVkbGVbYUxpbmVOYW1lXSA8PSAwKSB7XG4gICAgICB0aHJvdyBuZXcgVHlwZUVycm9yKCdMaW5lIG11c3QgYmUgZ3JlYXRlciB0aGFuIG9yIGVxdWFsIHRvIDEsIGdvdCAnXG4gICAgICAgICAgICAgICAgICAgICAgICAgICsgYU5lZWRsZVthTGluZU5hbWVdKTtcbiAgICB9XG4gICAgaWYgKGFOZWVkbGVbYUNvbHVtbk5hbWVdIDwgMCkge1xuICAgICAgdGhyb3cgbmV3IFR5cGVFcnJvcignQ29sdW1uIG11c3QgYmUgZ3JlYXRlciB0aGFuIG9yIGVxdWFsIHRvIDAsIGdvdCAnXG4gICAgICAgICAgICAgICAgICAgICAgICAgICsgYU5lZWRsZVthQ29sdW1uTmFtZV0pO1xuICAgIH1cblxuICAgIHJldHVybiBiaW5hcnlTZWFyY2guc2VhcmNoKGFOZWVkbGUsIGFNYXBwaW5ncywgYUNvbXBhcmF0b3IsIGFCaWFzKTtcbiAgfTtcblxuLyoqXG4gKiBDb21wdXRlIHRoZSBsYXN0IGNvbHVtbiBmb3IgZWFjaCBnZW5lcmF0ZWQgbWFwcGluZy4gVGhlIGxhc3QgY29sdW1uIGlzXG4gKiBpbmNsdXNpdmUuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmNvbXB1dGVDb2x1bW5TcGFucyA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2NvbXB1dGVDb2x1bW5TcGFucygpIHtcbiAgICBmb3IgKHZhciBpbmRleCA9IDA7IGluZGV4IDwgdGhpcy5fZ2VuZXJhdGVkTWFwcGluZ3MubGVuZ3RoOyArK2luZGV4KSB7XG4gICAgICB2YXIgbWFwcGluZyA9IHRoaXMuX2dlbmVyYXRlZE1hcHBpbmdzW2luZGV4XTtcblxuICAgICAgLy8gTWFwcGluZ3MgZG8gbm90IGNvbnRhaW4gYSBmaWVsZCBmb3IgdGhlIGxhc3QgZ2VuZXJhdGVkIGNvbHVtbnQuIFdlXG4gICAgICAvLyBjYW4gY29tZSB1cCB3aXRoIGFuIG9wdGltaXN0aWMgZXN0aW1hdGUsIGhvd2V2ZXIsIGJ5IGFzc3VtaW5nIHRoYXRcbiAgICAgIC8vIG1hcHBpbmdzIGFyZSBjb250aWd1b3VzIChpLmUuIGdpdmVuIHR3byBjb25zZWN1dGl2ZSBtYXBwaW5ncywgdGhlXG4gICAgICAvLyBmaXJzdCBtYXBwaW5nIGVuZHMgd2hlcmUgdGhlIHNlY29uZCBvbmUgc3RhcnRzKS5cbiAgICAgIGlmIChpbmRleCArIDEgPCB0aGlzLl9nZW5lcmF0ZWRNYXBwaW5ncy5sZW5ndGgpIHtcbiAgICAgICAgdmFyIG5leHRNYXBwaW5nID0gdGhpcy5fZ2VuZXJhdGVkTWFwcGluZ3NbaW5kZXggKyAxXTtcblxuICAgICAgICBpZiAobWFwcGluZy5nZW5lcmF0ZWRMaW5lID09PSBuZXh0TWFwcGluZy5nZW5lcmF0ZWRMaW5lKSB7XG4gICAgICAgICAgbWFwcGluZy5sYXN0R2VuZXJhdGVkQ29sdW1uID0gbmV4dE1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uIC0gMTtcbiAgICAgICAgICBjb250aW51ZTtcbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICAvLyBUaGUgbGFzdCBtYXBwaW5nIGZvciBlYWNoIGxpbmUgc3BhbnMgdGhlIGVudGlyZSBsaW5lLlxuICAgICAgbWFwcGluZy5sYXN0R2VuZXJhdGVkQ29sdW1uID0gSW5maW5pdHk7XG4gICAgfVxuICB9O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIG9yaWdpbmFsIHNvdXJjZSwgbGluZSwgYW5kIGNvbHVtbiBpbmZvcm1hdGlvbiBmb3IgdGhlIGdlbmVyYXRlZFxuICogc291cmNlJ3MgbGluZSBhbmQgY29sdW1uIHBvc2l0aW9ucyBwcm92aWRlZC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgYW4gb2JqZWN0XG4gKiB3aXRoIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLiAgVGhlIGxpbmUgbnVtYmVyXG4gKiAgICAgaXMgMS1iYXNlZC5cbiAqICAgLSBjb2x1bW46IFRoZSBjb2x1bW4gbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLiAgVGhlIGNvbHVtblxuICogICAgIG51bWJlciBpcyAwLWJhc2VkLlxuICogICAtIGJpYXM6IEVpdGhlciAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnIG9yXG4gKiAgICAgJ1NvdXJjZU1hcENvbnN1bWVyLkxFQVNUX1VQUEVSX0JPVU5EJy4gU3BlY2lmaWVzIHdoZXRoZXIgdG8gcmV0dXJuIHRoZVxuICogICAgIGNsb3Nlc3QgZWxlbWVudCB0aGF0IGlzIHNtYWxsZXIgdGhhbiBvciBncmVhdGVyIHRoYW4gdGhlIG9uZSB3ZSBhcmVcbiAqICAgICBzZWFyY2hpbmcgZm9yLCByZXNwZWN0aXZlbHksIGlmIHRoZSBleGFjdCBlbGVtZW50IGNhbm5vdCBiZSBmb3VuZC5cbiAqICAgICBEZWZhdWx0cyB0byAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIHNvdXJjZTogVGhlIG9yaWdpbmFsIHNvdXJjZSBmaWxlLCBvciBudWxsLlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLCBvciBudWxsLiAgVGhlXG4gKiAgICAgbGluZSBudW1iZXIgaXMgMS1iYXNlZC5cbiAqICAgLSBjb2x1bW46IFRoZSBjb2x1bW4gbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UsIG9yIG51bGwuICBUaGVcbiAqICAgICBjb2x1bW4gbnVtYmVyIGlzIDAtYmFzZWQuXG4gKiAgIC0gbmFtZTogVGhlIG9yaWdpbmFsIGlkZW50aWZpZXIsIG9yIG51bGwuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLm9yaWdpbmFsUG9zaXRpb25Gb3IgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9vcmlnaW5hbFBvc2l0aW9uRm9yKGFBcmdzKSB7XG4gICAgdmFyIG5lZWRsZSA9IHtcbiAgICAgIGdlbmVyYXRlZExpbmU6IHV0aWwuZ2V0QXJnKGFBcmdzLCAnbGluZScpLFxuICAgICAgZ2VuZXJhdGVkQ29sdW1uOiB1dGlsLmdldEFyZyhhQXJncywgJ2NvbHVtbicpXG4gICAgfTtcblxuICAgIHZhciBpbmRleCA9IHRoaXMuX2ZpbmRNYXBwaW5nKFxuICAgICAgbmVlZGxlLFxuICAgICAgdGhpcy5fZ2VuZXJhdGVkTWFwcGluZ3MsXG4gICAgICBcImdlbmVyYXRlZExpbmVcIixcbiAgICAgIFwiZ2VuZXJhdGVkQ29sdW1uXCIsXG4gICAgICB1dGlsLmNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0RlZmxhdGVkLFxuICAgICAgdXRpbC5nZXRBcmcoYUFyZ3MsICdiaWFzJywgU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQpXG4gICAgKTtcblxuICAgIGlmIChpbmRleCA+PSAwKSB7XG4gICAgICB2YXIgbWFwcGluZyA9IHRoaXMuX2dlbmVyYXRlZE1hcHBpbmdzW2luZGV4XTtcblxuICAgICAgaWYgKG1hcHBpbmcuZ2VuZXJhdGVkTGluZSA9PT0gbmVlZGxlLmdlbmVyYXRlZExpbmUpIHtcbiAgICAgICAgdmFyIHNvdXJjZSA9IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdzb3VyY2UnLCBudWxsKTtcbiAgICAgICAgaWYgKHNvdXJjZSAhPT0gbnVsbCkge1xuICAgICAgICAgIHNvdXJjZSA9IHRoaXMuX3NvdXJjZXMuYXQoc291cmNlKTtcbiAgICAgICAgICBzb3VyY2UgPSB1dGlsLmNvbXB1dGVTb3VyY2VVUkwodGhpcy5zb3VyY2VSb290LCBzb3VyY2UsIHRoaXMuX3NvdXJjZU1hcFVSTCk7XG4gICAgICAgIH1cbiAgICAgICAgdmFyIG5hbWUgPSB1dGlsLmdldEFyZyhtYXBwaW5nLCAnbmFtZScsIG51bGwpO1xuICAgICAgICBpZiAobmFtZSAhPT0gbnVsbCkge1xuICAgICAgICAgIG5hbWUgPSB0aGlzLl9uYW1lcy5hdChuYW1lKTtcbiAgICAgICAgfVxuICAgICAgICByZXR1cm4ge1xuICAgICAgICAgIHNvdXJjZTogc291cmNlLFxuICAgICAgICAgIGxpbmU6IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdvcmlnaW5hbExpbmUnLCBudWxsKSxcbiAgICAgICAgICBjb2x1bW46IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdvcmlnaW5hbENvbHVtbicsIG51bGwpLFxuICAgICAgICAgIG5hbWU6IG5hbWVcbiAgICAgICAgfTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICByZXR1cm4ge1xuICAgICAgc291cmNlOiBudWxsLFxuICAgICAgbGluZTogbnVsbCxcbiAgICAgIGNvbHVtbjogbnVsbCxcbiAgICAgIG5hbWU6IG51bGxcbiAgICB9O1xuICB9O1xuXG4vKipcbiAqIFJldHVybiB0cnVlIGlmIHdlIGhhdmUgdGhlIHNvdXJjZSBjb250ZW50IGZvciBldmVyeSBzb3VyY2UgaW4gdGhlIHNvdXJjZVxuICogbWFwLCBmYWxzZSBvdGhlcndpc2UuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmhhc0NvbnRlbnRzT2ZBbGxTb3VyY2VzID1cbiAgZnVuY3Rpb24gQmFzaWNTb3VyY2VNYXBDb25zdW1lcl9oYXNDb250ZW50c09mQWxsU291cmNlcygpIHtcbiAgICBpZiAoIXRoaXMuc291cmNlc0NvbnRlbnQpIHtcbiAgICAgIHJldHVybiBmYWxzZTtcbiAgICB9XG4gICAgcmV0dXJuIHRoaXMuc291cmNlc0NvbnRlbnQubGVuZ3RoID49IHRoaXMuX3NvdXJjZXMuc2l6ZSgpICYmXG4gICAgICAhdGhpcy5zb3VyY2VzQ29udGVudC5zb21lKGZ1bmN0aW9uIChzYykgeyByZXR1cm4gc2MgPT0gbnVsbDsgfSk7XG4gIH07XG5cbi8qKlxuICogUmV0dXJucyB0aGUgb3JpZ2luYWwgc291cmNlIGNvbnRlbnQuIFRoZSBvbmx5IGFyZ3VtZW50IGlzIHRoZSB1cmwgb2YgdGhlXG4gKiBvcmlnaW5hbCBzb3VyY2UgZmlsZS4gUmV0dXJucyBudWxsIGlmIG5vIG9yaWdpbmFsIHNvdXJjZSBjb250ZW50IGlzXG4gKiBhdmFpbGFibGUuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLnNvdXJjZUNvbnRlbnRGb3IgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9zb3VyY2VDb250ZW50Rm9yKGFTb3VyY2UsIG51bGxPbk1pc3NpbmcpIHtcbiAgICBpZiAoIXRoaXMuc291cmNlc0NvbnRlbnQpIHtcbiAgICAgIHJldHVybiBudWxsO1xuICAgIH1cblxuICAgIHZhciBpbmRleCA9IHRoaXMuX2ZpbmRTb3VyY2VJbmRleChhU291cmNlKTtcbiAgICBpZiAoaW5kZXggPj0gMCkge1xuICAgICAgcmV0dXJuIHRoaXMuc291cmNlc0NvbnRlbnRbaW5kZXhdO1xuICAgIH1cblxuICAgIHZhciByZWxhdGl2ZVNvdXJjZSA9IGFTb3VyY2U7XG4gICAgaWYgKHRoaXMuc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICByZWxhdGl2ZVNvdXJjZSA9IHV0aWwucmVsYXRpdmUodGhpcy5zb3VyY2VSb290LCByZWxhdGl2ZVNvdXJjZSk7XG4gICAgfVxuXG4gICAgdmFyIHVybDtcbiAgICBpZiAodGhpcy5zb3VyY2VSb290ICE9IG51bGxcbiAgICAgICAgJiYgKHVybCA9IHV0aWwudXJsUGFyc2UodGhpcy5zb3VyY2VSb290KSkpIHtcbiAgICAgIC8vIFhYWDogZmlsZTovLyBVUklzIGFuZCBhYnNvbHV0ZSBwYXRocyBsZWFkIHRvIHVuZXhwZWN0ZWQgYmVoYXZpb3IgZm9yXG4gICAgICAvLyBtYW55IHVzZXJzLiBXZSBjYW4gaGVscCB0aGVtIG91dCB3aGVuIHRoZXkgZXhwZWN0IGZpbGU6Ly8gVVJJcyB0b1xuICAgICAgLy8gYmVoYXZlIGxpa2UgaXQgd291bGQgaWYgdGhleSB3ZXJlIHJ1bm5pbmcgYSBsb2NhbCBIVFRQIHNlcnZlci4gU2VlXG4gICAgICAvLyBodHRwczovL2J1Z3ppbGxhLm1vemlsbGEub3JnL3Nob3dfYnVnLmNnaT9pZD04ODU1OTcuXG4gICAgICB2YXIgZmlsZVVyaUFic1BhdGggPSByZWxhdGl2ZVNvdXJjZS5yZXBsYWNlKC9eZmlsZTpcXC9cXC8vLCBcIlwiKTtcbiAgICAgIGlmICh1cmwuc2NoZW1lID09IFwiZmlsZVwiXG4gICAgICAgICAgJiYgdGhpcy5fc291cmNlcy5oYXMoZmlsZVVyaUFic1BhdGgpKSB7XG4gICAgICAgIHJldHVybiB0aGlzLnNvdXJjZXNDb250ZW50W3RoaXMuX3NvdXJjZXMuaW5kZXhPZihmaWxlVXJpQWJzUGF0aCldXG4gICAgICB9XG5cbiAgICAgIGlmICgoIXVybC5wYXRoIHx8IHVybC5wYXRoID09IFwiL1wiKVxuICAgICAgICAgICYmIHRoaXMuX3NvdXJjZXMuaGFzKFwiL1wiICsgcmVsYXRpdmVTb3VyY2UpKSB7XG4gICAgICAgIHJldHVybiB0aGlzLnNvdXJjZXNDb250ZW50W3RoaXMuX3NvdXJjZXMuaW5kZXhPZihcIi9cIiArIHJlbGF0aXZlU291cmNlKV07XG4gICAgICB9XG4gICAgfVxuXG4gICAgLy8gVGhpcyBmdW5jdGlvbiBpcyB1c2VkIHJlY3Vyc2l2ZWx5IGZyb21cbiAgICAvLyBJbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLnNvdXJjZUNvbnRlbnRGb3IuIEluIHRoYXQgY2FzZSwgd2VcbiAgICAvLyBkb24ndCB3YW50IHRvIHRocm93IGlmIHdlIGNhbid0IGZpbmQgdGhlIHNvdXJjZSAtIHdlIGp1c3Qgd2FudCB0b1xuICAgIC8vIHJldHVybiBudWxsLCBzbyB3ZSBwcm92aWRlIGEgZmxhZyB0byBleGl0IGdyYWNlZnVsbHkuXG4gICAgaWYgKG51bGxPbk1pc3NpbmcpIHtcbiAgICAgIHJldHVybiBudWxsO1xuICAgIH1cbiAgICBlbHNlIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignXCInICsgcmVsYXRpdmVTb3VyY2UgKyAnXCIgaXMgbm90IGluIHRoZSBTb3VyY2VNYXAuJyk7XG4gICAgfVxuICB9O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIGdlbmVyYXRlZCBsaW5lIGFuZCBjb2x1bW4gaW5mb3JtYXRpb24gZm9yIHRoZSBvcmlnaW5hbCBzb3VyY2UsXG4gKiBsaW5lLCBhbmQgY29sdW1uIHBvc2l0aW9ucyBwcm92aWRlZC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgYW4gb2JqZWN0IHdpdGhcbiAqIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gc291cmNlOiBUaGUgZmlsZW5hbWUgb2YgdGhlIG9yaWdpbmFsIHNvdXJjZS5cbiAqICAgLSBsaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZS4gIFRoZSBsaW5lIG51bWJlclxuICogICAgIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLiAgVGhlIGNvbHVtblxuICogICAgIG51bWJlciBpcyAwLWJhc2VkLlxuICogICAtIGJpYXM6IEVpdGhlciAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnIG9yXG4gKiAgICAgJ1NvdXJjZU1hcENvbnN1bWVyLkxFQVNUX1VQUEVSX0JPVU5EJy4gU3BlY2lmaWVzIHdoZXRoZXIgdG8gcmV0dXJuIHRoZVxuICogICAgIGNsb3Nlc3QgZWxlbWVudCB0aGF0IGlzIHNtYWxsZXIgdGhhbiBvciBncmVhdGVyIHRoYW4gdGhlIG9uZSB3ZSBhcmVcbiAqICAgICBzZWFyY2hpbmcgZm9yLCByZXNwZWN0aXZlbHksIGlmIHRoZSBleGFjdCBlbGVtZW50IGNhbm5vdCBiZSBmb3VuZC5cbiAqICAgICBEZWZhdWx0cyB0byAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZSwgb3IgbnVsbC4gIFRoZVxuICogICAgIGxpbmUgbnVtYmVyIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZSwgb3IgbnVsbC5cbiAqICAgICBUaGUgY29sdW1uIG51bWJlciBpcyAwLWJhc2VkLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5nZW5lcmF0ZWRQb3NpdGlvbkZvciA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2dlbmVyYXRlZFBvc2l0aW9uRm9yKGFBcmdzKSB7XG4gICAgdmFyIHNvdXJjZSA9IHV0aWwuZ2V0QXJnKGFBcmdzLCAnc291cmNlJyk7XG4gICAgc291cmNlID0gdGhpcy5fZmluZFNvdXJjZUluZGV4KHNvdXJjZSk7XG4gICAgaWYgKHNvdXJjZSA8IDApIHtcbiAgICAgIHJldHVybiB7XG4gICAgICAgIGxpbmU6IG51bGwsXG4gICAgICAgIGNvbHVtbjogbnVsbCxcbiAgICAgICAgbGFzdENvbHVtbjogbnVsbFxuICAgICAgfTtcbiAgICB9XG5cbiAgICB2YXIgbmVlZGxlID0ge1xuICAgICAgc291cmNlOiBzb3VyY2UsXG4gICAgICBvcmlnaW5hbExpbmU6IHV0aWwuZ2V0QXJnKGFBcmdzLCAnbGluZScpLFxuICAgICAgb3JpZ2luYWxDb2x1bW46IHV0aWwuZ2V0QXJnKGFBcmdzLCAnY29sdW1uJylcbiAgICB9O1xuXG4gICAgdmFyIGluZGV4ID0gdGhpcy5fZmluZE1hcHBpbmcoXG4gICAgICBuZWVkbGUsXG4gICAgICB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzLFxuICAgICAgXCJvcmlnaW5hbExpbmVcIixcbiAgICAgIFwib3JpZ2luYWxDb2x1bW5cIixcbiAgICAgIHV0aWwuY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnMsXG4gICAgICB1dGlsLmdldEFyZyhhQXJncywgJ2JpYXMnLCBTb3VyY2VNYXBDb25zdW1lci5HUkVBVEVTVF9MT1dFUl9CT1VORClcbiAgICApO1xuXG4gICAgaWYgKGluZGV4ID49IDApIHtcbiAgICAgIHZhciBtYXBwaW5nID0gdGhpcy5fb3JpZ2luYWxNYXBwaW5nc1tpbmRleF07XG5cbiAgICAgIGlmIChtYXBwaW5nLnNvdXJjZSA9PT0gbmVlZGxlLnNvdXJjZSkge1xuICAgICAgICByZXR1cm4ge1xuICAgICAgICAgIGxpbmU6IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdnZW5lcmF0ZWRMaW5lJywgbnVsbCksXG4gICAgICAgICAgY29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkQ29sdW1uJywgbnVsbCksXG4gICAgICAgICAgbGFzdENvbHVtbjogdXRpbC5nZXRBcmcobWFwcGluZywgJ2xhc3RHZW5lcmF0ZWRDb2x1bW4nLCBudWxsKVxuICAgICAgICB9O1xuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiB7XG4gICAgICBsaW5lOiBudWxsLFxuICAgICAgY29sdW1uOiBudWxsLFxuICAgICAgbGFzdENvbHVtbjogbnVsbFxuICAgIH07XG4gIH07XG5cbmV4cG9ydHMuQmFzaWNTb3VyY2VNYXBDb25zdW1lciA9IEJhc2ljU291cmNlTWFwQ29uc3VtZXI7XG5cbi8qKlxuICogQW4gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyIGluc3RhbmNlIHJlcHJlc2VudHMgYSBwYXJzZWQgc291cmNlIG1hcCB3aGljaFxuICogd2UgY2FuIHF1ZXJ5IGZvciBpbmZvcm1hdGlvbi4gSXQgZGlmZmVycyBmcm9tIEJhc2ljU291cmNlTWFwQ29uc3VtZXIgaW5cbiAqIHRoYXQgaXQgdGFrZXMgXCJpbmRleGVkXCIgc291cmNlIG1hcHMgKGkuZS4gb25lcyB3aXRoIGEgXCJzZWN0aW9uc1wiIGZpZWxkKSBhc1xuICogaW5wdXQuXG4gKlxuICogVGhlIGZpcnN0IHBhcmFtZXRlciBpcyBhIHJhdyBzb3VyY2UgbWFwIChlaXRoZXIgYXMgYSBKU09OIHN0cmluZywgb3IgYWxyZWFkeVxuICogcGFyc2VkIHRvIGFuIG9iamVjdCkuIEFjY29yZGluZyB0byB0aGUgc3BlYyBmb3IgaW5kZXhlZCBzb3VyY2UgbWFwcywgdGhleVxuICogaGF2ZSB0aGUgZm9sbG93aW5nIGF0dHJpYnV0ZXM6XG4gKlxuICogICAtIHZlcnNpb246IFdoaWNoIHZlcnNpb24gb2YgdGhlIHNvdXJjZSBtYXAgc3BlYyB0aGlzIG1hcCBpcyBmb2xsb3dpbmcuXG4gKiAgIC0gZmlsZTogT3B0aW9uYWwuIFRoZSBnZW5lcmF0ZWQgZmlsZSB0aGlzIHNvdXJjZSBtYXAgaXMgYXNzb2NpYXRlZCB3aXRoLlxuICogICAtIHNlY3Rpb25zOiBBIGxpc3Qgb2Ygc2VjdGlvbiBkZWZpbml0aW9ucy5cbiAqXG4gKiBFYWNoIHZhbHVlIHVuZGVyIHRoZSBcInNlY3Rpb25zXCIgZmllbGQgaGFzIHR3byBmaWVsZHM6XG4gKiAgIC0gb2Zmc2V0OiBUaGUgb2Zmc2V0IGludG8gdGhlIG9yaWdpbmFsIHNwZWNpZmllZCBhdCB3aGljaCB0aGlzIHNlY3Rpb25cbiAqICAgICAgIGJlZ2lucyB0byBhcHBseSwgZGVmaW5lZCBhcyBhbiBvYmplY3Qgd2l0aCBhIFwibGluZVwiIGFuZCBcImNvbHVtblwiXG4gKiAgICAgICBmaWVsZC5cbiAqICAgLSBtYXA6IEEgc291cmNlIG1hcCBkZWZpbml0aW9uLiBUaGlzIHNvdXJjZSBtYXAgY291bGQgYWxzbyBiZSBpbmRleGVkLFxuICogICAgICAgYnV0IGRvZXNuJ3QgaGF2ZSB0byBiZS5cbiAqXG4gKiBJbnN0ZWFkIG9mIHRoZSBcIm1hcFwiIGZpZWxkLCBpdCdzIGFsc28gcG9zc2libGUgdG8gaGF2ZSBhIFwidXJsXCIgZmllbGRcbiAqIHNwZWNpZnlpbmcgYSBVUkwgdG8gcmV0cmlldmUgYSBzb3VyY2UgbWFwIGZyb20sIGJ1dCB0aGF0J3MgY3VycmVudGx5XG4gKiB1bnN1cHBvcnRlZC5cbiAqXG4gKiBIZXJlJ3MgYW4gZXhhbXBsZSBzb3VyY2UgbWFwLCB0YWtlbiBmcm9tIHRoZSBzb3VyY2UgbWFwIHNwZWNbMF0sIGJ1dFxuICogbW9kaWZpZWQgdG8gb21pdCBhIHNlY3Rpb24gd2hpY2ggdXNlcyB0aGUgXCJ1cmxcIiBmaWVsZC5cbiAqXG4gKiAge1xuICogICAgdmVyc2lvbiA6IDMsXG4gKiAgICBmaWxlOiBcImFwcC5qc1wiLFxuICogICAgc2VjdGlvbnM6IFt7XG4gKiAgICAgIG9mZnNldDoge2xpbmU6MTAwLCBjb2x1bW46MTB9LFxuICogICAgICBtYXA6IHtcbiAqICAgICAgICB2ZXJzaW9uIDogMyxcbiAqICAgICAgICBmaWxlOiBcInNlY3Rpb24uanNcIixcbiAqICAgICAgICBzb3VyY2VzOiBbXCJmb28uanNcIiwgXCJiYXIuanNcIl0sXG4gKiAgICAgICAgbmFtZXM6IFtcInNyY1wiLCBcIm1hcHNcIiwgXCJhcmVcIiwgXCJmdW5cIl0sXG4gKiAgICAgICAgbWFwcGluZ3M6IFwiQUFBQSxFOztBQkNERTtcIlxuICogICAgICB9XG4gKiAgICB9XSxcbiAqICB9XG4gKlxuICogVGhlIHNlY29uZCBwYXJhbWV0ZXIsIGlmIGdpdmVuLCBpcyBhIHN0cmluZyB3aG9zZSB2YWx1ZSBpcyB0aGUgVVJMXG4gKiBhdCB3aGljaCB0aGUgc291cmNlIG1hcCB3YXMgZm91bmQuICBUaGlzIFVSTCBpcyB1c2VkIHRvIGNvbXB1dGUgdGhlXG4gKiBzb3VyY2VzIGFycmF5LlxuICpcbiAqIFswXTogaHR0cHM6Ly9kb2NzLmdvb2dsZS5jb20vZG9jdW1lbnQvZC8xVTFSR0FlaFF3UnlwVVRvdkYxS1JscGlPRnplMGItXzJnYzZmQUgwS1kway9lZGl0I2hlYWRpbmc9aC41MzVlczN4ZXByZ3RcbiAqL1xuZnVuY3Rpb24gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgdmFyIHNvdXJjZU1hcCA9IGFTb3VyY2VNYXA7XG4gIGlmICh0eXBlb2YgYVNvdXJjZU1hcCA9PT0gJ3N0cmluZycpIHtcbiAgICBzb3VyY2VNYXAgPSB1dGlsLnBhcnNlU291cmNlTWFwSW5wdXQoYVNvdXJjZU1hcCk7XG4gIH1cblxuICB2YXIgdmVyc2lvbiA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ3ZlcnNpb24nKTtcbiAgdmFyIHNlY3Rpb25zID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAnc2VjdGlvbnMnKTtcblxuICBpZiAodmVyc2lvbiAhPSB0aGlzLl92ZXJzaW9uKSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKCdVbnN1cHBvcnRlZCB2ZXJzaW9uOiAnICsgdmVyc2lvbik7XG4gIH1cblxuICB0aGlzLl9zb3VyY2VzID0gbmV3IEFycmF5U2V0KCk7XG4gIHRoaXMuX25hbWVzID0gbmV3IEFycmF5U2V0KCk7XG5cbiAgdmFyIGxhc3RPZmZzZXQgPSB7XG4gICAgbGluZTogLTEsXG4gICAgY29sdW1uOiAwXG4gIH07XG4gIHRoaXMuX3NlY3Rpb25zID0gc2VjdGlvbnMubWFwKGZ1bmN0aW9uIChzKSB7XG4gICAgaWYgKHMudXJsKSB7XG4gICAgICAvLyBUaGUgdXJsIGZpZWxkIHdpbGwgcmVxdWlyZSBzdXBwb3J0IGZvciBhc3luY2hyb25pY2l0eS5cbiAgICAgIC8vIFNlZSBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL2lzc3Vlcy8xNlxuICAgICAgdGhyb3cgbmV3IEVycm9yKCdTdXBwb3J0IGZvciB1cmwgZmllbGQgaW4gc2VjdGlvbnMgbm90IGltcGxlbWVudGVkLicpO1xuICAgIH1cbiAgICB2YXIgb2Zmc2V0ID0gdXRpbC5nZXRBcmcocywgJ29mZnNldCcpO1xuICAgIHZhciBvZmZzZXRMaW5lID0gdXRpbC5nZXRBcmcob2Zmc2V0LCAnbGluZScpO1xuICAgIHZhciBvZmZzZXRDb2x1bW4gPSB1dGlsLmdldEFyZyhvZmZzZXQsICdjb2x1bW4nKTtcblxuICAgIGlmIChvZmZzZXRMaW5lIDwgbGFzdE9mZnNldC5saW5lIHx8XG4gICAgICAgIChvZmZzZXRMaW5lID09PSBsYXN0T2Zmc2V0LmxpbmUgJiYgb2Zmc2V0Q29sdW1uIDwgbGFzdE9mZnNldC5jb2x1bW4pKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ1NlY3Rpb24gb2Zmc2V0cyBtdXN0IGJlIG9yZGVyZWQgYW5kIG5vbi1vdmVybGFwcGluZy4nKTtcbiAgICB9XG4gICAgbGFzdE9mZnNldCA9IG9mZnNldDtcblxuICAgIHJldHVybiB7XG4gICAgICBnZW5lcmF0ZWRPZmZzZXQ6IHtcbiAgICAgICAgLy8gVGhlIG9mZnNldCBmaWVsZHMgYXJlIDAtYmFzZWQsIGJ1dCB3ZSB1c2UgMS1iYXNlZCBpbmRpY2VzIHdoZW5cbiAgICAgICAgLy8gZW5jb2RpbmcvZGVjb2RpbmcgZnJvbSBWTFEuXG4gICAgICAgIGdlbmVyYXRlZExpbmU6IG9mZnNldExpbmUgKyAxLFxuICAgICAgICBnZW5lcmF0ZWRDb2x1bW46IG9mZnNldENvbHVtbiArIDFcbiAgICAgIH0sXG4gICAgICBjb25zdW1lcjogbmV3IFNvdXJjZU1hcENvbnN1bWVyKHV0aWwuZ2V0QXJnKHMsICdtYXAnKSwgYVNvdXJjZU1hcFVSTClcbiAgICB9XG4gIH0pO1xufVxuXG5JbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlID0gT2JqZWN0LmNyZWF0ZShTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUpO1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5jb25zdHJ1Y3RvciA9IFNvdXJjZU1hcENvbnN1bWVyO1xuXG4vKipcbiAqIFRoZSB2ZXJzaW9uIG9mIHRoZSBzb3VyY2UgbWFwcGluZyBzcGVjIHRoYXQgd2UgYXJlIGNvbnN1bWluZy5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8qKlxuICogVGhlIGxpc3Qgb2Ygb3JpZ2luYWwgc291cmNlcy5cbiAqL1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUsICdzb3VyY2VzJywge1xuICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICB2YXIgc291cmNlcyA9IFtdO1xuICAgIGZvciAodmFyIGkgPSAwOyBpIDwgdGhpcy5fc2VjdGlvbnMubGVuZ3RoOyBpKyspIHtcbiAgICAgIGZvciAodmFyIGogPSAwOyBqIDwgdGhpcy5fc2VjdGlvbnNbaV0uY29uc3VtZXIuc291cmNlcy5sZW5ndGg7IGorKykge1xuICAgICAgICBzb3VyY2VzLnB1c2godGhpcy5fc2VjdGlvbnNbaV0uY29uc3VtZXIuc291cmNlc1tqXSk7XG4gICAgICB9XG4gICAgfVxuICAgIHJldHVybiBzb3VyY2VzO1xuICB9XG59KTtcblxuLyoqXG4gKiBSZXR1cm5zIHRoZSBvcmlnaW5hbCBzb3VyY2UsIGxpbmUsIGFuZCBjb2x1bW4gaW5mb3JtYXRpb24gZm9yIHRoZSBnZW5lcmF0ZWRcbiAqIHNvdXJjZSdzIGxpbmUgYW5kIGNvbHVtbiBwb3NpdGlvbnMgcHJvdmlkZWQuIFRoZSBvbmx5IGFyZ3VtZW50IGlzIGFuIG9iamVjdFxuICogd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZS4gIFRoZSBsaW5lIG51bWJlclxuICogICAgIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZS4gIFRoZSBjb2x1bW5cbiAqICAgICBudW1iZXIgaXMgMC1iYXNlZC5cbiAqXG4gKiBhbmQgYW4gb2JqZWN0IGlzIHJldHVybmVkIHdpdGggdGhlIGZvbGxvd2luZyBwcm9wZXJ0aWVzOlxuICpcbiAqICAgLSBzb3VyY2U6IFRoZSBvcmlnaW5hbCBzb3VyY2UgZmlsZSwgb3IgbnVsbC5cbiAqICAgLSBsaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZSwgb3IgbnVsbC4gIFRoZVxuICogICAgIGxpbmUgbnVtYmVyIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLCBvciBudWxsLiAgVGhlXG4gKiAgICAgY29sdW1uIG51bWJlciBpcyAwLWJhc2VkLlxuICogICAtIG5hbWU6IFRoZSBvcmlnaW5hbCBpZGVudGlmaWVyLCBvciBudWxsLlxuICovXG5JbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLm9yaWdpbmFsUG9zaXRpb25Gb3IgPVxuICBmdW5jdGlvbiBJbmRleGVkU291cmNlTWFwQ29uc3VtZXJfb3JpZ2luYWxQb3NpdGlvbkZvcihhQXJncykge1xuICAgIHZhciBuZWVkbGUgPSB7XG4gICAgICBnZW5lcmF0ZWRMaW5lOiB1dGlsLmdldEFyZyhhQXJncywgJ2xpbmUnKSxcbiAgICAgIGdlbmVyYXRlZENvbHVtbjogdXRpbC5nZXRBcmcoYUFyZ3MsICdjb2x1bW4nKVxuICAgIH07XG5cbiAgICAvLyBGaW5kIHRoZSBzZWN0aW9uIGNvbnRhaW5pbmcgdGhlIGdlbmVyYXRlZCBwb3NpdGlvbiB3ZSdyZSB0cnlpbmcgdG8gbWFwXG4gICAgLy8gdG8gYW4gb3JpZ2luYWwgcG9zaXRpb24uXG4gICAgdmFyIHNlY3Rpb25JbmRleCA9IGJpbmFyeVNlYXJjaC5zZWFyY2gobmVlZGxlLCB0aGlzLl9zZWN0aW9ucyxcbiAgICAgIGZ1bmN0aW9uKG5lZWRsZSwgc2VjdGlvbikge1xuICAgICAgICB2YXIgY21wID0gbmVlZGxlLmdlbmVyYXRlZExpbmUgLSBzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lO1xuICAgICAgICBpZiAoY21wKSB7XG4gICAgICAgICAgcmV0dXJuIGNtcDtcbiAgICAgICAgfVxuXG4gICAgICAgIHJldHVybiAobmVlZGxlLmdlbmVyYXRlZENvbHVtbiAtXG4gICAgICAgICAgICAgICAgc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkQ29sdW1uKTtcbiAgICAgIH0pO1xuICAgIHZhciBzZWN0aW9uID0gdGhpcy5fc2VjdGlvbnNbc2VjdGlvbkluZGV4XTtcblxuICAgIGlmICghc2VjdGlvbikge1xuICAgICAgcmV0dXJuIHtcbiAgICAgICAgc291cmNlOiBudWxsLFxuICAgICAgICBsaW5lOiBudWxsLFxuICAgICAgICBjb2x1bW46IG51bGwsXG4gICAgICAgIG5hbWU6IG51bGxcbiAgICAgIH07XG4gICAgfVxuXG4gICAgcmV0dXJuIHNlY3Rpb24uY29uc3VtZXIub3JpZ2luYWxQb3NpdGlvbkZvcih7XG4gICAgICBsaW5lOiBuZWVkbGUuZ2VuZXJhdGVkTGluZSAtXG4gICAgICAgIChzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lIC0gMSksXG4gICAgICBjb2x1bW46IG5lZWRsZS5nZW5lcmF0ZWRDb2x1bW4gLVxuICAgICAgICAoc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkTGluZSA9PT0gbmVlZGxlLmdlbmVyYXRlZExpbmVcbiAgICAgICAgID8gc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkQ29sdW1uIC0gMVxuICAgICAgICAgOiAwKSxcbiAgICAgIGJpYXM6IGFBcmdzLmJpYXNcbiAgICB9KTtcbiAgfTtcblxuLyoqXG4gKiBSZXR1cm4gdHJ1ZSBpZiB3ZSBoYXZlIHRoZSBzb3VyY2UgY29udGVudCBmb3IgZXZlcnkgc291cmNlIGluIHRoZSBzb3VyY2VcbiAqIG1hcCwgZmFsc2Ugb3RoZXJ3aXNlLlxuICovXG5JbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmhhc0NvbnRlbnRzT2ZBbGxTb3VyY2VzID1cbiAgZnVuY3Rpb24gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyX2hhc0NvbnRlbnRzT2ZBbGxTb3VyY2VzKCkge1xuICAgIHJldHVybiB0aGlzLl9zZWN0aW9ucy5ldmVyeShmdW5jdGlvbiAocykge1xuICAgICAgcmV0dXJuIHMuY29uc3VtZXIuaGFzQ29udGVudHNPZkFsbFNvdXJjZXMoKTtcbiAgICB9KTtcbiAgfTtcblxuLyoqXG4gKiBSZXR1cm5zIHRoZSBvcmlnaW5hbCBzb3VyY2UgY29udGVudC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgdGhlIHVybCBvZiB0aGVcbiAqIG9yaWdpbmFsIHNvdXJjZSBmaWxlLiBSZXR1cm5zIG51bGwgaWYgbm8gb3JpZ2luYWwgc291cmNlIGNvbnRlbnQgaXNcbiAqIGF2YWlsYWJsZS5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5zb3VyY2VDb250ZW50Rm9yID1cbiAgZnVuY3Rpb24gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyX3NvdXJjZUNvbnRlbnRGb3IoYVNvdXJjZSwgbnVsbE9uTWlzc2luZykge1xuICAgIGZvciAodmFyIGkgPSAwOyBpIDwgdGhpcy5fc2VjdGlvbnMubGVuZ3RoOyBpKyspIHtcbiAgICAgIHZhciBzZWN0aW9uID0gdGhpcy5fc2VjdGlvbnNbaV07XG5cbiAgICAgIHZhciBjb250ZW50ID0gc2VjdGlvbi5jb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKGFTb3VyY2UsIHRydWUpO1xuICAgICAgaWYgKGNvbnRlbnQpIHtcbiAgICAgICAgcmV0dXJuIGNvbnRlbnQ7XG4gICAgICB9XG4gICAgfVxuICAgIGlmIChudWxsT25NaXNzaW5nKSB7XG4gICAgICByZXR1cm4gbnVsbDtcbiAgICB9XG4gICAgZWxzZSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ1wiJyArIGFTb3VyY2UgKyAnXCIgaXMgbm90IGluIHRoZSBTb3VyY2VNYXAuJyk7XG4gICAgfVxuICB9O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIGdlbmVyYXRlZCBsaW5lIGFuZCBjb2x1bW4gaW5mb3JtYXRpb24gZm9yIHRoZSBvcmlnaW5hbCBzb3VyY2UsXG4gKiBsaW5lLCBhbmQgY29sdW1uIHBvc2l0aW9ucyBwcm92aWRlZC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgYW4gb2JqZWN0IHdpdGhcbiAqIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gc291cmNlOiBUaGUgZmlsZW5hbWUgb2YgdGhlIG9yaWdpbmFsIHNvdXJjZS5cbiAqICAgLSBsaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZS4gIFRoZSBsaW5lIG51bWJlclxuICogICAgIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLiAgVGhlIGNvbHVtblxuICogICAgIG51bWJlciBpcyAwLWJhc2VkLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZSwgb3IgbnVsbC4gIFRoZVxuICogICAgIGxpbmUgbnVtYmVyIGlzIDEtYmFzZWQuIFxuICogICAtIGNvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIGdlbmVyYXRlZCBzb3VyY2UsIG9yIG51bGwuXG4gKiAgICAgVGhlIGNvbHVtbiBudW1iZXIgaXMgMC1iYXNlZC5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5nZW5lcmF0ZWRQb3NpdGlvbkZvciA9XG4gIGZ1bmN0aW9uIEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lcl9nZW5lcmF0ZWRQb3NpdGlvbkZvcihhQXJncykge1xuICAgIGZvciAodmFyIGkgPSAwOyBpIDwgdGhpcy5fc2VjdGlvbnMubGVuZ3RoOyBpKyspIHtcbiAgICAgIHZhciBzZWN0aW9uID0gdGhpcy5fc2VjdGlvbnNbaV07XG5cbiAgICAgIC8vIE9ubHkgY29uc2lkZXIgdGhpcyBzZWN0aW9uIGlmIHRoZSByZXF1ZXN0ZWQgc291cmNlIGlzIGluIHRoZSBsaXN0IG9mXG4gICAgICAvLyBzb3VyY2VzIG9mIHRoZSBjb25zdW1lci5cbiAgICAgIGlmIChzZWN0aW9uLmNvbnN1bWVyLl9maW5kU291cmNlSW5kZXgodXRpbC5nZXRBcmcoYUFyZ3MsICdzb3VyY2UnKSkgPT09IC0xKSB7XG4gICAgICAgIGNvbnRpbnVlO1xuICAgICAgfVxuICAgICAgdmFyIGdlbmVyYXRlZFBvc2l0aW9uID0gc2VjdGlvbi5jb25zdW1lci5nZW5lcmF0ZWRQb3NpdGlvbkZvcihhQXJncyk7XG4gICAgICBpZiAoZ2VuZXJhdGVkUG9zaXRpb24pIHtcbiAgICAgICAgdmFyIHJldCA9IHtcbiAgICAgICAgICBsaW5lOiBnZW5lcmF0ZWRQb3NpdGlvbi5saW5lICtcbiAgICAgICAgICAgIChzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lIC0gMSksXG4gICAgICAgICAgY29sdW1uOiBnZW5lcmF0ZWRQb3NpdGlvbi5jb2x1bW4gK1xuICAgICAgICAgICAgKHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZExpbmUgPT09IGdlbmVyYXRlZFBvc2l0aW9uLmxpbmVcbiAgICAgICAgICAgICA/IHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZENvbHVtbiAtIDFcbiAgICAgICAgICAgICA6IDApXG4gICAgICAgIH07XG4gICAgICAgIHJldHVybiByZXQ7XG4gICAgICB9XG4gICAgfVxuXG4gICAgcmV0dXJuIHtcbiAgICAgIGxpbmU6IG51bGwsXG4gICAgICBjb2x1bW46IG51bGxcbiAgICB9O1xuICB9O1xuXG4vKipcbiAqIFBhcnNlIHRoZSBtYXBwaW5ncyBpbiBhIHN0cmluZyBpbiB0byBhIGRhdGEgc3RydWN0dXJlIHdoaWNoIHdlIGNhbiBlYXNpbHlcbiAqIHF1ZXJ5ICh0aGUgb3JkZXJlZCBhcnJheXMgaW4gdGhlIGB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3NgIGFuZFxuICogYHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzYCBwcm9wZXJ0aWVzKS5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fcGFyc2VNYXBwaW5ncyA9XG4gIGZ1bmN0aW9uIEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lcl9wYXJzZU1hcHBpbmdzKGFTdHIsIGFTb3VyY2VSb290KSB7XG4gICAgdGhpcy5fX2dlbmVyYXRlZE1hcHBpbmdzID0gW107XG4gICAgdGhpcy5fX29yaWdpbmFsTWFwcGluZ3MgPSBbXTtcbiAgICBmb3IgKHZhciBpID0gMDsgaSA8IHRoaXMuX3NlY3Rpb25zLmxlbmd0aDsgaSsrKSB7XG4gICAgICB2YXIgc2VjdGlvbiA9IHRoaXMuX3NlY3Rpb25zW2ldO1xuICAgICAgdmFyIHNlY3Rpb25NYXBwaW5ncyA9IHNlY3Rpb24uY29uc3VtZXIuX2dlbmVyYXRlZE1hcHBpbmdzO1xuICAgICAgZm9yICh2YXIgaiA9IDA7IGogPCBzZWN0aW9uTWFwcGluZ3MubGVuZ3RoOyBqKyspIHtcbiAgICAgICAgdmFyIG1hcHBpbmcgPSBzZWN0aW9uTWFwcGluZ3Nbal07XG5cbiAgICAgICAgdmFyIHNvdXJjZSA9IHNlY3Rpb24uY29uc3VtZXIuX3NvdXJjZXMuYXQobWFwcGluZy5zb3VyY2UpO1xuICAgICAgICBzb3VyY2UgPSB1dGlsLmNvbXB1dGVTb3VyY2VVUkwoc2VjdGlvbi5jb25zdW1lci5zb3VyY2VSb290LCBzb3VyY2UsIHRoaXMuX3NvdXJjZU1hcFVSTCk7XG4gICAgICAgIHRoaXMuX3NvdXJjZXMuYWRkKHNvdXJjZSk7XG4gICAgICAgIHNvdXJjZSA9IHRoaXMuX3NvdXJjZXMuaW5kZXhPZihzb3VyY2UpO1xuXG4gICAgICAgIHZhciBuYW1lID0gbnVsbDtcbiAgICAgICAgaWYgKG1hcHBpbmcubmFtZSkge1xuICAgICAgICAgIG5hbWUgPSBzZWN0aW9uLmNvbnN1bWVyLl9uYW1lcy5hdChtYXBwaW5nLm5hbWUpO1xuICAgICAgICAgIHRoaXMuX25hbWVzLmFkZChuYW1lKTtcbiAgICAgICAgICBuYW1lID0gdGhpcy5fbmFtZXMuaW5kZXhPZihuYW1lKTtcbiAgICAgICAgfVxuXG4gICAgICAgIC8vIFRoZSBtYXBwaW5ncyBjb21pbmcgZnJvbSB0aGUgY29uc3VtZXIgZm9yIHRoZSBzZWN0aW9uIGhhdmVcbiAgICAgICAgLy8gZ2VuZXJhdGVkIHBvc2l0aW9ucyByZWxhdGl2ZSB0byB0aGUgc3RhcnQgb2YgdGhlIHNlY3Rpb24sIHNvIHdlXG4gICAgICAgIC8vIG5lZWQgdG8gb2Zmc2V0IHRoZW0gdG8gYmUgcmVsYXRpdmUgdG8gdGhlIHN0YXJ0IG9mIHRoZSBjb25jYXRlbmF0ZWRcbiAgICAgICAgLy8gZ2VuZXJhdGVkIGZpbGUuXG4gICAgICAgIHZhciBhZGp1c3RlZE1hcHBpbmcgPSB7XG4gICAgICAgICAgc291cmNlOiBzb3VyY2UsXG4gICAgICAgICAgZ2VuZXJhdGVkTGluZTogbWFwcGluZy5nZW5lcmF0ZWRMaW5lICtcbiAgICAgICAgICAgIChzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lIC0gMSksXG4gICAgICAgICAgZ2VuZXJhdGVkQ29sdW1uOiBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbiArXG4gICAgICAgICAgICAoc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkTGluZSA9PT0gbWFwcGluZy5nZW5lcmF0ZWRMaW5lXG4gICAgICAgICAgICA/IHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZENvbHVtbiAtIDFcbiAgICAgICAgICAgIDogMCksXG4gICAgICAgICAgb3JpZ2luYWxMaW5lOiBtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICBvcmlnaW5hbENvbHVtbjogbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICBuYW1lOiBuYW1lXG4gICAgICAgIH07XG5cbiAgICAgICAgdGhpcy5fX2dlbmVyYXRlZE1hcHBpbmdzLnB1c2goYWRqdXN0ZWRNYXBwaW5nKTtcbiAgICAgICAgaWYgKHR5cGVvZiBhZGp1c3RlZE1hcHBpbmcub3JpZ2luYWxMaW5lID09PSAnbnVtYmVyJykge1xuICAgICAgICAgIHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzLnB1c2goYWRqdXN0ZWRNYXBwaW5nKTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cblxuICAgIHF1aWNrU29ydCh0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3MsIHV0aWwuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zRGVmbGF0ZWQpO1xuICAgIHF1aWNrU29ydCh0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncywgdXRpbC5jb21wYXJlQnlPcmlnaW5hbFBvc2l0aW9ucyk7XG4gIH07XG5cbmV4cG9ydHMuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyID0gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW1hcC1jb25zdW1lci5qc1xuLy8gbW9kdWxlIGlkID0gN1xuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbmV4cG9ydHMuR1JFQVRFU1RfTE9XRVJfQk9VTkQgPSAxO1xuZXhwb3J0cy5MRUFTVF9VUFBFUl9CT1VORCA9IDI7XG5cbi8qKlxuICogUmVjdXJzaXZlIGltcGxlbWVudGF0aW9uIG9mIGJpbmFyeSBzZWFyY2guXG4gKlxuICogQHBhcmFtIGFMb3cgSW5kaWNlcyBoZXJlIGFuZCBsb3dlciBkbyBub3QgY29udGFpbiB0aGUgbmVlZGxlLlxuICogQHBhcmFtIGFIaWdoIEluZGljZXMgaGVyZSBhbmQgaGlnaGVyIGRvIG5vdCBjb250YWluIHRoZSBuZWVkbGUuXG4gKiBAcGFyYW0gYU5lZWRsZSBUaGUgZWxlbWVudCBiZWluZyBzZWFyY2hlZCBmb3IuXG4gKiBAcGFyYW0gYUhheXN0YWNrIFRoZSBub24tZW1wdHkgYXJyYXkgYmVpbmcgc2VhcmNoZWQuXG4gKiBAcGFyYW0gYUNvbXBhcmUgRnVuY3Rpb24gd2hpY2ggdGFrZXMgdHdvIGVsZW1lbnRzIGFuZCByZXR1cm5zIC0xLCAwLCBvciAxLlxuICogQHBhcmFtIGFCaWFzIEVpdGhlciAnYmluYXJ5U2VhcmNoLkdSRUFURVNUX0xPV0VSX0JPVU5EJyBvclxuICogICAgICdiaW5hcnlTZWFyY2guTEVBU1RfVVBQRVJfQk9VTkQnLiBTcGVjaWZpZXMgd2hldGhlciB0byByZXR1cm4gdGhlXG4gKiAgICAgY2xvc2VzdCBlbGVtZW50IHRoYXQgaXMgc21hbGxlciB0aGFuIG9yIGdyZWF0ZXIgdGhhbiB0aGUgb25lIHdlIGFyZVxuICogICAgIHNlYXJjaGluZyBmb3IsIHJlc3BlY3RpdmVseSwgaWYgdGhlIGV4YWN0IGVsZW1lbnQgY2Fubm90IGJlIGZvdW5kLlxuICovXG5mdW5jdGlvbiByZWN1cnNpdmVTZWFyY2goYUxvdywgYUhpZ2gsIGFOZWVkbGUsIGFIYXlzdGFjaywgYUNvbXBhcmUsIGFCaWFzKSB7XG4gIC8vIFRoaXMgZnVuY3Rpb24gdGVybWluYXRlcyB3aGVuIG9uZSBvZiB0aGUgZm9sbG93aW5nIGlzIHRydWU6XG4gIC8vXG4gIC8vICAgMS4gV2UgZmluZCB0aGUgZXhhY3QgZWxlbWVudCB3ZSBhcmUgbG9va2luZyBmb3IuXG4gIC8vXG4gIC8vICAgMi4gV2UgZGlkIG5vdCBmaW5kIHRoZSBleGFjdCBlbGVtZW50LCBidXQgd2UgY2FuIHJldHVybiB0aGUgaW5kZXggb2ZcbiAgLy8gICAgICB0aGUgbmV4dC1jbG9zZXN0IGVsZW1lbnQuXG4gIC8vXG4gIC8vICAgMy4gV2UgZGlkIG5vdCBmaW5kIHRoZSBleGFjdCBlbGVtZW50LCBhbmQgdGhlcmUgaXMgbm8gbmV4dC1jbG9zZXN0XG4gIC8vICAgICAgZWxlbWVudCB0aGFuIHRoZSBvbmUgd2UgYXJlIHNlYXJjaGluZyBmb3IsIHNvIHdlIHJldHVybiAtMS5cbiAgdmFyIG1pZCA9IE1hdGguZmxvb3IoKGFIaWdoIC0gYUxvdykgLyAyKSArIGFMb3c7XG4gIHZhciBjbXAgPSBhQ29tcGFyZShhTmVlZGxlLCBhSGF5c3RhY2tbbWlkXSwgdHJ1ZSk7XG4gIGlmIChjbXAgPT09IDApIHtcbiAgICAvLyBGb3VuZCB0aGUgZWxlbWVudCB3ZSBhcmUgbG9va2luZyBmb3IuXG4gICAgcmV0dXJuIG1pZDtcbiAgfVxuICBlbHNlIGlmIChjbXAgPiAwKSB7XG4gICAgLy8gT3VyIG5lZWRsZSBpcyBncmVhdGVyIHRoYW4gYUhheXN0YWNrW21pZF0uXG4gICAgaWYgKGFIaWdoIC0gbWlkID4gMSkge1xuICAgICAgLy8gVGhlIGVsZW1lbnQgaXMgaW4gdGhlIHVwcGVyIGhhbGYuXG4gICAgICByZXR1cm4gcmVjdXJzaXZlU2VhcmNoKG1pZCwgYUhpZ2gsIGFOZWVkbGUsIGFIYXlzdGFjaywgYUNvbXBhcmUsIGFCaWFzKTtcbiAgICB9XG5cbiAgICAvLyBUaGUgZXhhY3QgbmVlZGxlIGVsZW1lbnQgd2FzIG5vdCBmb3VuZCBpbiB0aGlzIGhheXN0YWNrLiBEZXRlcm1pbmUgaWZcbiAgICAvLyB3ZSBhcmUgaW4gdGVybWluYXRpb24gY2FzZSAoMykgb3IgKDIpIGFuZCByZXR1cm4gdGhlIGFwcHJvcHJpYXRlIHRoaW5nLlxuICAgIGlmIChhQmlhcyA9PSBleHBvcnRzLkxFQVNUX1VQUEVSX0JPVU5EKSB7XG4gICAgICByZXR1cm4gYUhpZ2ggPCBhSGF5c3RhY2subGVuZ3RoID8gYUhpZ2ggOiAtMTtcbiAgICB9IGVsc2Uge1xuICAgICAgcmV0dXJuIG1pZDtcbiAgICB9XG4gIH1cbiAgZWxzZSB7XG4gICAgLy8gT3VyIG5lZWRsZSBpcyBsZXNzIHRoYW4gYUhheXN0YWNrW21pZF0uXG4gICAgaWYgKG1pZCAtIGFMb3cgPiAxKSB7XG4gICAgICAvLyBUaGUgZWxlbWVudCBpcyBpbiB0aGUgbG93ZXIgaGFsZi5cbiAgICAgIHJldHVybiByZWN1cnNpdmVTZWFyY2goYUxvdywgbWlkLCBhTmVlZGxlLCBhSGF5c3RhY2ssIGFDb21wYXJlLCBhQmlhcyk7XG4gICAgfVxuXG4gICAgLy8gd2UgYXJlIGluIHRlcm1pbmF0aW9uIGNhc2UgKDMpIG9yICgyKSBhbmQgcmV0dXJuIHRoZSBhcHByb3ByaWF0ZSB0aGluZy5cbiAgICBpZiAoYUJpYXMgPT0gZXhwb3J0cy5MRUFTVF9VUFBFUl9CT1VORCkge1xuICAgICAgcmV0dXJuIG1pZDtcbiAgICB9IGVsc2Uge1xuICAgICAgcmV0dXJuIGFMb3cgPCAwID8gLTEgOiBhTG93O1xuICAgIH1cbiAgfVxufVxuXG4vKipcbiAqIFRoaXMgaXMgYW4gaW1wbGVtZW50YXRpb24gb2YgYmluYXJ5IHNlYXJjaCB3aGljaCB3aWxsIGFsd2F5cyB0cnkgYW5kIHJldHVyblxuICogdGhlIGluZGV4IG9mIHRoZSBjbG9zZXN0IGVsZW1lbnQgaWYgdGhlcmUgaXMgbm8gZXhhY3QgaGl0LiBUaGlzIGlzIGJlY2F1c2VcbiAqIG1hcHBpbmdzIGJldHdlZW4gb3JpZ2luYWwgYW5kIGdlbmVyYXRlZCBsaW5lL2NvbCBwYWlycyBhcmUgc2luZ2xlIHBvaW50cyxcbiAqIGFuZCB0aGVyZSBpcyBhbiBpbXBsaWNpdCByZWdpb24gYmV0d2VlbiBlYWNoIG9mIHRoZW0sIHNvIGEgbWlzcyBqdXN0IG1lYW5zXG4gKiB0aGF0IHlvdSBhcmVuJ3Qgb24gdGhlIHZlcnkgc3RhcnQgb2YgYSByZWdpb24uXG4gKlxuICogQHBhcmFtIGFOZWVkbGUgVGhlIGVsZW1lbnQgeW91IGFyZSBsb29raW5nIGZvci5cbiAqIEBwYXJhbSBhSGF5c3RhY2sgVGhlIGFycmF5IHRoYXQgaXMgYmVpbmcgc2VhcmNoZWQuXG4gKiBAcGFyYW0gYUNvbXBhcmUgQSBmdW5jdGlvbiB3aGljaCB0YWtlcyB0aGUgbmVlZGxlIGFuZCBhbiBlbGVtZW50IGluIHRoZVxuICogICAgIGFycmF5IGFuZCByZXR1cm5zIC0xLCAwLCBvciAxIGRlcGVuZGluZyBvbiB3aGV0aGVyIHRoZSBuZWVkbGUgaXMgbGVzc1xuICogICAgIHRoYW4sIGVxdWFsIHRvLCBvciBncmVhdGVyIHRoYW4gdGhlIGVsZW1lbnQsIHJlc3BlY3RpdmVseS5cbiAqIEBwYXJhbSBhQmlhcyBFaXRoZXIgJ2JpbmFyeVNlYXJjaC5HUkVBVEVTVF9MT1dFUl9CT1VORCcgb3JcbiAqICAgICAnYmluYXJ5U2VhcmNoLkxFQVNUX1VQUEVSX0JPVU5EJy4gU3BlY2lmaWVzIHdoZXRoZXIgdG8gcmV0dXJuIHRoZVxuICogICAgIGNsb3Nlc3QgZWxlbWVudCB0aGF0IGlzIHNtYWxsZXIgdGhhbiBvciBncmVhdGVyIHRoYW4gdGhlIG9uZSB3ZSBhcmVcbiAqICAgICBzZWFyY2hpbmcgZm9yLCByZXNwZWN0aXZlbHksIGlmIHRoZSBleGFjdCBlbGVtZW50IGNhbm5vdCBiZSBmb3VuZC5cbiAqICAgICBEZWZhdWx0cyB0byAnYmluYXJ5U2VhcmNoLkdSRUFURVNUX0xPV0VSX0JPVU5EJy5cbiAqL1xuZXhwb3J0cy5zZWFyY2ggPSBmdW5jdGlvbiBzZWFyY2goYU5lZWRsZSwgYUhheXN0YWNrLCBhQ29tcGFyZSwgYUJpYXMpIHtcbiAgaWYgKGFIYXlzdGFjay5sZW5ndGggPT09IDApIHtcbiAgICByZXR1cm4gLTE7XG4gIH1cblxuICB2YXIgaW5kZXggPSByZWN1cnNpdmVTZWFyY2goLTEsIGFIYXlzdGFjay5sZW5ndGgsIGFOZWVkbGUsIGFIYXlzdGFjayxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGFDb21wYXJlLCBhQmlhcyB8fCBleHBvcnRzLkdSRUFURVNUX0xPV0VSX0JPVU5EKTtcbiAgaWYgKGluZGV4IDwgMCkge1xuICAgIHJldHVybiAtMTtcbiAgfVxuXG4gIC8vIFdlIGhhdmUgZm91bmQgZWl0aGVyIHRoZSBleGFjdCBlbGVtZW50LCBvciB0aGUgbmV4dC1jbG9zZXN0IGVsZW1lbnQgdGhhblxuICAvLyB0aGUgb25lIHdlIGFyZSBzZWFyY2hpbmcgZm9yLiBIb3dldmVyLCB0aGVyZSBtYXkgYmUgbW9yZSB0aGFuIG9uZSBzdWNoXG4gIC8vIGVsZW1lbnQuIE1ha2Ugc3VyZSB3ZSBhbHdheXMgcmV0dXJuIHRoZSBzbWFsbGVzdCBvZiB0aGVzZS5cbiAgd2hpbGUgKGluZGV4IC0gMSA+PSAwKSB7XG4gICAgaWYgKGFDb21wYXJlKGFIYXlzdGFja1tpbmRleF0sIGFIYXlzdGFja1tpbmRleCAtIDFdLCB0cnVlKSAhPT0gMCkge1xuICAgICAgYnJlYWs7XG4gICAgfVxuICAgIC0taW5kZXg7XG4gIH1cblxuICByZXR1cm4gaW5kZXg7XG59O1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvYmluYXJ5LXNlYXJjaC5qc1xuLy8gbW9kdWxlIGlkID0gOFxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbi8vIEl0IHR1cm5zIG91dCB0aGF0IHNvbWUgKG1vc3Q/KSBKYXZhU2NyaXB0IGVuZ2luZXMgZG9uJ3Qgc2VsZi1ob3N0XG4vLyBgQXJyYXkucHJvdG90eXBlLnNvcnRgLiBUaGlzIG1ha2VzIHNlbnNlIGJlY2F1c2UgQysrIHdpbGwgbGlrZWx5IHJlbWFpblxuLy8gZmFzdGVyIHRoYW4gSlMgd2hlbiBkb2luZyByYXcgQ1BVLWludGVuc2l2ZSBzb3J0aW5nLiBIb3dldmVyLCB3aGVuIHVzaW5nIGFcbi8vIGN1c3RvbSBjb21wYXJhdG9yIGZ1bmN0aW9uLCBjYWxsaW5nIGJhY2sgYW5kIGZvcnRoIGJldHdlZW4gdGhlIFZNJ3MgQysrIGFuZFxuLy8gSklUJ2QgSlMgaXMgcmF0aGVyIHNsb3cgKmFuZCogbG9zZXMgSklUIHR5cGUgaW5mb3JtYXRpb24sIHJlc3VsdGluZyBpblxuLy8gd29yc2UgZ2VuZXJhdGVkIGNvZGUgZm9yIHRoZSBjb21wYXJhdG9yIGZ1bmN0aW9uIHRoYW4gd291bGQgYmUgb3B0aW1hbC4gSW5cbi8vIGZhY3QsIHdoZW4gc29ydGluZyB3aXRoIGEgY29tcGFyYXRvciwgdGhlc2UgY29zdHMgb3V0d2VpZ2ggdGhlIGJlbmVmaXRzIG9mXG4vLyBzb3J0aW5nIGluIEMrKy4gQnkgdXNpbmcgb3VyIG93biBKUy1pbXBsZW1lbnRlZCBRdWljayBTb3J0IChiZWxvdyksIHdlIGdldFxuLy8gYSB+MzUwMG1zIG1lYW4gc3BlZWQtdXAgaW4gYGJlbmNoL2JlbmNoLmh0bWxgLlxuXG4vKipcbiAqIFN3YXAgdGhlIGVsZW1lbnRzIGluZGV4ZWQgYnkgYHhgIGFuZCBgeWAgaW4gdGhlIGFycmF5IGBhcnlgLlxuICpcbiAqIEBwYXJhbSB7QXJyYXl9IGFyeVxuICogICAgICAgIFRoZSBhcnJheS5cbiAqIEBwYXJhbSB7TnVtYmVyfSB4XG4gKiAgICAgICAgVGhlIGluZGV4IG9mIHRoZSBmaXJzdCBpdGVtLlxuICogQHBhcmFtIHtOdW1iZXJ9IHlcbiAqICAgICAgICBUaGUgaW5kZXggb2YgdGhlIHNlY29uZCBpdGVtLlxuICovXG5mdW5jdGlvbiBzd2FwKGFyeSwgeCwgeSkge1xuICB2YXIgdGVtcCA9IGFyeVt4XTtcbiAgYXJ5W3hdID0gYXJ5W3ldO1xuICBhcnlbeV0gPSB0ZW1wO1xufVxuXG4vKipcbiAqIFJldHVybnMgYSByYW5kb20gaW50ZWdlciB3aXRoaW4gdGhlIHJhbmdlIGBsb3cgLi4gaGlnaGAgaW5jbHVzaXZlLlxuICpcbiAqIEBwYXJhbSB7TnVtYmVyfSBsb3dcbiAqICAgICAgICBUaGUgbG93ZXIgYm91bmQgb24gdGhlIHJhbmdlLlxuICogQHBhcmFtIHtOdW1iZXJ9IGhpZ2hcbiAqICAgICAgICBUaGUgdXBwZXIgYm91bmQgb24gdGhlIHJhbmdlLlxuICovXG5mdW5jdGlvbiByYW5kb21JbnRJblJhbmdlKGxvdywgaGlnaCkge1xuICByZXR1cm4gTWF0aC5yb3VuZChsb3cgKyAoTWF0aC5yYW5kb20oKSAqIChoaWdoIC0gbG93KSkpO1xufVxuXG4vKipcbiAqIFRoZSBRdWljayBTb3J0IGFsZ29yaXRobS5cbiAqXG4gKiBAcGFyYW0ge0FycmF5fSBhcnlcbiAqICAgICAgICBBbiBhcnJheSB0byBzb3J0LlxuICogQHBhcmFtIHtmdW5jdGlvbn0gY29tcGFyYXRvclxuICogICAgICAgIEZ1bmN0aW9uIHRvIHVzZSB0byBjb21wYXJlIHR3byBpdGVtcy5cbiAqIEBwYXJhbSB7TnVtYmVyfSBwXG4gKiAgICAgICAgU3RhcnQgaW5kZXggb2YgdGhlIGFycmF5XG4gKiBAcGFyYW0ge051bWJlcn0gclxuICogICAgICAgIEVuZCBpbmRleCBvZiB0aGUgYXJyYXlcbiAqL1xuZnVuY3Rpb24gZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBwLCByKSB7XG4gIC8vIElmIG91ciBsb3dlciBib3VuZCBpcyBsZXNzIHRoYW4gb3VyIHVwcGVyIGJvdW5kLCB3ZSAoMSkgcGFydGl0aW9uIHRoZVxuICAvLyBhcnJheSBpbnRvIHR3byBwaWVjZXMgYW5kICgyKSByZWN1cnNlIG9uIGVhY2ggaGFsZi4gSWYgaXQgaXMgbm90LCB0aGlzIGlzXG4gIC8vIHRoZSBlbXB0eSBhcnJheSBhbmQgb3VyIGJhc2UgY2FzZS5cblxuICBpZiAocCA8IHIpIHtcbiAgICAvLyAoMSkgUGFydGl0aW9uaW5nLlxuICAgIC8vXG4gICAgLy8gVGhlIHBhcnRpdGlvbmluZyBjaG9vc2VzIGEgcGl2b3QgYmV0d2VlbiBgcGAgYW5kIGByYCBhbmQgbW92ZXMgYWxsXG4gICAgLy8gZWxlbWVudHMgdGhhdCBhcmUgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBwaXZvdCB0byB0aGUgYmVmb3JlIGl0LCBhbmRcbiAgICAvLyBhbGwgdGhlIGVsZW1lbnRzIHRoYXQgYXJlIGdyZWF0ZXIgdGhhbiBpdCBhZnRlciBpdC4gVGhlIGVmZmVjdCBpcyB0aGF0XG4gICAgLy8gb25jZSBwYXJ0aXRpb24gaXMgZG9uZSwgdGhlIHBpdm90IGlzIGluIHRoZSBleGFjdCBwbGFjZSBpdCB3aWxsIGJlIHdoZW5cbiAgICAvLyB0aGUgYXJyYXkgaXMgcHV0IGluIHNvcnRlZCBvcmRlciwgYW5kIGl0IHdpbGwgbm90IG5lZWQgdG8gYmUgbW92ZWRcbiAgICAvLyBhZ2Fpbi4gVGhpcyBydW5zIGluIE8obikgdGltZS5cblxuICAgIC8vIEFsd2F5cyBjaG9vc2UgYSByYW5kb20gcGl2b3Qgc28gdGhhdCBhbiBpbnB1dCBhcnJheSB3aGljaCBpcyByZXZlcnNlXG4gICAgLy8gc29ydGVkIGRvZXMgbm90IGNhdXNlIE8obl4yKSBydW5uaW5nIHRpbWUuXG4gICAgdmFyIHBpdm90SW5kZXggPSByYW5kb21JbnRJblJhbmdlKHAsIHIpO1xuICAgIHZhciBpID0gcCAtIDE7XG5cbiAgICBzd2FwKGFyeSwgcGl2b3RJbmRleCwgcik7XG4gICAgdmFyIHBpdm90ID0gYXJ5W3JdO1xuXG4gICAgLy8gSW1tZWRpYXRlbHkgYWZ0ZXIgYGpgIGlzIGluY3JlbWVudGVkIGluIHRoaXMgbG9vcCwgdGhlIGZvbGxvd2luZyBob2xkXG4gICAgLy8gdHJ1ZTpcbiAgICAvL1xuICAgIC8vICAgKiBFdmVyeSBlbGVtZW50IGluIGBhcnlbcCAuLiBpXWAgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBwaXZvdC5cbiAgICAvL1xuICAgIC8vICAgKiBFdmVyeSBlbGVtZW50IGluIGBhcnlbaSsxIC4uIGotMV1gIGlzIGdyZWF0ZXIgdGhhbiB0aGUgcGl2b3QuXG4gICAgZm9yICh2YXIgaiA9IHA7IGogPCByOyBqKyspIHtcbiAgICAgIGlmIChjb21wYXJhdG9yKGFyeVtqXSwgcGl2b3QpIDw9IDApIHtcbiAgICAgICAgaSArPSAxO1xuICAgICAgICBzd2FwKGFyeSwgaSwgaik7XG4gICAgICB9XG4gICAgfVxuXG4gICAgc3dhcChhcnksIGkgKyAxLCBqKTtcbiAgICB2YXIgcSA9IGkgKyAxO1xuXG4gICAgLy8gKDIpIFJlY3Vyc2Ugb24gZWFjaCBoYWxmLlxuXG4gICAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBwLCBxIC0gMSk7XG4gICAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBxICsgMSwgcik7XG4gIH1cbn1cblxuLyoqXG4gKiBTb3J0IHRoZSBnaXZlbiBhcnJheSBpbi1wbGFjZSB3aXRoIHRoZSBnaXZlbiBjb21wYXJhdG9yIGZ1bmN0aW9uLlxuICpcbiAqIEBwYXJhbSB7QXJyYXl9IGFyeVxuICogICAgICAgIEFuIGFycmF5IHRvIHNvcnQuXG4gKiBAcGFyYW0ge2Z1bmN0aW9ufSBjb21wYXJhdG9yXG4gKiAgICAgICAgRnVuY3Rpb24gdG8gdXNlIHRvIGNvbXBhcmUgdHdvIGl0ZW1zLlxuICovXG5leHBvcnRzLnF1aWNrU29ydCA9IGZ1bmN0aW9uIChhcnksIGNvbXBhcmF0b3IpIHtcbiAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCAwLCBhcnkubGVuZ3RoIC0gMSk7XG59O1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvcXVpY2stc29ydC5qc1xuLy8gbW9kdWxlIGlkID0gOVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbnZhciBTb3VyY2VNYXBHZW5lcmF0b3IgPSByZXF1aXJlKCcuL3NvdXJjZS1tYXAtZ2VuZXJhdG9yJykuU291cmNlTWFwR2VuZXJhdG9yO1xudmFyIHV0aWwgPSByZXF1aXJlKCcuL3V0aWwnKTtcblxuLy8gTWF0Y2hlcyBhIFdpbmRvd3Mtc3R5bGUgYFxcclxcbmAgbmV3bGluZSBvciBhIGBcXG5gIG5ld2xpbmUgdXNlZCBieSBhbGwgb3RoZXJcbi8vIG9wZXJhdGluZyBzeXN0ZW1zIHRoZXNlIGRheXMgKGNhcHR1cmluZyB0aGUgcmVzdWx0KS5cbnZhciBSRUdFWF9ORVdMSU5FID0gLyhcXHI/XFxuKS87XG5cbi8vIE5ld2xpbmUgY2hhcmFjdGVyIGNvZGUgZm9yIGNoYXJDb2RlQXQoKSBjb21wYXJpc29uc1xudmFyIE5FV0xJTkVfQ09ERSA9IDEwO1xuXG4vLyBQcml2YXRlIHN5bWJvbCBmb3IgaWRlbnRpZnlpbmcgYFNvdXJjZU5vZGVgcyB3aGVuIG11bHRpcGxlIHZlcnNpb25zIG9mXG4vLyB0aGUgc291cmNlLW1hcCBsaWJyYXJ5IGFyZSBsb2FkZWQuIFRoaXMgTVVTVCBOT1QgQ0hBTkdFIGFjcm9zc1xuLy8gdmVyc2lvbnMhXG52YXIgaXNTb3VyY2VOb2RlID0gXCIkJCRpc1NvdXJjZU5vZGUkJCRcIjtcblxuLyoqXG4gKiBTb3VyY2VOb2RlcyBwcm92aWRlIGEgd2F5IHRvIGFic3RyYWN0IG92ZXIgaW50ZXJwb2xhdGluZy9jb25jYXRlbmF0aW5nXG4gKiBzbmlwcGV0cyBvZiBnZW5lcmF0ZWQgSmF2YVNjcmlwdCBzb3VyY2UgY29kZSB3aGlsZSBtYWludGFpbmluZyB0aGUgbGluZSBhbmRcbiAqIGNvbHVtbiBpbmZvcm1hdGlvbiBhc3NvY2lhdGVkIHdpdGggdGhlIG9yaWdpbmFsIHNvdXJjZSBjb2RlLlxuICpcbiAqIEBwYXJhbSBhTGluZSBUaGUgb3JpZ2luYWwgbGluZSBudW1iZXIuXG4gKiBAcGFyYW0gYUNvbHVtbiBUaGUgb3JpZ2luYWwgY29sdW1uIG51bWJlci5cbiAqIEBwYXJhbSBhU291cmNlIFRoZSBvcmlnaW5hbCBzb3VyY2UncyBmaWxlbmFtZS5cbiAqIEBwYXJhbSBhQ2h1bmtzIE9wdGlvbmFsLiBBbiBhcnJheSBvZiBzdHJpbmdzIHdoaWNoIGFyZSBzbmlwcGV0cyBvZlxuICogICAgICAgIGdlbmVyYXRlZCBKUywgb3Igb3RoZXIgU291cmNlTm9kZXMuXG4gKiBAcGFyYW0gYU5hbWUgVGhlIG9yaWdpbmFsIGlkZW50aWZpZXIuXG4gKi9cbmZ1bmN0aW9uIFNvdXJjZU5vZGUoYUxpbmUsIGFDb2x1bW4sIGFTb3VyY2UsIGFDaHVua3MsIGFOYW1lKSB7XG4gIHRoaXMuY2hpbGRyZW4gPSBbXTtcbiAgdGhpcy5zb3VyY2VDb250ZW50cyA9IHt9O1xuICB0aGlzLmxpbmUgPSBhTGluZSA9PSBudWxsID8gbnVsbCA6IGFMaW5lO1xuICB0aGlzLmNvbHVtbiA9IGFDb2x1bW4gPT0gbnVsbCA/IG51bGwgOiBhQ29sdW1uO1xuICB0aGlzLnNvdXJjZSA9IGFTb3VyY2UgPT0gbnVsbCA/IG51bGwgOiBhU291cmNlO1xuICB0aGlzLm5hbWUgPSBhTmFtZSA9PSBudWxsID8gbnVsbCA6IGFOYW1lO1xuICB0aGlzW2lzU291cmNlTm9kZV0gPSB0cnVlO1xuICBpZiAoYUNodW5rcyAhPSBudWxsKSB0aGlzLmFkZChhQ2h1bmtzKTtcbn1cblxuLyoqXG4gKiBDcmVhdGVzIGEgU291cmNlTm9kZSBmcm9tIGdlbmVyYXRlZCBjb2RlIGFuZCBhIFNvdXJjZU1hcENvbnN1bWVyLlxuICpcbiAqIEBwYXJhbSBhR2VuZXJhdGVkQ29kZSBUaGUgZ2VuZXJhdGVkIGNvZGVcbiAqIEBwYXJhbSBhU291cmNlTWFwQ29uc3VtZXIgVGhlIFNvdXJjZU1hcCBmb3IgdGhlIGdlbmVyYXRlZCBjb2RlXG4gKiBAcGFyYW0gYVJlbGF0aXZlUGF0aCBPcHRpb25hbC4gVGhlIHBhdGggdGhhdCByZWxhdGl2ZSBzb3VyY2VzIGluIHRoZVxuICogICAgICAgIFNvdXJjZU1hcENvbnN1bWVyIHNob3VsZCBiZSByZWxhdGl2ZSB0by5cbiAqL1xuU291cmNlTm9kZS5mcm9tU3RyaW5nV2l0aFNvdXJjZU1hcCA9XG4gIGZ1bmN0aW9uIFNvdXJjZU5vZGVfZnJvbVN0cmluZ1dpdGhTb3VyY2VNYXAoYUdlbmVyYXRlZENvZGUsIGFTb3VyY2VNYXBDb25zdW1lciwgYVJlbGF0aXZlUGF0aCkge1xuICAgIC8vIFRoZSBTb3VyY2VOb2RlIHdlIHdhbnQgdG8gZmlsbCB3aXRoIHRoZSBnZW5lcmF0ZWQgY29kZVxuICAgIC8vIGFuZCB0aGUgU291cmNlTWFwXG4gICAgdmFyIG5vZGUgPSBuZXcgU291cmNlTm9kZSgpO1xuXG4gICAgLy8gQWxsIGV2ZW4gaW5kaWNlcyBvZiB0aGlzIGFycmF5IGFyZSBvbmUgbGluZSBvZiB0aGUgZ2VuZXJhdGVkIGNvZGUsXG4gICAgLy8gd2hpbGUgYWxsIG9kZCBpbmRpY2VzIGFyZSB0aGUgbmV3bGluZXMgYmV0d2VlbiB0d28gYWRqYWNlbnQgbGluZXNcbiAgICAvLyAoc2luY2UgYFJFR0VYX05FV0xJTkVgIGNhcHR1cmVzIGl0cyBtYXRjaCkuXG4gICAgLy8gUHJvY2Vzc2VkIGZyYWdtZW50cyBhcmUgYWNjZXNzZWQgYnkgY2FsbGluZyBgc2hpZnROZXh0TGluZWAuXG4gICAgdmFyIHJlbWFpbmluZ0xpbmVzID0gYUdlbmVyYXRlZENvZGUuc3BsaXQoUkVHRVhfTkVXTElORSk7XG4gICAgdmFyIHJlbWFpbmluZ0xpbmVzSW5kZXggPSAwO1xuICAgIHZhciBzaGlmdE5leHRMaW5lID0gZnVuY3Rpb24oKSB7XG4gICAgICB2YXIgbGluZUNvbnRlbnRzID0gZ2V0TmV4dExpbmUoKTtcbiAgICAgIC8vIFRoZSBsYXN0IGxpbmUgb2YgYSBmaWxlIG1pZ2h0IG5vdCBoYXZlIGEgbmV3bGluZS5cbiAgICAgIHZhciBuZXdMaW5lID0gZ2V0TmV4dExpbmUoKSB8fCBcIlwiO1xuICAgICAgcmV0dXJuIGxpbmVDb250ZW50cyArIG5ld0xpbmU7XG5cbiAgICAgIGZ1bmN0aW9uIGdldE5leHRMaW5lKCkge1xuICAgICAgICByZXR1cm4gcmVtYWluaW5nTGluZXNJbmRleCA8IHJlbWFpbmluZ0xpbmVzLmxlbmd0aCA/XG4gICAgICAgICAgICByZW1haW5pbmdMaW5lc1tyZW1haW5pbmdMaW5lc0luZGV4KytdIDogdW5kZWZpbmVkO1xuICAgICAgfVxuICAgIH07XG5cbiAgICAvLyBXZSBuZWVkIHRvIHJlbWVtYmVyIHRoZSBwb3NpdGlvbiBvZiBcInJlbWFpbmluZ0xpbmVzXCJcbiAgICB2YXIgbGFzdEdlbmVyYXRlZExpbmUgPSAxLCBsYXN0R2VuZXJhdGVkQ29sdW1uID0gMDtcblxuICAgIC8vIFRoZSBnZW5lcmF0ZSBTb3VyY2VOb2RlcyB3ZSBuZWVkIGEgY29kZSByYW5nZS5cbiAgICAvLyBUbyBleHRyYWN0IGl0IGN1cnJlbnQgYW5kIGxhc3QgbWFwcGluZyBpcyB1c2VkLlxuICAgIC8vIEhlcmUgd2Ugc3RvcmUgdGhlIGxhc3QgbWFwcGluZy5cbiAgICB2YXIgbGFzdE1hcHBpbmcgPSBudWxsO1xuXG4gICAgYVNvdXJjZU1hcENvbnN1bWVyLmVhY2hNYXBwaW5nKGZ1bmN0aW9uIChtYXBwaW5nKSB7XG4gICAgICBpZiAobGFzdE1hcHBpbmcgIT09IG51bGwpIHtcbiAgICAgICAgLy8gV2UgYWRkIHRoZSBjb2RlIGZyb20gXCJsYXN0TWFwcGluZ1wiIHRvIFwibWFwcGluZ1wiOlxuICAgICAgICAvLyBGaXJzdCBjaGVjayBpZiB0aGVyZSBpcyBhIG5ldyBsaW5lIGluIGJldHdlZW4uXG4gICAgICAgIGlmIChsYXN0R2VuZXJhdGVkTGluZSA8IG1hcHBpbmcuZ2VuZXJhdGVkTGluZSkge1xuICAgICAgICAgIC8vIEFzc29jaWF0ZSBmaXJzdCBsaW5lIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgICAgYWRkTWFwcGluZ1dpdGhDb2RlKGxhc3RNYXBwaW5nLCBzaGlmdE5leHRMaW5lKCkpO1xuICAgICAgICAgIGxhc3RHZW5lcmF0ZWRMaW5lKys7XG4gICAgICAgICAgbGFzdEdlbmVyYXRlZENvbHVtbiA9IDA7XG4gICAgICAgICAgLy8gVGhlIHJlbWFpbmluZyBjb2RlIGlzIGFkZGVkIHdpdGhvdXQgbWFwcGluZ1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIC8vIFRoZXJlIGlzIG5vIG5ldyBsaW5lIGluIGJldHdlZW4uXG4gICAgICAgICAgLy8gQXNzb2NpYXRlIHRoZSBjb2RlIGJldHdlZW4gXCJsYXN0R2VuZXJhdGVkQ29sdW1uXCIgYW5kXG4gICAgICAgICAgLy8gXCJtYXBwaW5nLmdlbmVyYXRlZENvbHVtblwiIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgICAgdmFyIG5leHRMaW5lID0gcmVtYWluaW5nTGluZXNbcmVtYWluaW5nTGluZXNJbmRleF0gfHwgJyc7XG4gICAgICAgICAgdmFyIGNvZGUgPSBuZXh0TGluZS5zdWJzdHIoMCwgbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4gLVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxhc3RHZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgICAgIHJlbWFpbmluZ0xpbmVzW3JlbWFpbmluZ0xpbmVzSW5kZXhdID0gbmV4dExpbmUuc3Vic3RyKG1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uIC1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uKTtcbiAgICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uID0gbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW47XG4gICAgICAgICAgYWRkTWFwcGluZ1dpdGhDb2RlKGxhc3RNYXBwaW5nLCBjb2RlKTtcbiAgICAgICAgICAvLyBObyBtb3JlIHJlbWFpbmluZyBjb2RlLCBjb250aW51ZVxuICAgICAgICAgIGxhc3RNYXBwaW5nID0gbWFwcGluZztcbiAgICAgICAgICByZXR1cm47XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICAgIC8vIFdlIGFkZCB0aGUgZ2VuZXJhdGVkIGNvZGUgdW50aWwgdGhlIGZpcnN0IG1hcHBpbmdcbiAgICAgIC8vIHRvIHRoZSBTb3VyY2VOb2RlIHdpdGhvdXQgYW55IG1hcHBpbmcuXG4gICAgICAvLyBFYWNoIGxpbmUgaXMgYWRkZWQgYXMgc2VwYXJhdGUgc3RyaW5nLlxuICAgICAgd2hpbGUgKGxhc3RHZW5lcmF0ZWRMaW5lIDwgbWFwcGluZy5nZW5lcmF0ZWRMaW5lKSB7XG4gICAgICAgIG5vZGUuYWRkKHNoaWZ0TmV4dExpbmUoKSk7XG4gICAgICAgIGxhc3RHZW5lcmF0ZWRMaW5lKys7XG4gICAgICB9XG4gICAgICBpZiAobGFzdEdlbmVyYXRlZENvbHVtbiA8IG1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uKSB7XG4gICAgICAgIHZhciBuZXh0TGluZSA9IHJlbWFpbmluZ0xpbmVzW3JlbWFpbmluZ0xpbmVzSW5kZXhdIHx8ICcnO1xuICAgICAgICBub2RlLmFkZChuZXh0TGluZS5zdWJzdHIoMCwgbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4pKTtcbiAgICAgICAgcmVtYWluaW5nTGluZXNbcmVtYWluaW5nTGluZXNJbmRleF0gPSBuZXh0TGluZS5zdWJzdHIobWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uID0gbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW47XG4gICAgICB9XG4gICAgICBsYXN0TWFwcGluZyA9IG1hcHBpbmc7XG4gICAgfSwgdGhpcyk7XG4gICAgLy8gV2UgaGF2ZSBwcm9jZXNzZWQgYWxsIG1hcHBpbmdzLlxuICAgIGlmIChyZW1haW5pbmdMaW5lc0luZGV4IDwgcmVtYWluaW5nTGluZXMubGVuZ3RoKSB7XG4gICAgICBpZiAobGFzdE1hcHBpbmcpIHtcbiAgICAgICAgLy8gQXNzb2NpYXRlIHRoZSByZW1haW5pbmcgY29kZSBpbiB0aGUgY3VycmVudCBsaW5lIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgIGFkZE1hcHBpbmdXaXRoQ29kZShsYXN0TWFwcGluZywgc2hpZnROZXh0TGluZSgpKTtcbiAgICAgIH1cbiAgICAgIC8vIGFuZCBhZGQgdGhlIHJlbWFpbmluZyBsaW5lcyB3aXRob3V0IGFueSBtYXBwaW5nXG4gICAgICBub2RlLmFkZChyZW1haW5pbmdMaW5lcy5zcGxpY2UocmVtYWluaW5nTGluZXNJbmRleCkuam9pbihcIlwiKSk7XG4gICAgfVxuXG4gICAgLy8gQ29weSBzb3VyY2VzQ29udGVudCBpbnRvIFNvdXJjZU5vZGVcbiAgICBhU291cmNlTWFwQ29uc3VtZXIuc291cmNlcy5mb3JFYWNoKGZ1bmN0aW9uIChzb3VyY2VGaWxlKSB7XG4gICAgICB2YXIgY29udGVudCA9IGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKHNvdXJjZUZpbGUpO1xuICAgICAgaWYgKGNvbnRlbnQgIT0gbnVsbCkge1xuICAgICAgICBpZiAoYVJlbGF0aXZlUGF0aCAhPSBudWxsKSB7XG4gICAgICAgICAgc291cmNlRmlsZSA9IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBzb3VyY2VGaWxlKTtcbiAgICAgICAgfVxuICAgICAgICBub2RlLnNldFNvdXJjZUNvbnRlbnQoc291cmNlRmlsZSwgY29udGVudCk7XG4gICAgICB9XG4gICAgfSk7XG5cbiAgICByZXR1cm4gbm9kZTtcblxuICAgIGZ1bmN0aW9uIGFkZE1hcHBpbmdXaXRoQ29kZShtYXBwaW5nLCBjb2RlKSB7XG4gICAgICBpZiAobWFwcGluZyA9PT0gbnVsbCB8fCBtYXBwaW5nLnNvdXJjZSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIG5vZGUuYWRkKGNvZGUpO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgdmFyIHNvdXJjZSA9IGFSZWxhdGl2ZVBhdGhcbiAgICAgICAgICA/IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBtYXBwaW5nLnNvdXJjZSlcbiAgICAgICAgICA6IG1hcHBpbmcuc291cmNlO1xuICAgICAgICBub2RlLmFkZChuZXcgU291cmNlTm9kZShtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc291cmNlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBtYXBwaW5nLm5hbWUpKTtcbiAgICAgIH1cbiAgICB9XG4gIH07XG5cbi8qKlxuICogQWRkIGEgY2h1bmsgb2YgZ2VuZXJhdGVkIEpTIHRvIHRoaXMgc291cmNlIG5vZGUuXG4gKlxuICogQHBhcmFtIGFDaHVuayBBIHN0cmluZyBzbmlwcGV0IG9mIGdlbmVyYXRlZCBKUyBjb2RlLCBhbm90aGVyIGluc3RhbmNlIG9mXG4gKiAgICAgICAgU291cmNlTm9kZSwgb3IgYW4gYXJyYXkgd2hlcmUgZWFjaCBtZW1iZXIgaXMgb25lIG9mIHRob3NlIHRoaW5ncy5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUuYWRkID0gZnVuY3Rpb24gU291cmNlTm9kZV9hZGQoYUNodW5rKSB7XG4gIGlmIChBcnJheS5pc0FycmF5KGFDaHVuaykpIHtcbiAgICBhQ2h1bmsuZm9yRWFjaChmdW5jdGlvbiAoY2h1bmspIHtcbiAgICAgIHRoaXMuYWRkKGNodW5rKTtcbiAgICB9LCB0aGlzKTtcbiAgfVxuICBlbHNlIGlmIChhQ2h1bmtbaXNTb3VyY2VOb2RlXSB8fCB0eXBlb2YgYUNodW5rID09PSBcInN0cmluZ1wiKSB7XG4gICAgaWYgKGFDaHVuaykge1xuICAgICAgdGhpcy5jaGlsZHJlbi5wdXNoKGFDaHVuayk7XG4gICAgfVxuICB9XG4gIGVsc2Uge1xuICAgIHRocm93IG5ldyBUeXBlRXJyb3IoXG4gICAgICBcIkV4cGVjdGVkIGEgU291cmNlTm9kZSwgc3RyaW5nLCBvciBhbiBhcnJheSBvZiBTb3VyY2VOb2RlcyBhbmQgc3RyaW5ncy4gR290IFwiICsgYUNodW5rXG4gICAgKTtcbiAgfVxuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogQWRkIGEgY2h1bmsgb2YgZ2VuZXJhdGVkIEpTIHRvIHRoZSBiZWdpbm5pbmcgb2YgdGhpcyBzb3VyY2Ugbm9kZS5cbiAqXG4gKiBAcGFyYW0gYUNodW5rIEEgc3RyaW5nIHNuaXBwZXQgb2YgZ2VuZXJhdGVkIEpTIGNvZGUsIGFub3RoZXIgaW5zdGFuY2Ugb2ZcbiAqICAgICAgICBTb3VyY2VOb2RlLCBvciBhbiBhcnJheSB3aGVyZSBlYWNoIG1lbWJlciBpcyBvbmUgb2YgdGhvc2UgdGhpbmdzLlxuICovXG5Tb3VyY2VOb2RlLnByb3RvdHlwZS5wcmVwZW5kID0gZnVuY3Rpb24gU291cmNlTm9kZV9wcmVwZW5kKGFDaHVuaykge1xuICBpZiAoQXJyYXkuaXNBcnJheShhQ2h1bmspKSB7XG4gICAgZm9yICh2YXIgaSA9IGFDaHVuay5sZW5ndGgtMTsgaSA+PSAwOyBpLS0pIHtcbiAgICAgIHRoaXMucHJlcGVuZChhQ2h1bmtbaV0pO1xuICAgIH1cbiAgfVxuICBlbHNlIGlmIChhQ2h1bmtbaXNTb3VyY2VOb2RlXSB8fCB0eXBlb2YgYUNodW5rID09PSBcInN0cmluZ1wiKSB7XG4gICAgdGhpcy5jaGlsZHJlbi51bnNoaWZ0KGFDaHVuayk7XG4gIH1cbiAgZWxzZSB7XG4gICAgdGhyb3cgbmV3IFR5cGVFcnJvcihcbiAgICAgIFwiRXhwZWN0ZWQgYSBTb3VyY2VOb2RlLCBzdHJpbmcsIG9yIGFuIGFycmF5IG9mIFNvdXJjZU5vZGVzIGFuZCBzdHJpbmdzLiBHb3QgXCIgKyBhQ2h1bmtcbiAgICApO1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBXYWxrIG92ZXIgdGhlIHRyZWUgb2YgSlMgc25pcHBldHMgaW4gdGhpcyBub2RlIGFuZCBpdHMgY2hpbGRyZW4uIFRoZVxuICogd2Fsa2luZyBmdW5jdGlvbiBpcyBjYWxsZWQgb25jZSBmb3IgZWFjaCBzbmlwcGV0IG9mIEpTIGFuZCBpcyBwYXNzZWQgdGhhdFxuICogc25pcHBldCBhbmQgdGhlIGl0cyBvcmlnaW5hbCBhc3NvY2lhdGVkIHNvdXJjZSdzIGxpbmUvY29sdW1uIGxvY2F0aW9uLlxuICpcbiAqIEBwYXJhbSBhRm4gVGhlIHRyYXZlcnNhbCBmdW5jdGlvbi5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUud2FsayA9IGZ1bmN0aW9uIFNvdXJjZU5vZGVfd2FsayhhRm4pIHtcbiAgdmFyIGNodW5rO1xuICBmb3IgKHZhciBpID0gMCwgbGVuID0gdGhpcy5jaGlsZHJlbi5sZW5ndGg7IGkgPCBsZW47IGkrKykge1xuICAgIGNodW5rID0gdGhpcy5jaGlsZHJlbltpXTtcbiAgICBpZiAoY2h1bmtbaXNTb3VyY2VOb2RlXSkge1xuICAgICAgY2h1bmsud2FsayhhRm4pO1xuICAgIH1cbiAgICBlbHNlIHtcbiAgICAgIGlmIChjaHVuayAhPT0gJycpIHtcbiAgICAgICAgYUZuKGNodW5rLCB7IHNvdXJjZTogdGhpcy5zb3VyY2UsXG4gICAgICAgICAgICAgICAgICAgICBsaW5lOiB0aGlzLmxpbmUsXG4gICAgICAgICAgICAgICAgICAgICBjb2x1bW46IHRoaXMuY29sdW1uLFxuICAgICAgICAgICAgICAgICAgICAgbmFtZTogdGhpcy5uYW1lIH0pO1xuICAgICAgfVxuICAgIH1cbiAgfVxufTtcblxuLyoqXG4gKiBMaWtlIGBTdHJpbmcucHJvdG90eXBlLmpvaW5gIGV4Y2VwdCBmb3IgU291cmNlTm9kZXMuIEluc2VydHMgYGFTdHJgIGJldHdlZW5cbiAqIGVhY2ggb2YgYHRoaXMuY2hpbGRyZW5gLlxuICpcbiAqIEBwYXJhbSBhU2VwIFRoZSBzZXBhcmF0b3IuXG4gKi9cblNvdXJjZU5vZGUucHJvdG90eXBlLmpvaW4gPSBmdW5jdGlvbiBTb3VyY2VOb2RlX2pvaW4oYVNlcCkge1xuICB2YXIgbmV3Q2hpbGRyZW47XG4gIHZhciBpO1xuICB2YXIgbGVuID0gdGhpcy5jaGlsZHJlbi5sZW5ndGg7XG4gIGlmIChsZW4gPiAwKSB7XG4gICAgbmV3Q2hpbGRyZW4gPSBbXTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgbGVuLTE7IGkrKykge1xuICAgICAgbmV3Q2hpbGRyZW4ucHVzaCh0aGlzLmNoaWxkcmVuW2ldKTtcbiAgICAgIG5ld0NoaWxkcmVuLnB1c2goYVNlcCk7XG4gICAgfVxuICAgIG5ld0NoaWxkcmVuLnB1c2godGhpcy5jaGlsZHJlbltpXSk7XG4gICAgdGhpcy5jaGlsZHJlbiA9IG5ld0NoaWxkcmVuO1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBDYWxsIFN0cmluZy5wcm90b3R5cGUucmVwbGFjZSBvbiB0aGUgdmVyeSByaWdodC1tb3N0IHNvdXJjZSBzbmlwcGV0LiBVc2VmdWxcbiAqIGZvciB0cmltbWluZyB3aGl0ZXNwYWNlIGZyb20gdGhlIGVuZCBvZiBhIHNvdXJjZSBub2RlLCBldGMuXG4gKlxuICogQHBhcmFtIGFQYXR0ZXJuIFRoZSBwYXR0ZXJuIHRvIHJlcGxhY2UuXG4gKiBAcGFyYW0gYVJlcGxhY2VtZW50IFRoZSB0aGluZyB0byByZXBsYWNlIHRoZSBwYXR0ZXJuIHdpdGguXG4gKi9cblNvdXJjZU5vZGUucHJvdG90eXBlLnJlcGxhY2VSaWdodCA9IGZ1bmN0aW9uIFNvdXJjZU5vZGVfcmVwbGFjZVJpZ2h0KGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpIHtcbiAgdmFyIGxhc3RDaGlsZCA9IHRoaXMuY2hpbGRyZW5bdGhpcy5jaGlsZHJlbi5sZW5ndGggLSAxXTtcbiAgaWYgKGxhc3RDaGlsZFtpc1NvdXJjZU5vZGVdKSB7XG4gICAgbGFzdENoaWxkLnJlcGxhY2VSaWdodChhUGF0dGVybiwgYVJlcGxhY2VtZW50KTtcbiAgfVxuICBlbHNlIGlmICh0eXBlb2YgbGFzdENoaWxkID09PSAnc3RyaW5nJykge1xuICAgIHRoaXMuY2hpbGRyZW5bdGhpcy5jaGlsZHJlbi5sZW5ndGggLSAxXSA9IGxhc3RDaGlsZC5yZXBsYWNlKGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpO1xuICB9XG4gIGVsc2Uge1xuICAgIHRoaXMuY2hpbGRyZW4ucHVzaCgnJy5yZXBsYWNlKGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpKTtcbiAgfVxuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogU2V0IHRoZSBzb3VyY2UgY29udGVudCBmb3IgYSBzb3VyY2UgZmlsZS4gVGhpcyB3aWxsIGJlIGFkZGVkIHRvIHRoZSBTb3VyY2VNYXBHZW5lcmF0b3JcbiAqIGluIHRoZSBzb3VyY2VzQ29udGVudCBmaWVsZC5cbiAqXG4gKiBAcGFyYW0gYVNvdXJjZUZpbGUgVGhlIGZpbGVuYW1lIG9mIHRoZSBzb3VyY2UgZmlsZVxuICogQHBhcmFtIGFTb3VyY2VDb250ZW50IFRoZSBjb250ZW50IG9mIHRoZSBzb3VyY2UgZmlsZVxuICovXG5Tb3VyY2VOb2RlLnByb3RvdHlwZS5zZXRTb3VyY2VDb250ZW50ID1cbiAgZnVuY3Rpb24gU291cmNlTm9kZV9zZXRTb3VyY2VDb250ZW50KGFTb3VyY2VGaWxlLCBhU291cmNlQ29udGVudCkge1xuICAgIHRoaXMuc291cmNlQ29udGVudHNbdXRpbC50b1NldFN0cmluZyhhU291cmNlRmlsZSldID0gYVNvdXJjZUNvbnRlbnQ7XG4gIH07XG5cbi8qKlxuICogV2FsayBvdmVyIHRoZSB0cmVlIG9mIFNvdXJjZU5vZGVzLiBUaGUgd2Fsa2luZyBmdW5jdGlvbiBpcyBjYWxsZWQgZm9yIGVhY2hcbiAqIHNvdXJjZSBmaWxlIGNvbnRlbnQgYW5kIGlzIHBhc3NlZCB0aGUgZmlsZW5hbWUgYW5kIHNvdXJjZSBjb250ZW50LlxuICpcbiAqIEBwYXJhbSBhRm4gVGhlIHRyYXZlcnNhbCBmdW5jdGlvbi5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUud2Fsa1NvdXJjZUNvbnRlbnRzID1cbiAgZnVuY3Rpb24gU291cmNlTm9kZV93YWxrU291cmNlQ29udGVudHMoYUZuKSB7XG4gICAgZm9yICh2YXIgaSA9IDAsIGxlbiA9IHRoaXMuY2hpbGRyZW4ubGVuZ3RoOyBpIDwgbGVuOyBpKyspIHtcbiAgICAgIGlmICh0aGlzLmNoaWxkcmVuW2ldW2lzU291cmNlTm9kZV0pIHtcbiAgICAgICAgdGhpcy5jaGlsZHJlbltpXS53YWxrU291cmNlQ29udGVudHMoYUZuKTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICB2YXIgc291cmNlcyA9IE9iamVjdC5rZXlzKHRoaXMuc291cmNlQ29udGVudHMpO1xuICAgIGZvciAodmFyIGkgPSAwLCBsZW4gPSBzb3VyY2VzLmxlbmd0aDsgaSA8IGxlbjsgaSsrKSB7XG4gICAgICBhRm4odXRpbC5mcm9tU2V0U3RyaW5nKHNvdXJjZXNbaV0pLCB0aGlzLnNvdXJjZUNvbnRlbnRzW3NvdXJjZXNbaV1dKTtcbiAgICB9XG4gIH07XG5cbi8qKlxuICogUmV0dXJuIHRoZSBzdHJpbmcgcmVwcmVzZW50YXRpb24gb2YgdGhpcyBzb3VyY2Ugbm9kZS4gV2Fsa3Mgb3ZlciB0aGUgdHJlZVxuICogYW5kIGNvbmNhdGVuYXRlcyBhbGwgdGhlIHZhcmlvdXMgc25pcHBldHMgdG9nZXRoZXIgdG8gb25lIHN0cmluZy5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUudG9TdHJpbmcgPSBmdW5jdGlvbiBTb3VyY2VOb2RlX3RvU3RyaW5nKCkge1xuICB2YXIgc3RyID0gXCJcIjtcbiAgdGhpcy53YWxrKGZ1bmN0aW9uIChjaHVuaykge1xuICAgIHN0ciArPSBjaHVuaztcbiAgfSk7XG4gIHJldHVybiBzdHI7XG59O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIHN0cmluZyByZXByZXNlbnRhdGlvbiBvZiB0aGlzIHNvdXJjZSBub2RlIGFsb25nIHdpdGggYSBzb3VyY2VcbiAqIG1hcC5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUudG9TdHJpbmdXaXRoU291cmNlTWFwID0gZnVuY3Rpb24gU291cmNlTm9kZV90b1N0cmluZ1dpdGhTb3VyY2VNYXAoYUFyZ3MpIHtcbiAgdmFyIGdlbmVyYXRlZCA9IHtcbiAgICBjb2RlOiBcIlwiLFxuICAgIGxpbmU6IDEsXG4gICAgY29sdW1uOiAwXG4gIH07XG4gIHZhciBtYXAgPSBuZXcgU291cmNlTWFwR2VuZXJhdG9yKGFBcmdzKTtcbiAgdmFyIHNvdXJjZU1hcHBpbmdBY3RpdmUgPSBmYWxzZTtcbiAgdmFyIGxhc3RPcmlnaW5hbFNvdXJjZSA9IG51bGw7XG4gIHZhciBsYXN0T3JpZ2luYWxMaW5lID0gbnVsbDtcbiAgdmFyIGxhc3RPcmlnaW5hbENvbHVtbiA9IG51bGw7XG4gIHZhciBsYXN0T3JpZ2luYWxOYW1lID0gbnVsbDtcbiAgdGhpcy53YWxrKGZ1bmN0aW9uIChjaHVuaywgb3JpZ2luYWwpIHtcbiAgICBnZW5lcmF0ZWQuY29kZSArPSBjaHVuaztcbiAgICBpZiAob3JpZ2luYWwuc291cmNlICE9PSBudWxsXG4gICAgICAgICYmIG9yaWdpbmFsLmxpbmUgIT09IG51bGxcbiAgICAgICAgJiYgb3JpZ2luYWwuY29sdW1uICE9PSBudWxsKSB7XG4gICAgICBpZihsYXN0T3JpZ2luYWxTb3VyY2UgIT09IG9yaWdpbmFsLnNvdXJjZVxuICAgICAgICAgfHwgbGFzdE9yaWdpbmFsTGluZSAhPT0gb3JpZ2luYWwubGluZVxuICAgICAgICAgfHwgbGFzdE9yaWdpbmFsQ29sdW1uICE9PSBvcmlnaW5hbC5jb2x1bW5cbiAgICAgICAgIHx8IGxhc3RPcmlnaW5hbE5hbWUgIT09IG9yaWdpbmFsLm5hbWUpIHtcbiAgICAgICAgbWFwLmFkZE1hcHBpbmcoe1xuICAgICAgICAgIHNvdXJjZTogb3JpZ2luYWwuc291cmNlLFxuICAgICAgICAgIG9yaWdpbmFsOiB7XG4gICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgY29sdW1uOiBvcmlnaW5hbC5jb2x1bW5cbiAgICAgICAgICB9LFxuICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgbGluZTogZ2VuZXJhdGVkLmxpbmUsXG4gICAgICAgICAgICBjb2x1bW46IGdlbmVyYXRlZC5jb2x1bW5cbiAgICAgICAgICB9LFxuICAgICAgICAgIG5hbWU6IG9yaWdpbmFsLm5hbWVcbiAgICAgICAgfSk7XG4gICAgICB9XG4gICAgICBsYXN0T3JpZ2luYWxTb3VyY2UgPSBvcmlnaW5hbC5zb3VyY2U7XG4gICAgICBsYXN0T3JpZ2luYWxMaW5lID0gb3JpZ2luYWwubGluZTtcbiAgICAgIGxhc3RPcmlnaW5hbENvbHVtbiA9IG9yaWdpbmFsLmNvbHVtbjtcbiAgICAgIGxhc3RPcmlnaW5hbE5hbWUgPSBvcmlnaW5hbC5uYW1lO1xuICAgICAgc291cmNlTWFwcGluZ0FjdGl2ZSA9IHRydWU7XG4gICAgfSBlbHNlIGlmIChzb3VyY2VNYXBwaW5nQWN0aXZlKSB7XG4gICAgICBtYXAuYWRkTWFwcGluZyh7XG4gICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgIGxpbmU6IGdlbmVyYXRlZC5saW5lLFxuICAgICAgICAgIGNvbHVtbjogZ2VuZXJhdGVkLmNvbHVtblxuICAgICAgICB9XG4gICAgICB9KTtcbiAgICAgIGxhc3RPcmlnaW5hbFNvdXJjZSA9IG51bGw7XG4gICAgICBzb3VyY2VNYXBwaW5nQWN0aXZlID0gZmFsc2U7XG4gICAgfVxuICAgIGZvciAodmFyIGlkeCA9IDAsIGxlbmd0aCA9IGNodW5rLmxlbmd0aDsgaWR4IDwgbGVuZ3RoOyBpZHgrKykge1xuICAgICAgaWYgKGNodW5rLmNoYXJDb2RlQXQoaWR4KSA9PT0gTkVXTElORV9DT0RFKSB7XG4gICAgICAgIGdlbmVyYXRlZC5saW5lKys7XG4gICAgICAgIGdlbmVyYXRlZC5jb2x1bW4gPSAwO1xuICAgICAgICAvLyBNYXBwaW5ncyBlbmQgYXQgZW9sXG4gICAgICAgIGlmIChpZHggKyAxID09PSBsZW5ndGgpIHtcbiAgICAgICAgICBsYXN0T3JpZ2luYWxTb3VyY2UgPSBudWxsO1xuICAgICAgICAgIHNvdXJjZU1hcHBpbmdBY3RpdmUgPSBmYWxzZTtcbiAgICAgICAgfSBlbHNlIGlmIChzb3VyY2VNYXBwaW5nQWN0aXZlKSB7XG4gICAgICAgICAgbWFwLmFkZE1hcHBpbmcoe1xuICAgICAgICAgICAgc291cmNlOiBvcmlnaW5hbC5zb3VyY2UsXG4gICAgICAgICAgICBvcmlnaW5hbDoge1xuICAgICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgICBjb2x1bW46IG9yaWdpbmFsLmNvbHVtblxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgICBsaW5lOiBnZW5lcmF0ZWQubGluZSxcbiAgICAgICAgICAgICAgY29sdW1uOiBnZW5lcmF0ZWQuY29sdW1uXG4gICAgICAgICAgICB9LFxuICAgICAgICAgICAgbmFtZTogb3JpZ2luYWwubmFtZVxuICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBnZW5lcmF0ZWQuY29sdW1uKys7XG4gICAgICB9XG4gICAgfVxuICB9KTtcbiAgdGhpcy53YWxrU291cmNlQ29udGVudHMoZnVuY3Rpb24gKHNvdXJjZUZpbGUsIHNvdXJjZUNvbnRlbnQpIHtcbiAgICBtYXAuc2V0U291cmNlQ29udGVudChzb3VyY2VGaWxlLCBzb3VyY2VDb250ZW50KTtcbiAgfSk7XG5cbiAgcmV0dXJuIHsgY29kZTogZ2VuZXJhdGVkLmNvZGUsIG1hcDogbWFwIH07XG59O1xuXG5leHBvcnRzLlNvdXJjZU5vZGUgPSBTb3VyY2VOb2RlO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW5vZGUuanNcbi8vIG1vZHVsZSBpZCA9IDEwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCJdLCJzb3VyY2VSb290IjoiIn0= \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/source-map/dist/source-map.js b/node_modules/mathjs/examples/node_modules/source-map/dist/source-map.js new file mode 100644 index 0000000..b4eb087 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/dist/source-map.js @@ -0,0 +1,3233 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/source-map/dist/source-map.min.js b/node_modules/mathjs/examples/node_modules/source-map/dist/source-map.min.js new file mode 100644 index 0000000..c7c72da --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/dist/source-map.min.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.sourceMap=n():e.sourceMap=n()}(this,function(){return function(e){function n(t){if(r[t])return r[t].exports;var o=r[t]={exports:{},id:t,loaded:!1};return e[t].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var r={};return n.m=e,n.c=r,n.p="",n(0)}([function(e,n,r){n.SourceMapGenerator=r(1).SourceMapGenerator,n.SourceMapConsumer=r(7).SourceMapConsumer,n.SourceNode=r(10).SourceNode},function(e,n,r){function t(e){e||(e={}),this._file=i.getArg(e,"file",null),this._sourceRoot=i.getArg(e,"sourceRoot",null),this._skipValidation=i.getArg(e,"skipValidation",!1),this._sources=new s,this._names=new s,this._mappings=new a,this._sourcesContents=null}var o=r(2),i=r(4),s=r(5).ArraySet,a=r(6).MappingList;t.prototype._version=3,t.fromSourceMap=function(e){var n=e.sourceRoot,r=new t({file:e.file,sourceRoot:n});return e.eachMapping(function(e){var t={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(t.source=e.source,null!=n&&(t.source=i.relative(n,t.source)),t.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(t.name=e.name)),r.addMapping(t)}),e.sources.forEach(function(t){var o=t;null!==n&&(o=i.relative(n,t)),r._sources.has(o)||r._sources.add(o);var s=e.sourceContentFor(t);null!=s&&r.setSourceContent(t,s)}),r},t.prototype.addMapping=function(e){var n=i.getArg(e,"generated"),r=i.getArg(e,"original",null),t=i.getArg(e,"source",null),o=i.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,t,o),null!=t&&(t=String(t),this._sources.has(t)||this._sources.add(t)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:null!=r&&r.line,originalColumn:null!=r&&r.column,source:t,name:o})},t.prototype.setSourceContent=function(e,n){var r=e;null!=this._sourceRoot&&(r=i.relative(this._sourceRoot,r)),null!=n?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[i.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[i.toSetString(r)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},t.prototype.applySourceMap=function(e,n,r){var t=n;if(null==n){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');t=e.file}var o=this._sourceRoot;null!=o&&(t=i.relative(o,t));var a=new s,u=new s;this._mappings.unsortedForEach(function(n){if(n.source===t&&null!=n.originalLine){var s=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});null!=s.source&&(n.source=s.source,null!=r&&(n.source=i.join(r,n.source)),null!=o&&(n.source=i.relative(o,n.source)),n.originalLine=s.line,n.originalColumn=s.column,null!=s.name&&(n.name=s.name))}var l=n.source;null==l||a.has(l)||a.add(l);var c=n.name;null==c||u.has(c)||u.add(c)},this),this._sources=a,this._names=u,e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&(null!=r&&(n=i.join(r,n)),null!=o&&(n=i.relative(o,n)),this.setSourceContent(n,t))},this)},t.prototype._validateMapping=function(e,n,r,t){if(n&&"number"!=typeof n.line&&"number"!=typeof n.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||n||r||t)&&!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:t}))},t.prototype._serializeMappings=function(){for(var e,n,r,t,s=0,a=1,u=0,l=0,c=0,g=0,p="",h=this._mappings.toArray(),f=0,d=h.length;f0){if(!i.compareByGeneratedPositionsInflated(n,h[f-1]))continue;e+=","}e+=o.encode(n.generatedColumn-s),s=n.generatedColumn,null!=n.source&&(t=this._sources.indexOf(n.source),e+=o.encode(t-g),g=t,e+=o.encode(n.originalLine-1-l),l=n.originalLine-1,e+=o.encode(n.originalColumn-u),u=n.originalColumn,null!=n.name&&(r=this._names.indexOf(n.name),e+=o.encode(r-c),c=r)),p+=e}return p},t.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=i.relative(n,e));var r=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},t.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},t.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=t},function(e,n,r){function t(e){return e<0?(-e<<1)+1:(e<<1)+0}function o(e){var n=1===(1&e),r=e>>1;return n?-r:r}var i=r(3),s=5,a=1<>>=s,o>0&&(n|=l),r+=i.encode(n);while(o>0);return r},n.decode=function(e,n,r){var t,a,c=e.length,g=0,p=0;do{if(n>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(a=i.decode(e.charCodeAt(n++)),a===-1)throw new Error("Invalid base64 digit: "+e.charAt(n-1));t=!!(a&l),a&=u,g+=a<=0;c--)s=u[c],"."===s?u.splice(c,1):".."===s?l++:l>0&&(""===s?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return r=u.join("/"),""===r&&(r=a?"/":"."),i?(i.path=r,o(i)):r}function s(e,n){""===e&&(e="."),""===n&&(n=".");var r=t(n),s=t(e);if(s&&(e=s.path||"/"),r&&!r.scheme)return s&&(r.scheme=s.scheme),o(r);if(r||n.match(y))return n;if(s&&!s.host&&!s.path)return s.host=n,o(s);var a="/"===n.charAt(0)?n:i(e.replace(/\/+$/,"")+"/"+n);return s?(s.path=a,o(s)):a}function a(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==n.indexOf(e+"/");){var t=e.lastIndexOf("/");if(t<0)return n;if(e=e.slice(0,t),e.match(/^([^\/]+:\/)?\/*$/))return n;++r}return Array(r+1).join("../")+n.substr(e.length+1)}function u(e){return e}function l(e){return g(e)?"$"+e:e}function c(e){return g(e)?e.slice(1):e}function g(e){if(!e)return!1;var n=e.length;if(n<9)return!1;if(95!==e.charCodeAt(n-1)||95!==e.charCodeAt(n-2)||111!==e.charCodeAt(n-3)||116!==e.charCodeAt(n-4)||111!==e.charCodeAt(n-5)||114!==e.charCodeAt(n-6)||112!==e.charCodeAt(n-7)||95!==e.charCodeAt(n-8)||95!==e.charCodeAt(n-9))return!1;for(var r=n-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function p(e,n,r){var t=f(e.source,n.source);return 0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t||r?t:(t=e.generatedColumn-n.generatedColumn,0!==t?t:(t=e.generatedLine-n.generatedLine,0!==t?t:f(e.name,n.name)))))}function h(e,n,r){var t=e.generatedLine-n.generatedLine;return 0!==t?t:(t=e.generatedColumn-n.generatedColumn,0!==t||r?t:(t=f(e.source,n.source),0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t?t:f(e.name,n.name)))))}function f(e,n){return e===n?0:null===e?1:null===n?-1:e>n?1:-1}function d(e,n){var r=e.generatedLine-n.generatedLine;return 0!==r?r:(r=e.generatedColumn-n.generatedColumn,0!==r?r:(r=f(e.source,n.source),0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r?r:f(e.name,n.name)))))}function m(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))}function _(e,n,r){if(n=n||"",e&&("/"!==e[e.length-1]&&"/"!==n[0]&&(e+="/"),n=e+n),r){var a=t(r);if(!a)throw new Error("sourceMapURL could not be parsed");if(a.path){var u=a.path.lastIndexOf("/");u>=0&&(a.path=a.path.substring(0,u+1))}n=s(o(a),n)}return i(n)}n.getArg=r;var v=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,y=/^data:.+\,.+$/;n.urlParse=t,n.urlGenerate=o,n.normalize=i,n.join=s,n.isAbsolute=function(e){return"/"===e.charAt(0)||v.test(e)},n.relative=a;var C=function(){var e=Object.create(null);return!("__proto__"in e)}();n.toSetString=C?u:l,n.fromSetString=C?u:c,n.compareByOriginalPositions=p,n.compareByGeneratedPositionsDeflated=h,n.compareByGeneratedPositionsInflated=d,n.parseSourceMapInput=m,n.computeSourceURL=_},function(e,n,r){function t(){this._array=[],this._set=s?new Map:Object.create(null)}var o=r(4),i=Object.prototype.hasOwnProperty,s="undefined"!=typeof Map;t.fromArray=function(e,n){for(var r=new t,o=0,i=e.length;o=0)return n}else{var r=o.toSetString(e);if(i.call(this._set,r))return this._set[r]}throw new Error('"'+e+'" is not in the set.')},t.prototype.at=function(e){if(e>=0&&er||t==r&&s>=o||i.compareByGeneratedPositionsInflated(e,n)<=0}function o(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=r(4);o.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},o.prototype.add=function(e){t(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},o.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=o},function(e,n,r){function t(e,n){var r=e;return"string"==typeof e&&(r=a.parseSourceMapInput(e)),null!=r.sections?new s(r,n):new o(r,n)}function o(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var t=a.getArg(r,"version"),o=a.getArg(r,"sources"),i=a.getArg(r,"names",[]),s=a.getArg(r,"sourceRoot",null),u=a.getArg(r,"sourcesContent",null),c=a.getArg(r,"mappings"),g=a.getArg(r,"file",null);if(t!=this._version)throw new Error("Unsupported version: "+t);s&&(s=a.normalize(s)),o=o.map(String).map(a.normalize).map(function(e){return s&&a.isAbsolute(s)&&a.isAbsolute(e)?a.relative(s,e):e}),this._names=l.fromArray(i.map(String),!0),this._sources=l.fromArray(o,!0),this._absoluteSources=this._sources.toArray().map(function(e){return a.computeSourceURL(s,e,n)}),this.sourceRoot=s,this.sourcesContent=u,this._mappings=c,this._sourceMapURL=n,this.file=g}function i(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function s(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var o=a.getArg(r,"version"),i=a.getArg(r,"sections");if(o!=this._version)throw new Error("Unsupported version: "+o);this._sources=new l,this._names=new l;var s={line:-1,column:0};this._sections=i.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var r=a.getArg(e,"offset"),o=a.getArg(r,"line"),i=a.getArg(r,"column");if(o=0){var i=this._originalMappings[o];if(void 0===e.column)for(var s=i.originalLine;i&&i.originalLine===s;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var l=i.originalColumn;i&&i.originalLine===n&&i.originalColumn==l;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return t},n.SourceMapConsumer=t,o.prototype=Object.create(t.prototype),o.prototype.consumer=t,o.prototype._findSourceIndex=function(e){var n=e;if(null!=this.sourceRoot&&(n=a.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);var r;for(r=0;r1&&(r.source=d+o[1],d+=o[1],r.originalLine=h+o[2],h=r.originalLine,r.originalLine+=1,r.originalColumn=f+o[3],f=r.originalColumn,o.length>4&&(r.name=m+o[4],m+=o[4])),A.push(r),"number"==typeof r.originalLine&&S.push(r)}g(A,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=A,g(S,a.compareByOriginalPositions),this.__originalMappings=S},o.prototype._findMapping=function(e,n,r,t,o,i){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[t]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[t]);return u.search(e,n,o,i)},o.prototype.computeColumnSpans=function(){for(var e=0;e=0){var o=this._generatedMappings[r];if(o.generatedLine===n.generatedLine){var i=a.getArg(o,"source",null);null!==i&&(i=this._sources.at(i),i=a.computeSourceURL(this.sourceRoot,i,this._sourceMapURL));var s=a.getArg(o,"name",null);return null!==s&&(s=this._names.at(s)),{source:i,line:a.getArg(o,"originalLine",null),column:a.getArg(o,"originalColumn",null),name:s}}}return{source:null,line:null,column:null,name:null}},o.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},o.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;var r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];var t=e;null!=this.sourceRoot&&(t=a.relative(this.sourceRoot,t));var o;if(null!=this.sourceRoot&&(o=a.urlParse(this.sourceRoot))){var i=t.replace(/^file:\/\//,"");if("file"==o.scheme&&this._sources.has(i))return this.sourcesContent[this._sources.indexOf(i)];if((!o.path||"/"==o.path)&&this._sources.has("/"+t))return this.sourcesContent[this._sources.indexOf("/"+t)]}if(n)return null;throw new Error('"'+t+'" is not in the SourceMap.')},o.prototype.generatedPositionFor=function(e){var n=a.getArg(e,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};var r={source:n,originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},o=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",t.GREATEST_LOWER_BOUND));if(o>=0){var i=this._originalMappings[o];if(i.source===r.source)return{line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=o,s.prototype=Object.create(t.prototype),s.prototype.constructor=t,s.prototype._version=3,Object.defineProperty(s.prototype,"sources",{get:function(){for(var e=[],n=0;n0?t-u>1?r(u,t,o,i,s,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,o,i,s,a):a==n.LEAST_UPPER_BOUND?u:e<0?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,o,i){if(0===t.length)return-1;var s=r(-1,t.length,e,t,o,i||n.GREATEST_LOWER_BOUND);if(s<0)return-1;for(;s-1>=0&&0===o(t[s],t[s-1],!0);)--s;return s}},function(e,n){function r(e,n,r){var t=e[n];e[n]=e[r],e[r]=t}function t(e,n){return Math.round(e+Math.random()*(n-e))}function o(e,n,i,s){if(i=0;n--)this.prepend(e[n]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},t.prototype.walk=function(e){for(var n,r=0,t=this.children.length;r0){for(n=[],r=0;r 0 && aGenerated.column >= 0\n\t && !aOriginal && !aSource && !aName) {\n\t // Case 1.\n\t return;\n\t }\n\t else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n\t && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n\t && aGenerated.line > 0 && aGenerated.column >= 0\n\t && aOriginal.line > 0 && aOriginal.column >= 0\n\t && aSource) {\n\t // Cases 2 and 3.\n\t return;\n\t }\n\t else {\n\t throw new Error('Invalid mapping: ' + JSON.stringify({\n\t generated: aGenerated,\n\t source: aSource,\n\t original: aOriginal,\n\t name: aName\n\t }));\n\t }\n\t };\n\t\n\t/**\n\t * Serialize the accumulated mappings in to the stream of base 64 VLQs\n\t * specified by the source map format.\n\t */\n\tSourceMapGenerator.prototype._serializeMappings =\n\t function SourceMapGenerator_serializeMappings() {\n\t var previousGeneratedColumn = 0;\n\t var previousGeneratedLine = 1;\n\t var previousOriginalColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousName = 0;\n\t var previousSource = 0;\n\t var result = '';\n\t var next;\n\t var mapping;\n\t var nameIdx;\n\t var sourceIdx;\n\t\n\t var mappings = this._mappings.toArray();\n\t for (var i = 0, len = mappings.length; i < len; i++) {\n\t mapping = mappings[i];\n\t next = ''\n\t\n\t if (mapping.generatedLine !== previousGeneratedLine) {\n\t previousGeneratedColumn = 0;\n\t while (mapping.generatedLine !== previousGeneratedLine) {\n\t next += ';';\n\t previousGeneratedLine++;\n\t }\n\t }\n\t else {\n\t if (i > 0) {\n\t if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n\t continue;\n\t }\n\t next += ',';\n\t }\n\t }\n\t\n\t next += base64VLQ.encode(mapping.generatedColumn\n\t - previousGeneratedColumn);\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (mapping.source != null) {\n\t sourceIdx = this._sources.indexOf(mapping.source);\n\t next += base64VLQ.encode(sourceIdx - previousSource);\n\t previousSource = sourceIdx;\n\t\n\t // lines are stored 0-based in SourceMap spec version 3\n\t next += base64VLQ.encode(mapping.originalLine - 1\n\t - previousOriginalLine);\n\t previousOriginalLine = mapping.originalLine - 1;\n\t\n\t next += base64VLQ.encode(mapping.originalColumn\n\t - previousOriginalColumn);\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (mapping.name != null) {\n\t nameIdx = this._names.indexOf(mapping.name);\n\t next += base64VLQ.encode(nameIdx - previousName);\n\t previousName = nameIdx;\n\t }\n\t }\n\t\n\t result += next;\n\t }\n\t\n\t return result;\n\t };\n\t\n\tSourceMapGenerator.prototype._generateSourcesContent =\n\t function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n\t return aSources.map(function (source) {\n\t if (!this._sourcesContents) {\n\t return null;\n\t }\n\t if (aSourceRoot != null) {\n\t source = util.relative(aSourceRoot, source);\n\t }\n\t var key = util.toSetString(source);\n\t return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n\t ? this._sourcesContents[key]\n\t : null;\n\t }, this);\n\t };\n\t\n\t/**\n\t * Externalize the source map.\n\t */\n\tSourceMapGenerator.prototype.toJSON =\n\t function SourceMapGenerator_toJSON() {\n\t var map = {\n\t version: this._version,\n\t sources: this._sources.toArray(),\n\t names: this._names.toArray(),\n\t mappings: this._serializeMappings()\n\t };\n\t if (this._file != null) {\n\t map.file = this._file;\n\t }\n\t if (this._sourceRoot != null) {\n\t map.sourceRoot = this._sourceRoot;\n\t }\n\t if (this._sourcesContents) {\n\t map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n\t }\n\t\n\t return map;\n\t };\n\t\n\t/**\n\t * Render the source map being generated to a string.\n\t */\n\tSourceMapGenerator.prototype.toString =\n\t function SourceMapGenerator_toString() {\n\t return JSON.stringify(this.toJSON());\n\t };\n\t\n\texports.SourceMapGenerator = SourceMapGenerator;\n\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t *\n\t * Based on the Base 64 VLQ implementation in Closure Compiler:\n\t * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n\t *\n\t * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n\t * Redistribution and use in source and binary forms, with or without\n\t * modification, are permitted provided that the following conditions are\n\t * met:\n\t *\n\t * * Redistributions of source code must retain the above copyright\n\t * notice, this list of conditions and the following disclaimer.\n\t * * Redistributions in binary form must reproduce the above\n\t * copyright notice, this list of conditions and the following\n\t * disclaimer in the documentation and/or other materials provided\n\t * with the distribution.\n\t * * Neither the name of Google Inc. nor the names of its\n\t * contributors may be used to endorse or promote products derived\n\t * from this software without specific prior written permission.\n\t *\n\t * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\t * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\t * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\t * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\t * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\t * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\t * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\t * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\t * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\t * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\t */\n\t\n\tvar base64 = __webpack_require__(3);\n\t\n\t// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n\t// length quantities we use in the source map spec, the first bit is the sign,\n\t// the next four bits are the actual value, and the 6th bit is the\n\t// continuation bit. The continuation bit tells us whether there are more\n\t// digits in this value following this digit.\n\t//\n\t// Continuation\n\t// | Sign\n\t// | |\n\t// V V\n\t// 101011\n\t\n\tvar VLQ_BASE_SHIFT = 5;\n\t\n\t// binary: 100000\n\tvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\t\n\t// binary: 011111\n\tvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\t\n\t// binary: 100000\n\tvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\t\n\t/**\n\t * Converts from a two-complement value to a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n\t * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n\t */\n\tfunction toVLQSigned(aValue) {\n\t return aValue < 0\n\t ? ((-aValue) << 1) + 1\n\t : (aValue << 1) + 0;\n\t}\n\t\n\t/**\n\t * Converts to a two-complement value from a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n\t * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n\t */\n\tfunction fromVLQSigned(aValue) {\n\t var isNegative = (aValue & 1) === 1;\n\t var shifted = aValue >> 1;\n\t return isNegative\n\t ? -shifted\n\t : shifted;\n\t}\n\t\n\t/**\n\t * Returns the base 64 VLQ encoded value.\n\t */\n\texports.encode = function base64VLQ_encode(aValue) {\n\t var encoded = \"\";\n\t var digit;\n\t\n\t var vlq = toVLQSigned(aValue);\n\t\n\t do {\n\t digit = vlq & VLQ_BASE_MASK;\n\t vlq >>>= VLQ_BASE_SHIFT;\n\t if (vlq > 0) {\n\t // There are still more digits in this value, so we must make sure the\n\t // continuation bit is marked.\n\t digit |= VLQ_CONTINUATION_BIT;\n\t }\n\t encoded += base64.encode(digit);\n\t } while (vlq > 0);\n\t\n\t return encoded;\n\t};\n\t\n\t/**\n\t * Decodes the next base 64 VLQ value from the given string and returns the\n\t * value and the rest of the string via the out parameter.\n\t */\n\texports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n\t var strLen = aStr.length;\n\t var result = 0;\n\t var shift = 0;\n\t var continuation, digit;\n\t\n\t do {\n\t if (aIndex >= strLen) {\n\t throw new Error(\"Expected more digits in base 64 VLQ value.\");\n\t }\n\t\n\t digit = base64.decode(aStr.charCodeAt(aIndex++));\n\t if (digit === -1) {\n\t throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n\t }\n\t\n\t continuation = !!(digit & VLQ_CONTINUATION_BIT);\n\t digit &= VLQ_BASE_MASK;\n\t result = result + (digit << shift);\n\t shift += VLQ_BASE_SHIFT;\n\t } while (continuation);\n\t\n\t aOutParam.value = fromVLQSigned(result);\n\t aOutParam.rest = aIndex;\n\t};\n\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\t\n\t/**\n\t * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n\t */\n\texports.encode = function (number) {\n\t if (0 <= number && number < intToCharMap.length) {\n\t return intToCharMap[number];\n\t }\n\t throw new TypeError(\"Must be between 0 and 63: \" + number);\n\t};\n\t\n\t/**\n\t * Decode a single base 64 character code digit to an integer. Returns -1 on\n\t * failure.\n\t */\n\texports.decode = function (charCode) {\n\t var bigA = 65; // 'A'\n\t var bigZ = 90; // 'Z'\n\t\n\t var littleA = 97; // 'a'\n\t var littleZ = 122; // 'z'\n\t\n\t var zero = 48; // '0'\n\t var nine = 57; // '9'\n\t\n\t var plus = 43; // '+'\n\t var slash = 47; // '/'\n\t\n\t var littleOffset = 26;\n\t var numberOffset = 52;\n\t\n\t // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t if (bigA <= charCode && charCode <= bigZ) {\n\t return (charCode - bigA);\n\t }\n\t\n\t // 26 - 51: abcdefghijklmnopqrstuvwxyz\n\t if (littleA <= charCode && charCode <= littleZ) {\n\t return (charCode - littleA + littleOffset);\n\t }\n\t\n\t // 52 - 61: 0123456789\n\t if (zero <= charCode && charCode <= nine) {\n\t return (charCode - zero + numberOffset);\n\t }\n\t\n\t // 62: +\n\t if (charCode == plus) {\n\t return 62;\n\t }\n\t\n\t // 63: /\n\t if (charCode == slash) {\n\t return 63;\n\t }\n\t\n\t // Invalid base64 digit.\n\t return -1;\n\t};\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t/**\n\t * This is a helper function for getting values from parameter/options\n\t * objects.\n\t *\n\t * @param args The object we are extracting values from\n\t * @param name The name of the property we are getting.\n\t * @param defaultValue An optional value to return if the property is missing\n\t * from the object. If this is not specified and the property is missing, an\n\t * error will be thrown.\n\t */\n\tfunction getArg(aArgs, aName, aDefaultValue) {\n\t if (aName in aArgs) {\n\t return aArgs[aName];\n\t } else if (arguments.length === 3) {\n\t return aDefaultValue;\n\t } else {\n\t throw new Error('\"' + aName + '\" is a required argument.');\n\t }\n\t}\n\texports.getArg = getArg;\n\t\n\tvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\n\tvar dataUrlRegexp = /^data:.+\\,.+$/;\n\t\n\tfunction urlParse(aUrl) {\n\t var match = aUrl.match(urlRegexp);\n\t if (!match) {\n\t return null;\n\t }\n\t return {\n\t scheme: match[1],\n\t auth: match[2],\n\t host: match[3],\n\t port: match[4],\n\t path: match[5]\n\t };\n\t}\n\texports.urlParse = urlParse;\n\t\n\tfunction urlGenerate(aParsedUrl) {\n\t var url = '';\n\t if (aParsedUrl.scheme) {\n\t url += aParsedUrl.scheme + ':';\n\t }\n\t url += '//';\n\t if (aParsedUrl.auth) {\n\t url += aParsedUrl.auth + '@';\n\t }\n\t if (aParsedUrl.host) {\n\t url += aParsedUrl.host;\n\t }\n\t if (aParsedUrl.port) {\n\t url += \":\" + aParsedUrl.port\n\t }\n\t if (aParsedUrl.path) {\n\t url += aParsedUrl.path;\n\t }\n\t return url;\n\t}\n\texports.urlGenerate = urlGenerate;\n\t\n\t/**\n\t * Normalizes a path, or the path portion of a URL:\n\t *\n\t * - Replaces consecutive slashes with one slash.\n\t * - Removes unnecessary '.' parts.\n\t * - Removes unnecessary '/..' parts.\n\t *\n\t * Based on code in the Node.js 'path' core module.\n\t *\n\t * @param aPath The path or url to normalize.\n\t */\n\tfunction normalize(aPath) {\n\t var path = aPath;\n\t var url = urlParse(aPath);\n\t if (url) {\n\t if (!url.path) {\n\t return aPath;\n\t }\n\t path = url.path;\n\t }\n\t var isAbsolute = exports.isAbsolute(path);\n\t\n\t var parts = path.split(/\\/+/);\n\t for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n\t part = parts[i];\n\t if (part === '.') {\n\t parts.splice(i, 1);\n\t } else if (part === '..') {\n\t up++;\n\t } else if (up > 0) {\n\t if (part === '') {\n\t // The first part is blank if the path is absolute. Trying to go\n\t // above the root is a no-op. Therefore we can remove all '..' parts\n\t // directly after the root.\n\t parts.splice(i + 1, up);\n\t up = 0;\n\t } else {\n\t parts.splice(i, 2);\n\t up--;\n\t }\n\t }\n\t }\n\t path = parts.join('/');\n\t\n\t if (path === '') {\n\t path = isAbsolute ? '/' : '.';\n\t }\n\t\n\t if (url) {\n\t url.path = path;\n\t return urlGenerate(url);\n\t }\n\t return path;\n\t}\n\texports.normalize = normalize;\n\t\n\t/**\n\t * Joins two paths/URLs.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be joined with the root.\n\t *\n\t * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n\t * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n\t * first.\n\t * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n\t * is updated with the result and aRoot is returned. Otherwise the result\n\t * is returned.\n\t * - If aPath is absolute, the result is aPath.\n\t * - Otherwise the two paths are joined with a slash.\n\t * - Joining for example 'http://' and 'www.example.com' is also supported.\n\t */\n\tfunction join(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t if (aPath === \"\") {\n\t aPath = \".\";\n\t }\n\t var aPathUrl = urlParse(aPath);\n\t var aRootUrl = urlParse(aRoot);\n\t if (aRootUrl) {\n\t aRoot = aRootUrl.path || '/';\n\t }\n\t\n\t // `join(foo, '//www.example.org')`\n\t if (aPathUrl && !aPathUrl.scheme) {\n\t if (aRootUrl) {\n\t aPathUrl.scheme = aRootUrl.scheme;\n\t }\n\t return urlGenerate(aPathUrl);\n\t }\n\t\n\t if (aPathUrl || aPath.match(dataUrlRegexp)) {\n\t return aPath;\n\t }\n\t\n\t // `join('http://', 'www.example.com')`\n\t if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n\t aRootUrl.host = aPath;\n\t return urlGenerate(aRootUrl);\n\t }\n\t\n\t var joined = aPath.charAt(0) === '/'\n\t ? aPath\n\t : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\t\n\t if (aRootUrl) {\n\t aRootUrl.path = joined;\n\t return urlGenerate(aRootUrl);\n\t }\n\t return joined;\n\t}\n\texports.join = join;\n\t\n\texports.isAbsolute = function (aPath) {\n\t return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n\t};\n\t\n\t/**\n\t * Make a path relative to a URL or another path.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be made relative to aRoot.\n\t */\n\tfunction relative(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t\n\t aRoot = aRoot.replace(/\\/$/, '');\n\t\n\t // It is possible for the path to be above the root. In this case, simply\n\t // checking whether the root is a prefix of the path won't work. Instead, we\n\t // need to remove components from the root one by one, until either we find\n\t // a prefix that fits, or we run out of components to remove.\n\t var level = 0;\n\t while (aPath.indexOf(aRoot + '/') !== 0) {\n\t var index = aRoot.lastIndexOf(\"/\");\n\t if (index < 0) {\n\t return aPath;\n\t }\n\t\n\t // If the only part of the root that is left is the scheme (i.e. http://,\n\t // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n\t // have exhausted all components, so the path is not relative to the root.\n\t aRoot = aRoot.slice(0, index);\n\t if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n\t return aPath;\n\t }\n\t\n\t ++level;\n\t }\n\t\n\t // Make sure we add a \"../\" for each component we removed from the root.\n\t return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n\t}\n\texports.relative = relative;\n\t\n\tvar supportsNullProto = (function () {\n\t var obj = Object.create(null);\n\t return !('__proto__' in obj);\n\t}());\n\t\n\tfunction identity (s) {\n\t return s;\n\t}\n\t\n\t/**\n\t * Because behavior goes wacky when you set `__proto__` on objects, we\n\t * have to prefix all the strings in our set with an arbitrary character.\n\t *\n\t * See https://github.com/mozilla/source-map/pull/31 and\n\t * https://github.com/mozilla/source-map/issues/30\n\t *\n\t * @param String aStr\n\t */\n\tfunction toSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return '$' + aStr;\n\t }\n\t\n\t return aStr;\n\t}\n\texports.toSetString = supportsNullProto ? identity : toSetString;\n\t\n\tfunction fromSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return aStr.slice(1);\n\t }\n\t\n\t return aStr;\n\t}\n\texports.fromSetString = supportsNullProto ? identity : fromSetString;\n\t\n\tfunction isProtoString(s) {\n\t if (!s) {\n\t return false;\n\t }\n\t\n\t var length = s.length;\n\t\n\t if (length < 9 /* \"__proto__\".length */) {\n\t return false;\n\t }\n\t\n\t if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n\t s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n\t s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n\t s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 9) !== 95 /* '_' */) {\n\t return false;\n\t }\n\t\n\t for (var i = length - 10; i >= 0; i--) {\n\t if (s.charCodeAt(i) !== 36 /* '$' */) {\n\t return false;\n\t }\n\t }\n\t\n\t return true;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings where the original positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same original source/line/column, but different generated\n\t * line and column the same. Useful when searching for a mapping with a\n\t * stubbed out mapping.\n\t */\n\tfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n\t var cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0 || onlyCompareOriginal) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByOriginalPositions = compareByOriginalPositions;\n\t\n\t/**\n\t * Comparator between two mappings with deflated source and name indices where\n\t * the generated positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same generated line and column, but different\n\t * source/name/original line and column the same. Useful when searching for a\n\t * mapping with a stubbed out mapping.\n\t */\n\tfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0 || onlyCompareGenerated) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\t\n\tfunction strcmp(aStr1, aStr2) {\n\t if (aStr1 === aStr2) {\n\t return 0;\n\t }\n\t\n\t if (aStr1 === null) {\n\t return 1; // aStr2 !== null\n\t }\n\t\n\t if (aStr2 === null) {\n\t return -1; // aStr1 !== null\n\t }\n\t\n\t if (aStr1 > aStr2) {\n\t return 1;\n\t }\n\t\n\t return -1;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings with inflated source and name strings where\n\t * the generated positions are compared.\n\t */\n\tfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\t\n\t/**\n\t * Strip any JSON XSSI avoidance prefix from the string (as documented\n\t * in the source maps specification), and then parse the string as\n\t * JSON.\n\t */\n\tfunction parseSourceMapInput(str) {\n\t return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n\t}\n\texports.parseSourceMapInput = parseSourceMapInput;\n\t\n\t/**\n\t * Compute the URL of a source given the the source root, the source's\n\t * URL, and the source map's URL.\n\t */\n\tfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n\t sourceURL = sourceURL || '';\n\t\n\t if (sourceRoot) {\n\t // This follows what Chrome does.\n\t if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n\t sourceRoot += '/';\n\t }\n\t // The spec says:\n\t // Line 4: An optional source root, useful for relocating source\n\t // files on a server or removing repeated values in the\n\t // “sources” entry. This value is prepended to the individual\n\t // entries in the “source” field.\n\t sourceURL = sourceRoot + sourceURL;\n\t }\n\t\n\t // Historically, SourceMapConsumer did not take the sourceMapURL as\n\t // a parameter. This mode is still somewhat supported, which is why\n\t // this code block is conditional. However, it's preferable to pass\n\t // the source map URL to SourceMapConsumer, so that this function\n\t // can implement the source URL resolution algorithm as outlined in\n\t // the spec. This block is basically the equivalent of:\n\t // new URL(sourceURL, sourceMapURL).toString()\n\t // ... except it avoids using URL, which wasn't available in the\n\t // older releases of node still supported by this library.\n\t //\n\t // The spec says:\n\t // If the sources are not absolute URLs after prepending of the\n\t // “sourceRoot”, the sources are resolved relative to the\n\t // SourceMap (like resolving script src in a html document).\n\t if (sourceMapURL) {\n\t var parsed = urlParse(sourceMapURL);\n\t if (!parsed) {\n\t throw new Error(\"sourceMapURL could not be parsed\");\n\t }\n\t if (parsed.path) {\n\t // Strip the last path component, but keep the \"/\".\n\t var index = parsed.path.lastIndexOf('/');\n\t if (index >= 0) {\n\t parsed.path = parsed.path.substring(0, index + 1);\n\t }\n\t }\n\t sourceURL = join(urlGenerate(parsed), sourceURL);\n\t }\n\t\n\t return normalize(sourceURL);\n\t}\n\texports.computeSourceURL = computeSourceURL;\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar has = Object.prototype.hasOwnProperty;\n\tvar hasNativeMap = typeof Map !== \"undefined\";\n\t\n\t/**\n\t * A data structure which is a combination of an array and a set. Adding a new\n\t * member is O(1), testing for membership is O(1), and finding the index of an\n\t * element is O(1). Removing elements from the set is not supported. Only\n\t * strings are supported for membership.\n\t */\n\tfunction ArraySet() {\n\t this._array = [];\n\t this._set = hasNativeMap ? new Map() : Object.create(null);\n\t}\n\t\n\t/**\n\t * Static method for creating ArraySet instances from an existing array.\n\t */\n\tArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n\t var set = new ArraySet();\n\t for (var i = 0, len = aArray.length; i < len; i++) {\n\t set.add(aArray[i], aAllowDuplicates);\n\t }\n\t return set;\n\t};\n\t\n\t/**\n\t * Return how many unique items are in this ArraySet. If duplicates have been\n\t * added, than those do not count towards the size.\n\t *\n\t * @returns Number\n\t */\n\tArraySet.prototype.size = function ArraySet_size() {\n\t return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n\t};\n\t\n\t/**\n\t * Add the given string to this set.\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n\t var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n\t var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n\t var idx = this._array.length;\n\t if (!isDuplicate || aAllowDuplicates) {\n\t this._array.push(aStr);\n\t }\n\t if (!isDuplicate) {\n\t if (hasNativeMap) {\n\t this._set.set(aStr, idx);\n\t } else {\n\t this._set[sStr] = idx;\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Is the given string a member of this set?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.has = function ArraySet_has(aStr) {\n\t if (hasNativeMap) {\n\t return this._set.has(aStr);\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t return has.call(this._set, sStr);\n\t }\n\t};\n\t\n\t/**\n\t * What is the index of the given string in the array?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n\t if (hasNativeMap) {\n\t var idx = this._set.get(aStr);\n\t if (idx >= 0) {\n\t return idx;\n\t }\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t if (has.call(this._set, sStr)) {\n\t return this._set[sStr];\n\t }\n\t }\n\t\n\t throw new Error('\"' + aStr + '\" is not in the set.');\n\t};\n\t\n\t/**\n\t * What is the element at the given index?\n\t *\n\t * @param Number aIdx\n\t */\n\tArraySet.prototype.at = function ArraySet_at(aIdx) {\n\t if (aIdx >= 0 && aIdx < this._array.length) {\n\t return this._array[aIdx];\n\t }\n\t throw new Error('No element indexed by ' + aIdx);\n\t};\n\t\n\t/**\n\t * Returns the array representation of this set (which has the proper indices\n\t * indicated by indexOf). Note that this is a copy of the internal array used\n\t * for storing the members so that no one can mess with internal state.\n\t */\n\tArraySet.prototype.toArray = function ArraySet_toArray() {\n\t return this._array.slice();\n\t};\n\t\n\texports.ArraySet = ArraySet;\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2014 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\t\n\t/**\n\t * Determine whether mappingB is after mappingA with respect to generated\n\t * position.\n\t */\n\tfunction generatedPositionAfter(mappingA, mappingB) {\n\t // Optimized for most common case\n\t var lineA = mappingA.generatedLine;\n\t var lineB = mappingB.generatedLine;\n\t var columnA = mappingA.generatedColumn;\n\t var columnB = mappingB.generatedColumn;\n\t return lineB > lineA || lineB == lineA && columnB >= columnA ||\n\t util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n\t}\n\t\n\t/**\n\t * A data structure to provide a sorted view of accumulated mappings in a\n\t * performance conscious manner. It trades a neglibable overhead in general\n\t * case for a large speedup in case of mappings being added in order.\n\t */\n\tfunction MappingList() {\n\t this._array = [];\n\t this._sorted = true;\n\t // Serves as infimum\n\t this._last = {generatedLine: -1, generatedColumn: 0};\n\t}\n\t\n\t/**\n\t * Iterate through internal items. This method takes the same arguments that\n\t * `Array.prototype.forEach` takes.\n\t *\n\t * NOTE: The order of the mappings is NOT guaranteed.\n\t */\n\tMappingList.prototype.unsortedForEach =\n\t function MappingList_forEach(aCallback, aThisArg) {\n\t this._array.forEach(aCallback, aThisArg);\n\t };\n\t\n\t/**\n\t * Add the given source mapping.\n\t *\n\t * @param Object aMapping\n\t */\n\tMappingList.prototype.add = function MappingList_add(aMapping) {\n\t if (generatedPositionAfter(this._last, aMapping)) {\n\t this._last = aMapping;\n\t this._array.push(aMapping);\n\t } else {\n\t this._sorted = false;\n\t this._array.push(aMapping);\n\t }\n\t};\n\t\n\t/**\n\t * Returns the flat, sorted array of mappings. The mappings are sorted by\n\t * generated position.\n\t *\n\t * WARNING: This method returns internal data without copying, for\n\t * performance. The return value must NOT be mutated, and should be treated as\n\t * an immutable borrow. If you want to take ownership, you must make your own\n\t * copy.\n\t */\n\tMappingList.prototype.toArray = function MappingList_toArray() {\n\t if (!this._sorted) {\n\t this._array.sort(util.compareByGeneratedPositionsInflated);\n\t this._sorted = true;\n\t }\n\t return this._array;\n\t};\n\t\n\texports.MappingList = MappingList;\n\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar binarySearch = __webpack_require__(8);\n\tvar ArraySet = __webpack_require__(5).ArraySet;\n\tvar base64VLQ = __webpack_require__(2);\n\tvar quickSort = __webpack_require__(9).quickSort;\n\t\n\tfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t return sourceMap.sections != null\n\t ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n\t : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n\t}\n\t\n\tSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n\t return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n\t}\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tSourceMapConsumer.prototype._version = 3;\n\t\n\t// `__generatedMappings` and `__originalMappings` are arrays that hold the\n\t// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n\t// are lazily instantiated, accessed via the `_generatedMappings` and\n\t// `_originalMappings` getters respectively, and we only parse the mappings\n\t// and create these arrays once queried for a source location. We jump through\n\t// these hoops because there can be many thousands of mappings, and parsing\n\t// them is expensive, so we only want to do it if we must.\n\t//\n\t// Each object in the arrays is of the form:\n\t//\n\t// {\n\t// generatedLine: The line number in the generated code,\n\t// generatedColumn: The column number in the generated code,\n\t// source: The path to the original source file that generated this\n\t// chunk of code,\n\t// originalLine: The line number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// originalColumn: The column number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// name: The name of the original symbol which generated this chunk of\n\t// code.\n\t// }\n\t//\n\t// All properties except for `generatedLine` and `generatedColumn` can be\n\t// `null`.\n\t//\n\t// `_generatedMappings` is ordered by the generated positions.\n\t//\n\t// `_originalMappings` is ordered by the original positions.\n\t\n\tSourceMapConsumer.prototype.__generatedMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__generatedMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__generatedMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype.__originalMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__originalMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__originalMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype._charIsMappingSeparator =\n\t function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n\t var c = aStr.charAt(index);\n\t return c === \";\" || c === \",\";\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t throw new Error(\"Subclasses must implement _parseMappings\");\n\t };\n\t\n\tSourceMapConsumer.GENERATED_ORDER = 1;\n\tSourceMapConsumer.ORIGINAL_ORDER = 2;\n\t\n\tSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\n\tSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Iterate over each mapping between an original source/line/column and a\n\t * generated line/column in this source map.\n\t *\n\t * @param Function aCallback\n\t * The function that is called with each mapping.\n\t * @param Object aContext\n\t * Optional. If specified, this object will be the value of `this` every\n\t * time that `aCallback` is called.\n\t * @param aOrder\n\t * Either `SourceMapConsumer.GENERATED_ORDER` or\n\t * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n\t * iterate over the mappings sorted by the generated file's line/column\n\t * order or the original's source/line/column order, respectively. Defaults to\n\t * `SourceMapConsumer.GENERATED_ORDER`.\n\t */\n\tSourceMapConsumer.prototype.eachMapping =\n\t function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n\t var context = aContext || null;\n\t var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\t\n\t var mappings;\n\t switch (order) {\n\t case SourceMapConsumer.GENERATED_ORDER:\n\t mappings = this._generatedMappings;\n\t break;\n\t case SourceMapConsumer.ORIGINAL_ORDER:\n\t mappings = this._originalMappings;\n\t break;\n\t default:\n\t throw new Error(\"Unknown order of iteration.\");\n\t }\n\t\n\t var sourceRoot = this.sourceRoot;\n\t mappings.map(function (mapping) {\n\t var source = mapping.source === null ? null : this._sources.at(mapping.source);\n\t source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n\t return {\n\t source: source,\n\t generatedLine: mapping.generatedLine,\n\t generatedColumn: mapping.generatedColumn,\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: mapping.name === null ? null : this._names.at(mapping.name)\n\t };\n\t }, this).forEach(aCallback, context);\n\t };\n\t\n\t/**\n\t * Returns all generated line and column information for the original source,\n\t * line, and column provided. If no column is provided, returns all mappings\n\t * corresponding to a either the line we are searching for or the next\n\t * closest line that has any mappings. Otherwise, returns all mappings\n\t * corresponding to the given line and either the column we are searching for\n\t * or the next closest column that has any offsets.\n\t *\n\t * The only argument is an object with the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number is 1-based.\n\t * - column: Optional. the column number in the original source.\n\t * The column number is 0-based.\n\t *\n\t * and an array of objects is returned, each with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tSourceMapConsumer.prototype.allGeneratedPositionsFor =\n\t function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n\t var line = util.getArg(aArgs, 'line');\n\t\n\t // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n\t // returns the index of the closest mapping less than the needle. By\n\t // setting needle.originalColumn to 0, we thus find the last mapping for\n\t // the given line, provided such a mapping exists.\n\t var needle = {\n\t source: util.getArg(aArgs, 'source'),\n\t originalLine: line,\n\t originalColumn: util.getArg(aArgs, 'column', 0)\n\t };\n\t\n\t needle.source = this._findSourceIndex(needle.source);\n\t if (needle.source < 0) {\n\t return [];\n\t }\n\t\n\t var mappings = [];\n\t\n\t var index = this._findMapping(needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t binarySearch.LEAST_UPPER_BOUND);\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (aArgs.column === undefined) {\n\t var originalLine = mapping.originalLine;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we found. Since\n\t // mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we found.\n\t while (mapping && mapping.originalLine === originalLine) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t } else {\n\t var originalColumn = mapping.originalColumn;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we were searching for.\n\t // Since mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we are searching for.\n\t while (mapping &&\n\t mapping.originalLine === line &&\n\t mapping.originalColumn == originalColumn) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t }\n\t }\n\t\n\t return mappings;\n\t };\n\t\n\texports.SourceMapConsumer = SourceMapConsumer;\n\t\n\t/**\n\t * A BasicSourceMapConsumer instance represents a parsed source map which we can\n\t * query for information about the original file positions by giving it a file\n\t * position in the generated source.\n\t *\n\t * The first parameter is the raw source map (either as a JSON string, or\n\t * already parsed to an object). According to the spec, source maps have the\n\t * following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - sources: An array of URLs to the original source files.\n\t * - names: An array of identifiers which can be referrenced by individual mappings.\n\t * - sourceRoot: Optional. The URL root from which all sources are relative.\n\t * - sourcesContent: Optional. An array of contents of the original source files.\n\t * - mappings: A string of base64 VLQs which contain the actual mappings.\n\t * - file: Optional. The generated file this source map is associated with.\n\t *\n\t * Here is an example source map, taken from the source map spec[0]:\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"out.js\",\n\t * sourceRoot : \"\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AA,AB;;ABCDE;\"\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n\t */\n\tfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sources = util.getArg(sourceMap, 'sources');\n\t // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n\t // requires the array) to play nice here.\n\t var names = util.getArg(sourceMap, 'names', []);\n\t var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n\t var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n\t var mappings = util.getArg(sourceMap, 'mappings');\n\t var file = util.getArg(sourceMap, 'file', null);\n\t\n\t // Once again, Sass deviates from the spec and supplies the version as a\n\t // string rather than a number, so we use loose equality checking here.\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t if (sourceRoot) {\n\t sourceRoot = util.normalize(sourceRoot);\n\t }\n\t\n\t sources = sources\n\t .map(String)\n\t // Some source maps produce relative source paths like \"./foo.js\" instead of\n\t // \"foo.js\". Normalize these first so that future comparisons will succeed.\n\t // See bugzil.la/1090768.\n\t .map(util.normalize)\n\t // Always ensure that absolute sources are internally stored relative to\n\t // the source root, if the source root is absolute. Not doing this would\n\t // be particularly problematic when the source root is a prefix of the\n\t // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n\t .map(function (source) {\n\t return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n\t ? util.relative(sourceRoot, source)\n\t : source;\n\t });\n\t\n\t // Pass `true` below to allow duplicate names and sources. While source maps\n\t // are intended to be compressed and deduplicated, the TypeScript compiler\n\t // sometimes generates source maps with duplicates in them. See Github issue\n\t // #72 and bugzil.la/889492.\n\t this._names = ArraySet.fromArray(names.map(String), true);\n\t this._sources = ArraySet.fromArray(sources, true);\n\t\n\t this._absoluteSources = this._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t this.sourceRoot = sourceRoot;\n\t this.sourcesContent = sourcesContent;\n\t this._mappings = mappings;\n\t this._sourceMapURL = aSourceMapURL;\n\t this.file = file;\n\t}\n\t\n\tBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\t\n\t/**\n\t * Utility function to find the index of a source. Returns -1 if not\n\t * found.\n\t */\n\tBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t if (this._sources.has(relativeSource)) {\n\t return this._sources.indexOf(relativeSource);\n\t }\n\t\n\t // Maybe aSource is an absolute URL as returned by |sources|. In\n\t // this case we can't simply undo the transform.\n\t var i;\n\t for (i = 0; i < this._absoluteSources.length; ++i) {\n\t if (this._absoluteSources[i] == aSource) {\n\t return i;\n\t }\n\t }\n\t\n\t return -1;\n\t};\n\t\n\t/**\n\t * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n\t *\n\t * @param SourceMapGenerator aSourceMap\n\t * The source map that will be consumed.\n\t * @param String aSourceMapURL\n\t * The URL at which the source map can be found (optional)\n\t * @returns BasicSourceMapConsumer\n\t */\n\tBasicSourceMapConsumer.fromSourceMap =\n\t function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n\t var smc = Object.create(BasicSourceMapConsumer.prototype);\n\t\n\t var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n\t var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n\t smc.sourceRoot = aSourceMap._sourceRoot;\n\t smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n\t smc.sourceRoot);\n\t smc.file = aSourceMap._file;\n\t smc._sourceMapURL = aSourceMapURL;\n\t smc._absoluteSources = smc._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t // Because we are modifying the entries (by converting string sources and\n\t // names to indices into the sources and names ArraySets), we have to make\n\t // a copy of the entry or else bad things happen. Shared mutable state\n\t // strikes again! See github issue #191.\n\t\n\t var generatedMappings = aSourceMap._mappings.toArray().slice();\n\t var destGeneratedMappings = smc.__generatedMappings = [];\n\t var destOriginalMappings = smc.__originalMappings = [];\n\t\n\t for (var i = 0, length = generatedMappings.length; i < length; i++) {\n\t var srcMapping = generatedMappings[i];\n\t var destMapping = new Mapping;\n\t destMapping.generatedLine = srcMapping.generatedLine;\n\t destMapping.generatedColumn = srcMapping.generatedColumn;\n\t\n\t if (srcMapping.source) {\n\t destMapping.source = sources.indexOf(srcMapping.source);\n\t destMapping.originalLine = srcMapping.originalLine;\n\t destMapping.originalColumn = srcMapping.originalColumn;\n\t\n\t if (srcMapping.name) {\n\t destMapping.name = names.indexOf(srcMapping.name);\n\t }\n\t\n\t destOriginalMappings.push(destMapping);\n\t }\n\t\n\t destGeneratedMappings.push(destMapping);\n\t }\n\t\n\t quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\t\n\t return smc;\n\t };\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tBasicSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t return this._absoluteSources.slice();\n\t }\n\t});\n\t\n\t/**\n\t * Provide the JIT with a nice shape / hidden class.\n\t */\n\tfunction Mapping() {\n\t this.generatedLine = 0;\n\t this.generatedColumn = 0;\n\t this.source = null;\n\t this.originalLine = null;\n\t this.originalColumn = null;\n\t this.name = null;\n\t}\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tBasicSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t var generatedLine = 1;\n\t var previousGeneratedColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousOriginalColumn = 0;\n\t var previousSource = 0;\n\t var previousName = 0;\n\t var length = aStr.length;\n\t var index = 0;\n\t var cachedSegments = {};\n\t var temp = {};\n\t var originalMappings = [];\n\t var generatedMappings = [];\n\t var mapping, str, segment, end, value;\n\t\n\t while (index < length) {\n\t if (aStr.charAt(index) === ';') {\n\t generatedLine++;\n\t index++;\n\t previousGeneratedColumn = 0;\n\t }\n\t else if (aStr.charAt(index) === ',') {\n\t index++;\n\t }\n\t else {\n\t mapping = new Mapping();\n\t mapping.generatedLine = generatedLine;\n\t\n\t // Because each offset is encoded relative to the previous one,\n\t // many segments often have the same encoding. We can exploit this\n\t // fact by caching the parsed variable length fields of each segment,\n\t // allowing us to avoid a second parse if we encounter the same\n\t // segment again.\n\t for (end = index; end < length; end++) {\n\t if (this._charIsMappingSeparator(aStr, end)) {\n\t break;\n\t }\n\t }\n\t str = aStr.slice(index, end);\n\t\n\t segment = cachedSegments[str];\n\t if (segment) {\n\t index += str.length;\n\t } else {\n\t segment = [];\n\t while (index < end) {\n\t base64VLQ.decode(aStr, index, temp);\n\t value = temp.value;\n\t index = temp.rest;\n\t segment.push(value);\n\t }\n\t\n\t if (segment.length === 2) {\n\t throw new Error('Found a source, but no line and column');\n\t }\n\t\n\t if (segment.length === 3) {\n\t throw new Error('Found a source and line, but no column');\n\t }\n\t\n\t cachedSegments[str] = segment;\n\t }\n\t\n\t // Generated column.\n\t mapping.generatedColumn = previousGeneratedColumn + segment[0];\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (segment.length > 1) {\n\t // Original source.\n\t mapping.source = previousSource + segment[1];\n\t previousSource += segment[1];\n\t\n\t // Original line.\n\t mapping.originalLine = previousOriginalLine + segment[2];\n\t previousOriginalLine = mapping.originalLine;\n\t // Lines are stored 0-based\n\t mapping.originalLine += 1;\n\t\n\t // Original column.\n\t mapping.originalColumn = previousOriginalColumn + segment[3];\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (segment.length > 4) {\n\t // Original name.\n\t mapping.name = previousName + segment[4];\n\t previousName += segment[4];\n\t }\n\t }\n\t\n\t generatedMappings.push(mapping);\n\t if (typeof mapping.originalLine === 'number') {\n\t originalMappings.push(mapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t this.__generatedMappings = generatedMappings;\n\t\n\t quickSort(originalMappings, util.compareByOriginalPositions);\n\t this.__originalMappings = originalMappings;\n\t };\n\t\n\t/**\n\t * Find the mapping that best matches the hypothetical \"needle\" mapping that\n\t * we are searching for in the given \"haystack\" of mappings.\n\t */\n\tBasicSourceMapConsumer.prototype._findMapping =\n\t function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n\t aColumnName, aComparator, aBias) {\n\t // To return the position we are searching for, we must first find the\n\t // mapping for the given position and then return the opposite position it\n\t // points to. Because the mappings are sorted, we can use binary search to\n\t // find the best mapping.\n\t\n\t if (aNeedle[aLineName] <= 0) {\n\t throw new TypeError('Line must be greater than or equal to 1, got '\n\t + aNeedle[aLineName]);\n\t }\n\t if (aNeedle[aColumnName] < 0) {\n\t throw new TypeError('Column must be greater than or equal to 0, got '\n\t + aNeedle[aColumnName]);\n\t }\n\t\n\t return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n\t };\n\t\n\t/**\n\t * Compute the last column for each generated mapping. The last column is\n\t * inclusive.\n\t */\n\tBasicSourceMapConsumer.prototype.computeColumnSpans =\n\t function SourceMapConsumer_computeColumnSpans() {\n\t for (var index = 0; index < this._generatedMappings.length; ++index) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t // Mappings do not contain a field for the last generated columnt. We\n\t // can come up with an optimistic estimate, however, by assuming that\n\t // mappings are contiguous (i.e. given two consecutive mappings, the\n\t // first mapping ends where the second one starts).\n\t if (index + 1 < this._generatedMappings.length) {\n\t var nextMapping = this._generatedMappings[index + 1];\n\t\n\t if (mapping.generatedLine === nextMapping.generatedLine) {\n\t mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n\t continue;\n\t }\n\t }\n\t\n\t // The last mapping for each line spans the entire line.\n\t mapping.lastGeneratedColumn = Infinity;\n\t }\n\t };\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tBasicSourceMapConsumer.prototype.originalPositionFor =\n\t function SourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._generatedMappings,\n\t \"generatedLine\",\n\t \"generatedColumn\",\n\t util.compareByGeneratedPositionsDeflated,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t if (mapping.generatedLine === needle.generatedLine) {\n\t var source = util.getArg(mapping, 'source', null);\n\t if (source !== null) {\n\t source = this._sources.at(source);\n\t source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n\t }\n\t var name = util.getArg(mapping, 'name', null);\n\t if (name !== null) {\n\t name = this._names.at(name);\n\t }\n\t return {\n\t source: source,\n\t line: util.getArg(mapping, 'originalLine', null),\n\t column: util.getArg(mapping, 'originalColumn', null),\n\t name: name\n\t };\n\t }\n\t }\n\t\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function BasicSourceMapConsumer_hasContentsOfAllSources() {\n\t if (!this.sourcesContent) {\n\t return false;\n\t }\n\t return this.sourcesContent.length >= this._sources.size() &&\n\t !this.sourcesContent.some(function (sc) { return sc == null; });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tBasicSourceMapConsumer.prototype.sourceContentFor =\n\t function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t if (!this.sourcesContent) {\n\t return null;\n\t }\n\t\n\t var index = this._findSourceIndex(aSource);\n\t if (index >= 0) {\n\t return this.sourcesContent[index];\n\t }\n\t\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t var url;\n\t if (this.sourceRoot != null\n\t && (url = util.urlParse(this.sourceRoot))) {\n\t // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n\t // many users. We can help them out when they expect file:// URIs to\n\t // behave like it would if they were running a local HTTP server. See\n\t // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n\t var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n\t if (url.scheme == \"file\"\n\t && this._sources.has(fileUriAbsPath)) {\n\t return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n\t }\n\t\n\t if ((!url.path || url.path == \"/\")\n\t && this._sources.has(\"/\" + relativeSource)) {\n\t return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n\t }\n\t }\n\t\n\t // This function is used recursively from\n\t // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n\t // don't want to throw if we can't find the source - we just want to\n\t // return null, so we provide a flag to exit gracefully.\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tBasicSourceMapConsumer.prototype.generatedPositionFor =\n\t function SourceMapConsumer_generatedPositionFor(aArgs) {\n\t var source = util.getArg(aArgs, 'source');\n\t source = this._findSourceIndex(source);\n\t if (source < 0) {\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t }\n\t\n\t var needle = {\n\t source: source,\n\t originalLine: util.getArg(aArgs, 'line'),\n\t originalColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (mapping.source === needle.source) {\n\t return {\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t };\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t };\n\t\n\texports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\t\n\t/**\n\t * An IndexedSourceMapConsumer instance represents a parsed source map which\n\t * we can query for information. It differs from BasicSourceMapConsumer in\n\t * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n\t * input.\n\t *\n\t * The first parameter is a raw source map (either as a JSON string, or already\n\t * parsed to an object). According to the spec for indexed source maps, they\n\t * have the following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - file: Optional. The generated file this source map is associated with.\n\t * - sections: A list of section definitions.\n\t *\n\t * Each value under the \"sections\" field has two fields:\n\t * - offset: The offset into the original specified at which this section\n\t * begins to apply, defined as an object with a \"line\" and \"column\"\n\t * field.\n\t * - map: A source map definition. This source map could also be indexed,\n\t * but doesn't have to be.\n\t *\n\t * Instead of the \"map\" field, it's also possible to have a \"url\" field\n\t * specifying a URL to retrieve a source map from, but that's currently\n\t * unsupported.\n\t *\n\t * Here's an example source map, taken from the source map spec[0], but\n\t * modified to omit a section which uses the \"url\" field.\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"app.js\",\n\t * sections: [{\n\t * offset: {line:100, column:10},\n\t * map: {\n\t * version : 3,\n\t * file: \"section.js\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AAAA,E;;ABCDE;\"\n\t * }\n\t * }],\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n\t */\n\tfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sections = util.getArg(sourceMap, 'sections');\n\t\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t this._sources = new ArraySet();\n\t this._names = new ArraySet();\n\t\n\t var lastOffset = {\n\t line: -1,\n\t column: 0\n\t };\n\t this._sections = sections.map(function (s) {\n\t if (s.url) {\n\t // The url field will require support for asynchronicity.\n\t // See https://github.com/mozilla/source-map/issues/16\n\t throw new Error('Support for url field in sections not implemented.');\n\t }\n\t var offset = util.getArg(s, 'offset');\n\t var offsetLine = util.getArg(offset, 'line');\n\t var offsetColumn = util.getArg(offset, 'column');\n\t\n\t if (offsetLine < lastOffset.line ||\n\t (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n\t throw new Error('Section offsets must be ordered and non-overlapping.');\n\t }\n\t lastOffset = offset;\n\t\n\t return {\n\t generatedOffset: {\n\t // The offset fields are 0-based, but we use 1-based indices when\n\t // encoding/decoding from VLQ.\n\t generatedLine: offsetLine + 1,\n\t generatedColumn: offsetColumn + 1\n\t },\n\t consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n\t }\n\t });\n\t}\n\t\n\tIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tIndexedSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t var sources = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n\t sources.push(this._sections[i].consumer.sources[j]);\n\t }\n\t }\n\t return sources;\n\t }\n\t});\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tIndexedSourceMapConsumer.prototype.originalPositionFor =\n\t function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t // Find the section containing the generated position we're trying to map\n\t // to an original position.\n\t var sectionIndex = binarySearch.search(needle, this._sections,\n\t function(needle, section) {\n\t var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n\t if (cmp) {\n\t return cmp;\n\t }\n\t\n\t return (needle.generatedColumn -\n\t section.generatedOffset.generatedColumn);\n\t });\n\t var section = this._sections[sectionIndex];\n\t\n\t if (!section) {\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t }\n\t\n\t return section.consumer.originalPositionFor({\n\t line: needle.generatedLine -\n\t (section.generatedOffset.generatedLine - 1),\n\t column: needle.generatedColumn -\n\t (section.generatedOffset.generatedLine === needle.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t bias: aArgs.bias\n\t });\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n\t return this._sections.every(function (s) {\n\t return s.consumer.hasContentsOfAllSources();\n\t });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tIndexedSourceMapConsumer.prototype.sourceContentFor =\n\t function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t var content = section.consumer.sourceContentFor(aSource, true);\n\t if (content) {\n\t return content;\n\t }\n\t }\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based. \n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tIndexedSourceMapConsumer.prototype.generatedPositionFor =\n\t function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t // Only consider this section if the requested source is in the list of\n\t // sources of the consumer.\n\t if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n\t continue;\n\t }\n\t var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n\t if (generatedPosition) {\n\t var ret = {\n\t line: generatedPosition.line +\n\t (section.generatedOffset.generatedLine - 1),\n\t column: generatedPosition.column +\n\t (section.generatedOffset.generatedLine === generatedPosition.line\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0)\n\t };\n\t return ret;\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null\n\t };\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tIndexedSourceMapConsumer.prototype._parseMappings =\n\t function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t this.__generatedMappings = [];\n\t this.__originalMappings = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t var sectionMappings = section.consumer._generatedMappings;\n\t for (var j = 0; j < sectionMappings.length; j++) {\n\t var mapping = sectionMappings[j];\n\t\n\t var source = section.consumer._sources.at(mapping.source);\n\t source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n\t this._sources.add(source);\n\t source = this._sources.indexOf(source);\n\t\n\t var name = null;\n\t if (mapping.name) {\n\t name = section.consumer._names.at(mapping.name);\n\t this._names.add(name);\n\t name = this._names.indexOf(name);\n\t }\n\t\n\t // The mappings coming from the consumer for the section have\n\t // generated positions relative to the start of the section, so we\n\t // need to offset them to be relative to the start of the concatenated\n\t // generated file.\n\t var adjustedMapping = {\n\t source: source,\n\t generatedLine: mapping.generatedLine +\n\t (section.generatedOffset.generatedLine - 1),\n\t generatedColumn: mapping.generatedColumn +\n\t (section.generatedOffset.generatedLine === mapping.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: name\n\t };\n\t\n\t this.__generatedMappings.push(adjustedMapping);\n\t if (typeof adjustedMapping.originalLine === 'number') {\n\t this.__originalMappings.push(adjustedMapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t quickSort(this.__originalMappings, util.compareByOriginalPositions);\n\t };\n\t\n\texports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\texports.GREATEST_LOWER_BOUND = 1;\n\texports.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Recursive implementation of binary search.\n\t *\n\t * @param aLow Indices here and lower do not contain the needle.\n\t * @param aHigh Indices here and higher do not contain the needle.\n\t * @param aNeedle The element being searched for.\n\t * @param aHaystack The non-empty array being searched.\n\t * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t */\n\tfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n\t // This function terminates when one of the following is true:\n\t //\n\t // 1. We find the exact element we are looking for.\n\t //\n\t // 2. We did not find the exact element, but we can return the index of\n\t // the next-closest element.\n\t //\n\t // 3. We did not find the exact element, and there is no next-closest\n\t // element than the one we are searching for, so we return -1.\n\t var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n\t var cmp = aCompare(aNeedle, aHaystack[mid], true);\n\t if (cmp === 0) {\n\t // Found the element we are looking for.\n\t return mid;\n\t }\n\t else if (cmp > 0) {\n\t // Our needle is greater than aHaystack[mid].\n\t if (aHigh - mid > 1) {\n\t // The element is in the upper half.\n\t return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // The exact needle element was not found in this haystack. Determine if\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return aHigh < aHaystack.length ? aHigh : -1;\n\t } else {\n\t return mid;\n\t }\n\t }\n\t else {\n\t // Our needle is less than aHaystack[mid].\n\t if (mid - aLow > 1) {\n\t // The element is in the lower half.\n\t return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return mid;\n\t } else {\n\t return aLow < 0 ? -1 : aLow;\n\t }\n\t }\n\t}\n\t\n\t/**\n\t * This is an implementation of binary search which will always try and return\n\t * the index of the closest element if there is no exact hit. This is because\n\t * mappings between original and generated line/col pairs are single points,\n\t * and there is an implicit region between each of them, so a miss just means\n\t * that you aren't on the very start of a region.\n\t *\n\t * @param aNeedle The element you are looking for.\n\t * @param aHaystack The array that is being searched.\n\t * @param aCompare A function which takes the needle and an element in the\n\t * array and returns -1, 0, or 1 depending on whether the needle is less\n\t * than, equal to, or greater than the element, respectively.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n\t */\n\texports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n\t if (aHaystack.length === 0) {\n\t return -1;\n\t }\n\t\n\t var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n\t aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n\t if (index < 0) {\n\t return -1;\n\t }\n\t\n\t // We have found either the exact element, or the next-closest element than\n\t // the one we are searching for. However, there may be more than one such\n\t // element. Make sure we always return the smallest of these.\n\t while (index - 1 >= 0) {\n\t if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n\t break;\n\t }\n\t --index;\n\t }\n\t\n\t return index;\n\t};\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t// It turns out that some (most?) JavaScript engines don't self-host\n\t// `Array.prototype.sort`. This makes sense because C++ will likely remain\n\t// faster than JS when doing raw CPU-intensive sorting. However, when using a\n\t// custom comparator function, calling back and forth between the VM's C++ and\n\t// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n\t// worse generated code for the comparator function than would be optimal. In\n\t// fact, when sorting with a comparator, these costs outweigh the benefits of\n\t// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n\t// a ~3500ms mean speed-up in `bench/bench.html`.\n\t\n\t/**\n\t * Swap the elements indexed by `x` and `y` in the array `ary`.\n\t *\n\t * @param {Array} ary\n\t * The array.\n\t * @param {Number} x\n\t * The index of the first item.\n\t * @param {Number} y\n\t * The index of the second item.\n\t */\n\tfunction swap(ary, x, y) {\n\t var temp = ary[x];\n\t ary[x] = ary[y];\n\t ary[y] = temp;\n\t}\n\t\n\t/**\n\t * Returns a random integer within the range `low .. high` inclusive.\n\t *\n\t * @param {Number} low\n\t * The lower bound on the range.\n\t * @param {Number} high\n\t * The upper bound on the range.\n\t */\n\tfunction randomIntInRange(low, high) {\n\t return Math.round(low + (Math.random() * (high - low)));\n\t}\n\t\n\t/**\n\t * The Quick Sort algorithm.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t * @param {Number} p\n\t * Start index of the array\n\t * @param {Number} r\n\t * End index of the array\n\t */\n\tfunction doQuickSort(ary, comparator, p, r) {\n\t // If our lower bound is less than our upper bound, we (1) partition the\n\t // array into two pieces and (2) recurse on each half. If it is not, this is\n\t // the empty array and our base case.\n\t\n\t if (p < r) {\n\t // (1) Partitioning.\n\t //\n\t // The partitioning chooses a pivot between `p` and `r` and moves all\n\t // elements that are less than or equal to the pivot to the before it, and\n\t // all the elements that are greater than it after it. The effect is that\n\t // once partition is done, the pivot is in the exact place it will be when\n\t // the array is put in sorted order, and it will not need to be moved\n\t // again. This runs in O(n) time.\n\t\n\t // Always choose a random pivot so that an input array which is reverse\n\t // sorted does not cause O(n^2) running time.\n\t var pivotIndex = randomIntInRange(p, r);\n\t var i = p - 1;\n\t\n\t swap(ary, pivotIndex, r);\n\t var pivot = ary[r];\n\t\n\t // Immediately after `j` is incremented in this loop, the following hold\n\t // true:\n\t //\n\t // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n\t //\n\t // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n\t for (var j = p; j < r; j++) {\n\t if (comparator(ary[j], pivot) <= 0) {\n\t i += 1;\n\t swap(ary, i, j);\n\t }\n\t }\n\t\n\t swap(ary, i + 1, j);\n\t var q = i + 1;\n\t\n\t // (2) Recurse on each half.\n\t\n\t doQuickSort(ary, comparator, p, q - 1);\n\t doQuickSort(ary, comparator, q + 1, r);\n\t }\n\t}\n\t\n\t/**\n\t * Sort the given array in-place with the given comparator function.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t */\n\texports.quickSort = function (ary, comparator) {\n\t doQuickSort(ary, comparator, 0, ary.length - 1);\n\t};\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;\n\tvar util = __webpack_require__(4);\n\t\n\t// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n\t// operating systems these days (capturing the result).\n\tvar REGEX_NEWLINE = /(\\r?\\n)/;\n\t\n\t// Newline character code for charCodeAt() comparisons\n\tvar NEWLINE_CODE = 10;\n\t\n\t// Private symbol for identifying `SourceNode`s when multiple versions of\n\t// the source-map library are loaded. This MUST NOT CHANGE across\n\t// versions!\n\tvar isSourceNode = \"$$$isSourceNode$$$\";\n\t\n\t/**\n\t * SourceNodes provide a way to abstract over interpolating/concatenating\n\t * snippets of generated JavaScript source code while maintaining the line and\n\t * column information associated with the original source code.\n\t *\n\t * @param aLine The original line number.\n\t * @param aColumn The original column number.\n\t * @param aSource The original source's filename.\n\t * @param aChunks Optional. An array of strings which are snippets of\n\t * generated JS, or other SourceNodes.\n\t * @param aName The original identifier.\n\t */\n\tfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n\t this.children = [];\n\t this.sourceContents = {};\n\t this.line = aLine == null ? null : aLine;\n\t this.column = aColumn == null ? null : aColumn;\n\t this.source = aSource == null ? null : aSource;\n\t this.name = aName == null ? null : aName;\n\t this[isSourceNode] = true;\n\t if (aChunks != null) this.add(aChunks);\n\t}\n\t\n\t/**\n\t * Creates a SourceNode from generated code and a SourceMapConsumer.\n\t *\n\t * @param aGeneratedCode The generated code\n\t * @param aSourceMapConsumer The SourceMap for the generated code\n\t * @param aRelativePath Optional. The path that relative sources in the\n\t * SourceMapConsumer should be relative to.\n\t */\n\tSourceNode.fromStringWithSourceMap =\n\t function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n\t // The SourceNode we want to fill with the generated code\n\t // and the SourceMap\n\t var node = new SourceNode();\n\t\n\t // All even indices of this array are one line of the generated code,\n\t // while all odd indices are the newlines between two adjacent lines\n\t // (since `REGEX_NEWLINE` captures its match).\n\t // Processed fragments are accessed by calling `shiftNextLine`.\n\t var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n\t var remainingLinesIndex = 0;\n\t var shiftNextLine = function() {\n\t var lineContents = getNextLine();\n\t // The last line of a file might not have a newline.\n\t var newLine = getNextLine() || \"\";\n\t return lineContents + newLine;\n\t\n\t function getNextLine() {\n\t return remainingLinesIndex < remainingLines.length ?\n\t remainingLines[remainingLinesIndex++] : undefined;\n\t }\n\t };\n\t\n\t // We need to remember the position of \"remainingLines\"\n\t var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\t\n\t // The generate SourceNodes we need a code range.\n\t // To extract it current and last mapping is used.\n\t // Here we store the last mapping.\n\t var lastMapping = null;\n\t\n\t aSourceMapConsumer.eachMapping(function (mapping) {\n\t if (lastMapping !== null) {\n\t // We add the code from \"lastMapping\" to \"mapping\":\n\t // First check if there is a new line in between.\n\t if (lastGeneratedLine < mapping.generatedLine) {\n\t // Associate first line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t lastGeneratedLine++;\n\t lastGeneratedColumn = 0;\n\t // The remaining code is added without mapping\n\t } else {\n\t // There is no new line in between.\n\t // Associate the code between \"lastGeneratedColumn\" and\n\t // \"mapping.generatedColumn\" with \"lastMapping\"\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t var code = nextLine.substr(0, mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t addMappingWithCode(lastMapping, code);\n\t // No more remaining code, continue\n\t lastMapping = mapping;\n\t return;\n\t }\n\t }\n\t // We add the generated code until the first mapping\n\t // to the SourceNode without any mapping.\n\t // Each line is added as separate string.\n\t while (lastGeneratedLine < mapping.generatedLine) {\n\t node.add(shiftNextLine());\n\t lastGeneratedLine++;\n\t }\n\t if (lastGeneratedColumn < mapping.generatedColumn) {\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t node.add(nextLine.substr(0, mapping.generatedColumn));\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t }\n\t lastMapping = mapping;\n\t }, this);\n\t // We have processed all mappings.\n\t if (remainingLinesIndex < remainingLines.length) {\n\t if (lastMapping) {\n\t // Associate the remaining code in the current line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t }\n\t // and add the remaining lines without any mapping\n\t node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n\t }\n\t\n\t // Copy sourcesContent into SourceNode\n\t aSourceMapConsumer.sources.forEach(function (sourceFile) {\n\t var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n\t if (content != null) {\n\t if (aRelativePath != null) {\n\t sourceFile = util.join(aRelativePath, sourceFile);\n\t }\n\t node.setSourceContent(sourceFile, content);\n\t }\n\t });\n\t\n\t return node;\n\t\n\t function addMappingWithCode(mapping, code) {\n\t if (mapping === null || mapping.source === undefined) {\n\t node.add(code);\n\t } else {\n\t var source = aRelativePath\n\t ? util.join(aRelativePath, mapping.source)\n\t : mapping.source;\n\t node.add(new SourceNode(mapping.originalLine,\n\t mapping.originalColumn,\n\t source,\n\t code,\n\t mapping.name));\n\t }\n\t }\n\t };\n\t\n\t/**\n\t * Add a chunk of generated JS to this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.add = function SourceNode_add(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t aChunk.forEach(function (chunk) {\n\t this.add(chunk);\n\t }, this);\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t if (aChunk) {\n\t this.children.push(aChunk);\n\t }\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Add a chunk of generated JS to the beginning of this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t for (var i = aChunk.length-1; i >= 0; i--) {\n\t this.prepend(aChunk[i]);\n\t }\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t this.children.unshift(aChunk);\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Walk over the tree of JS snippets in this node and its children. The\n\t * walking function is called once for each snippet of JS and is passed that\n\t * snippet and the its original associated source's line/column location.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n\t var chunk;\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t chunk = this.children[i];\n\t if (chunk[isSourceNode]) {\n\t chunk.walk(aFn);\n\t }\n\t else {\n\t if (chunk !== '') {\n\t aFn(chunk, { source: this.source,\n\t line: this.line,\n\t column: this.column,\n\t name: this.name });\n\t }\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n\t * each of `this.children`.\n\t *\n\t * @param aSep The separator.\n\t */\n\tSourceNode.prototype.join = function SourceNode_join(aSep) {\n\t var newChildren;\n\t var i;\n\t var len = this.children.length;\n\t if (len > 0) {\n\t newChildren = [];\n\t for (i = 0; i < len-1; i++) {\n\t newChildren.push(this.children[i]);\n\t newChildren.push(aSep);\n\t }\n\t newChildren.push(this.children[i]);\n\t this.children = newChildren;\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Call String.prototype.replace on the very right-most source snippet. Useful\n\t * for trimming whitespace from the end of a source node, etc.\n\t *\n\t * @param aPattern The pattern to replace.\n\t * @param aReplacement The thing to replace the pattern with.\n\t */\n\tSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n\t var lastChild = this.children[this.children.length - 1];\n\t if (lastChild[isSourceNode]) {\n\t lastChild.replaceRight(aPattern, aReplacement);\n\t }\n\t else if (typeof lastChild === 'string') {\n\t this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n\t }\n\t else {\n\t this.children.push(''.replace(aPattern, aReplacement));\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Set the source content for a source file. This will be added to the SourceMapGenerator\n\t * in the sourcesContent field.\n\t *\n\t * @param aSourceFile The filename of the source file\n\t * @param aSourceContent The content of the source file\n\t */\n\tSourceNode.prototype.setSourceContent =\n\t function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n\t this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n\t };\n\t\n\t/**\n\t * Walk over the tree of SourceNodes. The walking function is called for each\n\t * source file content and is passed the filename and source content.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walkSourceContents =\n\t function SourceNode_walkSourceContents(aFn) {\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t if (this.children[i][isSourceNode]) {\n\t this.children[i].walkSourceContents(aFn);\n\t }\n\t }\n\t\n\t var sources = Object.keys(this.sourceContents);\n\t for (var i = 0, len = sources.length; i < len; i++) {\n\t aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n\t }\n\t };\n\t\n\t/**\n\t * Return the string representation of this source node. Walks over the tree\n\t * and concatenates all the various snippets together to one string.\n\t */\n\tSourceNode.prototype.toString = function SourceNode_toString() {\n\t var str = \"\";\n\t this.walk(function (chunk) {\n\t str += chunk;\n\t });\n\t return str;\n\t};\n\t\n\t/**\n\t * Returns the string representation of this source node along with a source\n\t * map.\n\t */\n\tSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n\t var generated = {\n\t code: \"\",\n\t line: 1,\n\t column: 0\n\t };\n\t var map = new SourceMapGenerator(aArgs);\n\t var sourceMappingActive = false;\n\t var lastOriginalSource = null;\n\t var lastOriginalLine = null;\n\t var lastOriginalColumn = null;\n\t var lastOriginalName = null;\n\t this.walk(function (chunk, original) {\n\t generated.code += chunk;\n\t if (original.source !== null\n\t && original.line !== null\n\t && original.column !== null) {\n\t if(lastOriginalSource !== original.source\n\t || lastOriginalLine !== original.line\n\t || lastOriginalColumn !== original.column\n\t || lastOriginalName !== original.name) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t lastOriginalSource = original.source;\n\t lastOriginalLine = original.line;\n\t lastOriginalColumn = original.column;\n\t lastOriginalName = original.name;\n\t sourceMappingActive = true;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t }\n\t });\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t }\n\t for (var idx = 0, length = chunk.length; idx < length; idx++) {\n\t if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n\t generated.line++;\n\t generated.column = 0;\n\t // Mappings end at eol\n\t if (idx + 1 === length) {\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t } else {\n\t generated.column++;\n\t }\n\t }\n\t });\n\t this.walkSourceContents(function (sourceFile, sourceContent) {\n\t map.setSourceContent(sourceFile, sourceContent);\n\t });\n\t\n\t return { code: generated.code, map: map };\n\t};\n\t\n\texports.SourceNode = SourceNode;\n\n\n/***/ })\n/******/ ])\n});\n;\n\n\n// WEBPACK FOOTER //\n// source-map.min.js"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 0fd5815da764db5fb9fe","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./source-map.js\n// module id = 0\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-generator.js\n// module id = 1\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64-vlq.js\n// module id = 2\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64.js\n// module id = 3\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // “sources” entry. This value is prepended to the individual\n // entries in the “source” field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // “sourceRoot”, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/util.js\n// module id = 4\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/array-set.js\n// module id = 5\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/mapping-list.js\n// module id = 6\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._absoluteSources.slice();\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-consumer.js\n// module id = 7\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/binary-search.js\n// module id = 8\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/quick-sort.js\n// module id = 9\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex] || '';\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex] || '';\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-node.js\n// module id = 10\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/source-map/lib/array-set.js b/node_modules/mathjs/examples/node_modules/source-map/lib/array-set.js new file mode 100644 index 0000000..fbd5c81 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/lib/array-set.js @@ -0,0 +1,121 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; diff --git a/node_modules/mathjs/examples/node_modules/source-map/lib/base64-vlq.js b/node_modules/mathjs/examples/node_modules/source-map/lib/base64-vlq.js new file mode 100644 index 0000000..612b404 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/lib/base64-vlq.js @@ -0,0 +1,140 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; diff --git a/node_modules/mathjs/examples/node_modules/source-map/lib/base64.js b/node_modules/mathjs/examples/node_modules/source-map/lib/base64.js new file mode 100644 index 0000000..8aa86b3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/lib/base64.js @@ -0,0 +1,67 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; diff --git a/node_modules/mathjs/examples/node_modules/source-map/lib/binary-search.js b/node_modules/mathjs/examples/node_modules/source-map/lib/binary-search.js new file mode 100644 index 0000000..010ac94 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/lib/binary-search.js @@ -0,0 +1,111 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/node_modules/mathjs/examples/node_modules/source-map/lib/mapping-list.js b/node_modules/mathjs/examples/node_modules/source-map/lib/mapping-list.js new file mode 100644 index 0000000..06d1274 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/lib/mapping-list.js @@ -0,0 +1,79 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; diff --git a/node_modules/mathjs/examples/node_modules/source-map/lib/quick-sort.js b/node_modules/mathjs/examples/node_modules/source-map/lib/quick-sort.js new file mode 100644 index 0000000..6a7caad --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/lib/quick-sort.js @@ -0,0 +1,114 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; diff --git a/node_modules/mathjs/examples/node_modules/source-map/lib/source-map-consumer.js b/node_modules/mathjs/examples/node_modules/source-map/lib/source-map-consumer.js new file mode 100644 index 0000000..7b99d1d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/lib/source-map-consumer.js @@ -0,0 +1,1145 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/node_modules/mathjs/examples/node_modules/source-map/lib/source-map-generator.js b/node_modules/mathjs/examples/node_modules/source-map/lib/source-map-generator.js new file mode 100644 index 0000000..508bcfb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/lib/source-map-generator.js @@ -0,0 +1,425 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/node_modules/mathjs/examples/node_modules/source-map/lib/source-node.js b/node_modules/mathjs/examples/node_modules/source-map/lib/source-node.js new file mode 100644 index 0000000..8bcdbe3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/lib/source-node.js @@ -0,0 +1,413 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; diff --git a/node_modules/mathjs/examples/node_modules/source-map/lib/util.js b/node_modules/mathjs/examples/node_modules/source-map/lib/util.js new file mode 100644 index 0000000..3ca92e5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/lib/util.js @@ -0,0 +1,488 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/node_modules/mathjs/examples/node_modules/source-map/package.json b/node_modules/mathjs/examples/node_modules/source-map/package.json new file mode 100644 index 0000000..2466341 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/package.json @@ -0,0 +1,73 @@ +{ + "name": "source-map", + "description": "Generates and consumes source maps", + "version": "0.6.1", + "homepage": "https://github.com/mozilla/source-map", + "author": "Nick Fitzgerald ", + "contributors": [ + "Tobias Koppers ", + "Duncan Beevers ", + "Stephen Crane ", + "Ryan Seddon ", + "Miles Elam ", + "Mihai Bazon ", + "Michael Ficarra ", + "Todd Wolfson ", + "Alexander Solovyov ", + "Felix Gnass ", + "Conrad Irwin ", + "usrbincc ", + "David Glasser ", + "Chase Douglas ", + "Evan Wallace ", + "Heather Arthur ", + "Hugh Kennedy ", + "David Glasser ", + "Simon Lydell ", + "Jmeas Smith ", + "Michael Z Goddard ", + "azu ", + "John Gozde ", + "Adam Kirkton ", + "Chris Montgomery ", + "J. Ryan Stinnett ", + "Jack Herrington ", + "Chris Truter ", + "Daniel Espeset ", + "Jamie Wong ", + "Eddy Bruël ", + "Hawken Rives ", + "Gilad Peleg ", + "djchie ", + "Gary Ye ", + "Nicolas Lalevée " + ], + "repository": { + "type": "git", + "url": "http://github.com/mozilla/source-map.git" + }, + "main": "./source-map.js", + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/", + "dist/source-map.debug.js", + "dist/source-map.js", + "dist/source-map.min.js", + "dist/source-map.min.js.map" + ], + "engines": { + "node": ">=0.10.0" + }, + "license": "BSD-3-Clause", + "scripts": { + "test": "npm run build && node test/run-tests.js", + "build": "webpack --color", + "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" + }, + "devDependencies": { + "doctoc": "^0.15.0", + "webpack": "^1.12.0" + }, + "typings": "source-map" +} diff --git a/node_modules/mathjs/examples/node_modules/source-map/source-map.d.ts b/node_modules/mathjs/examples/node_modules/source-map/source-map.d.ts new file mode 100644 index 0000000..8f972b0 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/source-map.d.ts @@ -0,0 +1,98 @@ +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +export interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: string[]; + names: string[]; + sourcesContent?: string[]; + mappings: string; +} + +export interface Position { + line: number; + column: number; +} + +export interface LineRange extends Position { + lastColumn: number; +} + +export interface FindPosition extends Position { + // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND + bias?: number; +} + +export interface SourceFindPosition extends FindPosition { + source: string; +} + +export interface MappedPosition extends Position { + source: string; + name?: string; +} + +export interface MappingItem { + source: string; + generatedLine: number; + generatedColumn: number; + originalLine: number; + originalColumn: number; + name: string; +} + +export class SourceMapConsumer { + static GENERATED_ORDER: number; + static ORIGINAL_ORDER: number; + + static GREATEST_LOWER_BOUND: number; + static LEAST_UPPER_BOUND: number; + + constructor(rawSourceMap: RawSourceMap); + computeColumnSpans(): void; + originalPositionFor(generatedPosition: FindPosition): MappedPosition; + generatedPositionFor(originalPosition: SourceFindPosition): LineRange; + allGeneratedPositionsFor(originalPosition: MappedPosition): Position[]; + hasContentsOfAllSources(): boolean; + sourceContentFor(source: string, returnNullOnMissing?: boolean): string; + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; +} + +export interface Mapping { + generated: Position; + original: Position; + source: string; + name?: string; +} + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; + addMapping(mapping: Mapping): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + toString(): string; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export class SourceNode { + constructor(); + constructor(line: number, column: number, source: string); + constructor(line: number, column: number, source: string, chunk?: string, name?: string); + static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; + add(chunk: string): void; + prepend(chunk: string): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; + join(sep: string): SourceNode; + replaceRight(pattern: string, replacement: string): SourceNode; + toString(): string; + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; +} diff --git a/node_modules/mathjs/examples/node_modules/source-map/source-map.js b/node_modules/mathjs/examples/node_modules/source-map/source-map.js new file mode 100644 index 0000000..bc88fe8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/source-map/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/node_modules/mathjs/examples/node_modules/strip-final-newline/index.js b/node_modules/mathjs/examples/node_modules/strip-final-newline/index.js new file mode 100644 index 0000000..78fc0c5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/strip-final-newline/index.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = input => { + const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); + const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); + + if (input[input.length - 1] === LF) { + input = input.slice(0, input.length - 1); + } + + if (input[input.length - 1] === CR) { + input = input.slice(0, input.length - 1); + } + + return input; +}; diff --git a/node_modules/mathjs/examples/node_modules/strip-final-newline/license b/node_modules/mathjs/examples/node_modules/strip-final-newline/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/strip-final-newline/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/strip-final-newline/package.json b/node_modules/mathjs/examples/node_modules/strip-final-newline/package.json new file mode 100644 index 0000000..d9f2a6c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/strip-final-newline/package.json @@ -0,0 +1,40 @@ +{ + "name": "strip-final-newline", + "version": "2.0.0", + "description": "Strip the final newline character from a string/buffer", + "license": "MIT", + "repository": "sindresorhus/strip-final-newline", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "strip", + "trim", + "remove", + "delete", + "final", + "last", + "end", + "file", + "newline", + "linebreak", + "character", + "string", + "buffer" + ], + "devDependencies": { + "ava": "^0.25.0", + "xo": "^0.23.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/strip-final-newline/readme.md b/node_modules/mathjs/examples/node_modules/strip-final-newline/readme.md new file mode 100644 index 0000000..32dfd50 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/strip-final-newline/readme.md @@ -0,0 +1,30 @@ +# strip-final-newline [![Build Status](https://travis-ci.com/sindresorhus/strip-final-newline.svg?branch=master)](https://travis-ci.com/sindresorhus/strip-final-newline) + +> Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from a string/buffer + +Can be useful when parsing the output of, for example, `ChildProcess#execFile`, as [binaries usually output a newline at the end](https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline). Normally, you would use `stdout.trim()`, but that would also remove newlines at the start and whitespace. + + +## Install + +``` +$ npm install strip-final-newline +``` + + +## Usage + +```js +const stripFinalNewline = require('strip-final-newline'); + +stripFinalNewline('foo\nbar\n\n'); +//=> 'foo\nbar\n' + +stripFinalNewline(Buffer.from('foo\nbar\n\n')).toString(); +//=> 'foo\nbar\n' +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/mathjs/examples/node_modules/supports-color/browser.js b/node_modules/mathjs/examples/node_modules/supports-color/browser.js new file mode 100644 index 0000000..f097aec --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-color/browser.js @@ -0,0 +1,24 @@ +/* eslint-env browser */ +'use strict'; + +function getChromeVersion() { + const matches = /(Chrome|Chromium)\/(?\d+)\./.exec(navigator.userAgent); + + if (!matches) { + return; + } + + return Number.parseInt(matches.groups.chromeVersion, 10); +} + +const colorSupport = getChromeVersion() >= 69 ? { + level: 1, + hasBasic: true, + has256: false, + has16m: false +} : false; + +module.exports = { + stdout: colorSupport, + stderr: colorSupport +}; diff --git a/node_modules/mathjs/examples/node_modules/supports-color/index.js b/node_modules/mathjs/examples/node_modules/supports-color/index.js new file mode 100644 index 0000000..2dd2fcb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-color/index.js @@ -0,0 +1,152 @@ +'use strict'; +const os = require('os'); +const tty = require('tty'); +const hasFlag = require('has-flag'); + +const {env} = process; + +let flagForceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + flagForceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + flagForceColor = 1; +} + +function envForceColor() { + if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + return 1; + } + + if (env.FORCE_COLOR === 'false') { + return 0; + } + + return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { + const noFlagForceColor = envForceColor(); + if (noFlagForceColor !== undefined) { + flagForceColor = noFlagForceColor; + } + + const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; + + if (forceColor === 0) { + return 0; + } + + if (sniffFlags) { + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +function getSupportLevel(stream, options = {}) { + const level = supportsColor(stream, { + streamIsTTY: stream && stream.isTTY, + ...options + }); + + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel({isTTY: tty.isatty(1)}), + stderr: getSupportLevel({isTTY: tty.isatty(2)}) +}; diff --git a/node_modules/mathjs/examples/node_modules/supports-color/license b/node_modules/mathjs/examples/node_modules/supports-color/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-color/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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. diff --git a/node_modules/mathjs/examples/node_modules/supports-color/package.json b/node_modules/mathjs/examples/node_modules/supports-color/package.json new file mode 100644 index 0000000..a97bf2a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-color/package.json @@ -0,0 +1,58 @@ +{ + "name": "supports-color", + "version": "8.1.1", + "description": "Detect whether a terminal supports color", + "license": "MIT", + "repository": "chalk/supports-color", + "funding": "https://github.com/chalk/supports-color?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js", + "browser.js" + ], + "exports": { + "node": "./index.js", + "default": "./browser.js" + }, + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "dependencies": { + "has-flag": "^4.0.0" + }, + "devDependencies": { + "ava": "^2.4.0", + "import-fresh": "^3.2.2", + "xo": "^0.35.0" + }, + "browser": "browser.js" +} diff --git a/node_modules/mathjs/examples/node_modules/supports-color/readme.md b/node_modules/mathjs/examples/node_modules/supports-color/readme.md new file mode 100644 index 0000000..3eedd1c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-color/readme.md @@ -0,0 +1,77 @@ +# supports-color + +> Detect whether a terminal supports color + +## Install + +``` +$ npm install supports-color +``` + +## Usage + +```js +const supportsColor = require('supports-color'); + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + +## API + +Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + +### `require('supports-color').supportsColor(stream, options?)` + +Additionally, `supports-color` exposes the `.supportsColor()` function that takes an arbitrary write stream (e.g. `process.stdout`) and an optional options object to (re-)evaluate color support for an arbitrary stream. + +For example, `require('supports-color').stdout` is the equivalent of `require('supports-color').supportsColor(process.stdout)`. + +The options object supports a single boolean property `sniffFlags`. By default it is `true`, which instructs `supportsColor()` to sniff `process.argv` for the multitude of `--color` flags (see _Info_ below). If `false`, then `process.argv` is not considered when determining color support. + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + +--- + +
    + + Get professional support for this package with a Tidelift subscription + +
    + + Tidelift helps make open source sustainable for maintainers while giving companies
    assurances about security, maintenance, and licensing for their dependencies. +
    +
    + +--- diff --git a/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/.eslintrc b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/.eslintrc new file mode 100644 index 0000000..346ffec --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/.eslintrc @@ -0,0 +1,14 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "browser": true, + "node": true, + }, + + "rules": { + "id-length": "off", + }, +} diff --git a/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/.github/FUNDING.yml b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/.github/FUNDING.yml new file mode 100644 index 0000000..e8d64f3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/supports-preserve-symlink-flag +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/.nycrc b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md new file mode 100644 index 0000000..61f607f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2022-01-02 + +### Commits + +- Tests [`e2f59ad`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/e2f59ad74e2ae0f5f4899fcde6a6f693ab7cc074) +- Initial commit [`dc222aa`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/dc222aad3c0b940d8d3af1ca9937d108bd2dc4b9) +- [meta] do not publish workflow files [`5ef77f7`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/5ef77f7cb6946d16ee38672be9ec0f1bbdf63262) +- npm init [`992b068`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/992b068503a461f7e8676f40ca2aab255fd8d6ff) +- read me [`6c9afa9`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/6c9afa9fabc8eaf0814aaed6dd01e6df0931b76d) +- Initial implementation [`2f98925`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/2f9892546396d4ab0ad9f1ff83e76c3f01234ae8) +- [meta] add `auto-changelog` [`6c476ae`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/6c476ae1ed7ce68b0480344f090ac2844f35509d) +- [Dev Deps] add `eslint`, `@ljharb/eslint-config` [`d0fffc8`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/d0fffc886d25fba119355520750a909d64da0087) +- Only apps should have lockfiles [`ab318ed`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/ab318ed7ae62f6c2c0e80a50398d40912afd8f69) +- [meta] add `safe-publish-latest` [`2bb23b3`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/2bb23b3ebab02dc4135c4cdf0217db82835b9fca) +- [meta] add `sideEffects` flag [`600223b`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/600223ba24f30779f209d9097721eff35ed62741) diff --git a/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/LICENSE b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/LICENSE new file mode 100644 index 0000000..2e7b9a3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Inspect JS + +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. diff --git a/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/README.md b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/README.md new file mode 100644 index 0000000..eb05b12 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/README.md @@ -0,0 +1,42 @@ +# node-supports-preserve-symlinks-flag [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Determine if the current node version supports the `--preserve-symlinks` flag. + +## Example + +```js +var supportsPreserveSymlinks = require('node-supports-preserve-symlinks-flag'); +var assert = require('assert'); + +assert.equal(supportsPreserveSymlinks, null); // in a browser +assert.equal(supportsPreserveSymlinks, false); // in node < v6.2 +assert.equal(supportsPreserveSymlinks, true); // in node v6.2+ +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/node-supports-preserve-symlinks-flag +[npm-version-svg]: https://versionbadg.es/inspect-js/node-supports-preserve-symlinks-flag.svg +[deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag.svg +[deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag +[dev-deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/node-supports-preserve-symlinks-flag.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/node-supports-preserve-symlinks-flag.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/node-supports-preserve-symlinks-flag.svg +[downloads-url]: https://npm-stat.com/charts.html?package=node-supports-preserve-symlinks-flag +[codecov-image]: https://codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/node-supports-preserve-symlinks-flag +[actions-url]: https://github.com/inspect-js/node-supports-preserve-symlinks-flag/actions diff --git a/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/browser.js b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/browser.js new file mode 100644 index 0000000..087be1f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/browser.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = null; diff --git a/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/index.js b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/index.js new file mode 100644 index 0000000..86fd5d3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/index.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = ( +// node 12+ + process.allowedNodeEnvironmentFlags && process.allowedNodeEnvironmentFlags.has('--preserve-symlinks') +) || ( +// node v6.2 - v11 + String(module.constructor._findPath).indexOf('preserveSymlinks') >= 0 // eslint-disable-line no-underscore-dangle +); diff --git a/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/package.json b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/package.json new file mode 100644 index 0000000..56edadc --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/package.json @@ -0,0 +1,70 @@ +{ + "name": "supports-preserve-symlinks-flag", + "version": "1.0.0", + "description": "Determine if the current node version supports the `--preserve-symlinks` flag.", + "main": "./index.js", + "browser": "./browser.js", + "exports": { + ".": [ + { + "browser": "./browser.js", + "default": "./index.js" + }, + "./index.js" + ], + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/node-supports-preserve-symlinks-flag.git" + }, + "keywords": [ + "node", + "flag", + "symlink", + "symlinks", + "preserve-symlinks" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/node-supports-preserve-symlinks-flag/issues" + }, + "homepage": "https://github.com/inspect-js/node-supports-preserve-symlinks-flag#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.1.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "eslint": "^8.6.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "semver": "^6.3.0", + "tape": "^5.4.0" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/test/index.js b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/test/index.js new file mode 100644 index 0000000..9938d67 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/supports-preserve-symlinks-flag/test/index.js @@ -0,0 +1,29 @@ +'use strict'; + +var test = require('tape'); +var semver = require('semver'); + +var supportsPreserveSymlinks = require('../'); +var browser = require('../browser'); + +test('supportsPreserveSymlinks', function (t) { + t.equal(typeof supportsPreserveSymlinks, 'boolean', 'is a boolean'); + + t.equal(browser, null, 'browser file is `null`'); + t.equal( + supportsPreserveSymlinks, + null, + 'in a browser, is null', + { skip: typeof window === 'undefined' } + ); + + var expected = semver.satisfies(process.version, '>= 6.2'); + t.equal( + supportsPreserveSymlinks, + expected, + 'is true in node v6.2+, false otherwise (actual: ' + supportsPreserveSymlinks + ', expected ' + expected + ')', + { skip: typeof window !== 'undefined' } + ); + + t.end(); +}); diff --git a/node_modules/mathjs/examples/node_modules/tapable/LICENSE b/node_modules/mathjs/examples/node_modules/tapable/LICENSE new file mode 100644 index 0000000..03c083c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright JS Foundation and other contributors + +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. diff --git a/node_modules/mathjs/examples/node_modules/tapable/README.md b/node_modules/mathjs/examples/node_modules/tapable/README.md new file mode 100644 index 0000000..1377197 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/README.md @@ -0,0 +1,296 @@ +# Tapable + +The tapable package expose many Hook classes, which can be used to create hooks for plugins. + +``` javascript +const { + SyncHook, + SyncBailHook, + SyncWaterfallHook, + SyncLoopHook, + AsyncParallelHook, + AsyncParallelBailHook, + AsyncSeriesHook, + AsyncSeriesBailHook, + AsyncSeriesWaterfallHook + } = require("tapable"); +``` + +## Installation + +``` shell +npm install --save tapable +``` + +## Usage + +All Hook constructors take one optional argument, which is a list of argument names as strings. + +``` js +const hook = new SyncHook(["arg1", "arg2", "arg3"]); +``` + +The best practice is to expose all hooks of a class in a `hooks` property: + +``` js +class Car { + constructor() { + this.hooks = { + accelerate: new SyncHook(["newSpeed"]), + brake: new SyncHook(), + calculateRoutes: new AsyncParallelHook(["source", "target", "routesList"]) + }; + } + + /* ... */ +} +``` + +Other people can now use these hooks: + +``` js +const myCar = new Car(); + +// Use the tap method to add a consument +myCar.hooks.brake.tap("WarningLampPlugin", () => warningLamp.on()); +``` + +It's required to pass a name to identify the plugin/reason. + +You may receive arguments: + +``` js +myCar.hooks.accelerate.tap("LoggerPlugin", newSpeed => console.log(`Accelerating to ${newSpeed}`)); +``` + +For sync hooks, `tap` is the only valid method to add a plugin. Async hooks also support async plugins: + +``` js +myCar.hooks.calculateRoutes.tapPromise("GoogleMapsPlugin", (source, target, routesList) => { + // return a promise + return google.maps.findRoute(source, target).then(route => { + routesList.add(route); + }); +}); +myCar.hooks.calculateRoutes.tapAsync("BingMapsPlugin", (source, target, routesList, callback) => { + bing.findRoute(source, target, (err, route) => { + if(err) return callback(err); + routesList.add(route); + // call the callback + callback(); + }); +}); + +// You can still use sync plugins +myCar.hooks.calculateRoutes.tap("CachedRoutesPlugin", (source, target, routesList) => { + const cachedRoute = cache.get(source, target); + if(cachedRoute) + routesList.add(cachedRoute); +}) +``` +The class declaring these hooks need to call them: + +``` js +class Car { + /** + * You won't get returned value from SyncHook or AsyncParallelHook, + * to do that, use SyncWaterfallHook and AsyncSeriesWaterfallHook respectively + **/ + + setSpeed(newSpeed) { + // following call returns undefined even when you returned values + this.hooks.accelerate.call(newSpeed); + } + + useNavigationSystemPromise(source, target) { + const routesList = new List(); + return this.hooks.calculateRoutes.promise(source, target, routesList).then((res) => { + // res is undefined for AsyncParallelHook + return routesList.getRoutes(); + }); + } + + useNavigationSystemAsync(source, target, callback) { + const routesList = new List(); + this.hooks.calculateRoutes.callAsync(source, target, routesList, err => { + if(err) return callback(err); + callback(null, routesList.getRoutes()); + }); + } +} +``` + +The Hook will compile a method with the most efficient way of running your plugins. It generates code depending on: +* The number of registered plugins (none, one, many) +* The kind of registered plugins (sync, async, promise) +* The used call method (sync, async, promise) +* The number of arguments +* Whether interception is used + +This ensures fastest possible execution. + +## Hook types + +Each hook can be tapped with one or several functions. How they are executed depends on the hook type: + +* Basic hook (without “Waterfall”, “Bail” or “Loop” in its name). This hook simply calls every function it tapped in a row. + +* __Waterfall__. A waterfall hook also calls each tapped function in a row. Unlike the basic hook, it passes a return value from each function to the next function. + +* __Bail__. A bail hook allows exiting early. When any of the tapped function returns anything, the bail hook will stop executing the remaining ones. + +* __Loop__. When a plugin in a loop hook returns a non-undefined value the hook will restart from the first plugin. It will loop until all plugins return undefined. + +Additionally, hooks can be synchronous or asynchronous. To reflect this, there’re “Sync”, “AsyncSeries”, and “AsyncParallel” hook classes: + +* __Sync__. A sync hook can only be tapped with synchronous functions (using `myHook.tap()`). + +* __AsyncSeries__. An async-series hook can be tapped with synchronous, callback-based and promise-based functions (using `myHook.tap()`, `myHook.tapAsync()` and `myHook.tapPromise()`). They call each async method in a row. + +* __AsyncParallel__. An async-parallel hook can also be tapped with synchronous, callback-based and promise-based functions (using `myHook.tap()`, `myHook.tapAsync()` and `myHook.tapPromise()`). However, they run each async method in parallel. + +The hook type is reflected in its class name. E.g., `AsyncSeriesWaterfallHook` allows asynchronous functions and runs them in series, passing each function’s return value into the next function. + + +## Interception + +All Hooks offer an additional interception API: + +``` js +myCar.hooks.calculateRoutes.intercept({ + call: (source, target, routesList) => { + console.log("Starting to calculate routes"); + }, + register: (tapInfo) => { + // tapInfo = { type: "promise", name: "GoogleMapsPlugin", fn: ... } + console.log(`${tapInfo.name} is doing its job`); + return tapInfo; // may return a new tapInfo object + } +}) +``` + +**call**: `(...args) => void` Adding `call` to your interceptor will trigger when hooks are triggered. You have access to the hooks arguments. + +**tap**: `(tap: Tap) => void` Adding `tap` to your interceptor will trigger when a plugin taps into a hook. Provided is the `Tap` object. `Tap` object can't be changed. + +**loop**: `(...args) => void` Adding `loop` to your interceptor will trigger for each loop of a looping hook. + +**register**: `(tap: Tap) => Tap | undefined` Adding `register` to your interceptor will trigger for each added `Tap` and allows to modify it. + +## Context + +Plugins and interceptors can opt-in to access an optional `context` object, which can be used to pass arbitrary values to subsequent plugins and interceptors. + +``` js +myCar.hooks.accelerate.intercept({ + context: true, + tap: (context, tapInfo) => { + // tapInfo = { type: "sync", name: "NoisePlugin", fn: ... } + console.log(`${tapInfo.name} is doing it's job`); + + // `context` starts as an empty object if at least one plugin uses `context: true`. + // If no plugins use `context: true`, then `context` is undefined. + if (context) { + // Arbitrary properties can be added to `context`, which plugins can then access. + context.hasMuffler = true; + } + } +}); + +myCar.hooks.accelerate.tap({ + name: "NoisePlugin", + context: true +}, (context, newSpeed) => { + if (context && context.hasMuffler) { + console.log("Silence..."); + } else { + console.log("Vroom!"); + } +}); +``` + +## HookMap + +A HookMap is a helper class for a Map with Hooks + +``` js +const keyedHook = new HookMap(key => new SyncHook(["arg"])) +``` + +``` js +keyedHook.for("some-key").tap("MyPlugin", (arg) => { /* ... */ }); +keyedHook.for("some-key").tapAsync("MyPlugin", (arg, callback) => { /* ... */ }); +keyedHook.for("some-key").tapPromise("MyPlugin", (arg) => { /* ... */ }); +``` + +``` js +const hook = keyedHook.get("some-key"); +if(hook !== undefined) { + hook.callAsync("arg", err => { /* ... */ }); +} +``` + +## Hook/HookMap interface + +Public: + +``` ts +interface Hook { + tap: (name: string | Tap, fn: (context?, ...args) => Result) => void, + tapAsync: (name: string | Tap, fn: (context?, ...args, callback: (err, result: Result) => void) => void) => void, + tapPromise: (name: string | Tap, fn: (context?, ...args) => Promise) => void, + intercept: (interceptor: HookInterceptor) => void +} + +interface HookInterceptor { + call: (context?, ...args) => void, + loop: (context?, ...args) => void, + tap: (context?, tap: Tap) => void, + register: (tap: Tap) => Tap, + context: boolean +} + +interface HookMap { + for: (key: any) => Hook, + intercept: (interceptor: HookMapInterceptor) => void +} + +interface HookMapInterceptor { + factory: (key: any, hook: Hook) => Hook +} + +interface Tap { + name: string, + type: string + fn: Function, + stage: number, + context: boolean, + before?: string | Array +} +``` + +Protected (only for the class containing the hook): + +``` ts +interface Hook { + isUsed: () => boolean, + call: (...args) => Result, + promise: (...args) => Promise, + callAsync: (...args, callback: (err, result: Result) => void) => void, +} + +interface HookMap { + get: (key: any) => Hook | undefined, + for: (key: any) => Hook +} +``` + +## MultiHook + +A helper Hook-like class to redirect taps to multiple other hooks: + +``` js +const { MultiHook } = require("tapable"); + +this.hooks.allHooks = new MultiHook([this.hooks.hookA, this.hooks.hookB]); +``` diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncParallelBailHook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncParallelBailHook.js new file mode 100644 index 0000000..45eca33 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncParallelBailHook.js @@ -0,0 +1,85 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncParallelBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, onDone }) { + let code = ""; + code += `var _results = new Array(${this.options.taps.length});\n`; + code += "var _checkDone = function() {\n"; + code += "for(var i = 0; i < _results.length; i++) {\n"; + code += "var item = _results[i];\n"; + code += "if(item === undefined) return false;\n"; + code += "if(item.result !== undefined) {\n"; + code += onResult("item.result"); + code += "return true;\n"; + code += "}\n"; + code += "if(item.error) {\n"; + code += onError("item.error"); + code += "return true;\n"; + code += "}\n"; + code += "}\n"; + code += "return false;\n"; + code += "}\n"; + code += this.callTapsParallel({ + onError: (i, err, done, doneBreak) => { + let code = ""; + code += `if(${i} < _results.length && ((_results.length = ${i + + 1}), (_results[${i}] = { error: ${err} }), _checkDone())) {\n`; + code += doneBreak(true); + code += "} else {\n"; + code += done(); + code += "}\n"; + return code; + }, + onResult: (i, result, done, doneBreak) => { + let code = ""; + code += `if(${i} < _results.length && (${result} !== undefined && (_results.length = ${i + + 1}), (_results[${i}] = { result: ${result} }), _checkDone())) {\n`; + code += doneBreak(true); + code += "} else {\n"; + code += done(); + code += "}\n"; + return code; + }, + onTap: (i, run, done, doneBreak) => { + let code = ""; + if (i > 0) { + code += `if(${i} >= _results.length) {\n`; + code += done(); + code += "} else {\n"; + } + code += run(); + if (i > 0) code += "}\n"; + return code; + }, + onDone + }); + return code; + } +} + +const factory = new AsyncParallelBailHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncParallelBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncParallelBailHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncParallelBailHook.prototype = null; + +module.exports = AsyncParallelBailHook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncParallelHook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncParallelHook.js new file mode 100644 index 0000000..b7a3631 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncParallelHook.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncParallelHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsParallel({ + onError: (i, err, done, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncParallelHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncParallelHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncParallelHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncParallelHook.prototype = null; + +module.exports = AsyncParallelHook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesBailHook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesBailHook.js new file mode 100644 index 0000000..5df66df --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesBailHook.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncSeriesBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onResult: (i, result, next) => + `if(${result} !== undefined) {\n${onResult( + result + )}\n} else {\n${next()}}\n`, + resultReturns, + onDone + }); + } +} + +const factory = new AsyncSeriesBailHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncSeriesBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesBailHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncSeriesBailHook.prototype = null; + +module.exports = AsyncSeriesBailHook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesHook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesHook.js new file mode 100644 index 0000000..3edad00 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesHook.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncSeriesHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncSeriesHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncSeriesHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncSeriesHook.prototype = null; + +module.exports = AsyncSeriesHook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesLoopHook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesLoopHook.js new file mode 100644 index 0000000..fb5f067 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesLoopHook.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncSeriesLoopHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsLooping({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncSeriesLoopHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncSeriesLoopHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesLoopHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncSeriesLoopHook.prototype = null; + +module.exports = AsyncSeriesLoopHook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesWaterfallHook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesWaterfallHook.js new file mode 100644 index 0000000..910b536 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/AsyncSeriesWaterfallHook.js @@ -0,0 +1,47 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncSeriesWaterfallHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onResult: (i, result, next) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += `${this._args[0]} = ${result};\n`; + code += `}\n`; + code += next(); + return code; + }, + onDone: () => onResult(this._args[0]) + }); + } +} + +const factory = new AsyncSeriesWaterfallHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncSeriesWaterfallHook(args = [], name = undefined) { + if (args.length < 1) + throw new Error("Waterfall hooks must have at least one argument"); + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesWaterfallHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncSeriesWaterfallHook.prototype = null; + +module.exports = AsyncSeriesWaterfallHook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/Hook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/Hook.js new file mode 100644 index 0000000..db04426 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/Hook.js @@ -0,0 +1,175 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const util = require("util"); + +const deprecateContext = util.deprecate(() => {}, +"Hook.context is deprecated and will be removed"); + +const CALL_DELEGATE = function(...args) { + this.call = this._createCall("sync"); + return this.call(...args); +}; +const CALL_ASYNC_DELEGATE = function(...args) { + this.callAsync = this._createCall("async"); + return this.callAsync(...args); +}; +const PROMISE_DELEGATE = function(...args) { + this.promise = this._createCall("promise"); + return this.promise(...args); +}; + +class Hook { + constructor(args = [], name = undefined) { + this._args = args; + this.name = name; + this.taps = []; + this.interceptors = []; + this._call = CALL_DELEGATE; + this.call = CALL_DELEGATE; + this._callAsync = CALL_ASYNC_DELEGATE; + this.callAsync = CALL_ASYNC_DELEGATE; + this._promise = PROMISE_DELEGATE; + this.promise = PROMISE_DELEGATE; + this._x = undefined; + + this.compile = this.compile; + this.tap = this.tap; + this.tapAsync = this.tapAsync; + this.tapPromise = this.tapPromise; + } + + compile(options) { + throw new Error("Abstract: should be overridden"); + } + + _createCall(type) { + return this.compile({ + taps: this.taps, + interceptors: this.interceptors, + args: this._args, + type: type + }); + } + + _tap(type, options, fn) { + if (typeof options === "string") { + options = { + name: options.trim() + }; + } else if (typeof options !== "object" || options === null) { + throw new Error("Invalid tap options"); + } + if (typeof options.name !== "string" || options.name === "") { + throw new Error("Missing name for tap"); + } + if (typeof options.context !== "undefined") { + deprecateContext(); + } + options = Object.assign({ type, fn }, options); + options = this._runRegisterInterceptors(options); + this._insert(options); + } + + tap(options, fn) { + this._tap("sync", options, fn); + } + + tapAsync(options, fn) { + this._tap("async", options, fn); + } + + tapPromise(options, fn) { + this._tap("promise", options, fn); + } + + _runRegisterInterceptors(options) { + for (const interceptor of this.interceptors) { + if (interceptor.register) { + const newOptions = interceptor.register(options); + if (newOptions !== undefined) { + options = newOptions; + } + } + } + return options; + } + + withOptions(options) { + const mergeOptions = opt => + Object.assign({}, options, typeof opt === "string" ? { name: opt } : opt); + + return { + name: this.name, + tap: (opt, fn) => this.tap(mergeOptions(opt), fn), + tapAsync: (opt, fn) => this.tapAsync(mergeOptions(opt), fn), + tapPromise: (opt, fn) => this.tapPromise(mergeOptions(opt), fn), + intercept: interceptor => this.intercept(interceptor), + isUsed: () => this.isUsed(), + withOptions: opt => this.withOptions(mergeOptions(opt)) + }; + } + + isUsed() { + return this.taps.length > 0 || this.interceptors.length > 0; + } + + intercept(interceptor) { + this._resetCompilation(); + this.interceptors.push(Object.assign({}, interceptor)); + if (interceptor.register) { + for (let i = 0; i < this.taps.length; i++) { + this.taps[i] = interceptor.register(this.taps[i]); + } + } + } + + _resetCompilation() { + this.call = this._call; + this.callAsync = this._callAsync; + this.promise = this._promise; + } + + _insert(item) { + this._resetCompilation(); + let before; + if (typeof item.before === "string") { + before = new Set([item.before]); + } else if (Array.isArray(item.before)) { + before = new Set(item.before); + } + let stage = 0; + if (typeof item.stage === "number") { + stage = item.stage; + } + let i = this.taps.length; + while (i > 0) { + i--; + const x = this.taps[i]; + this.taps[i + 1] = x; + const xStage = x.stage || 0; + if (before) { + if (before.has(x.name)) { + before.delete(x.name); + continue; + } + if (before.size > 0) { + continue; + } + } + if (xStage > stage) { + continue; + } + i++; + break; + } + this.taps[i] = item; + } +} + +Object.setPrototypeOf(Hook.prototype, null); + +module.exports = Hook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/HookCodeFactory.js b/node_modules/mathjs/examples/node_modules/tapable/lib/HookCodeFactory.js new file mode 100644 index 0000000..c9f5340 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/HookCodeFactory.js @@ -0,0 +1,468 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class HookCodeFactory { + constructor(config) { + this.config = config; + this.options = undefined; + this._args = undefined; + } + + create(options) { + this.init(options); + let fn; + switch (this.options.type) { + case "sync": + fn = new Function( + this.args(), + '"use strict";\n' + + this.header() + + this.contentWithInterceptors({ + onError: err => `throw ${err};\n`, + onResult: result => `return ${result};\n`, + resultReturns: true, + onDone: () => "", + rethrowIfPossible: true + }) + ); + break; + case "async": + fn = new Function( + this.args({ + after: "_callback" + }), + '"use strict";\n' + + this.header() + + this.contentWithInterceptors({ + onError: err => `_callback(${err});\n`, + onResult: result => `_callback(null, ${result});\n`, + onDone: () => "_callback();\n" + }) + ); + break; + case "promise": + let errorHelperUsed = false; + const content = this.contentWithInterceptors({ + onError: err => { + errorHelperUsed = true; + return `_error(${err});\n`; + }, + onResult: result => `_resolve(${result});\n`, + onDone: () => "_resolve();\n" + }); + let code = ""; + code += '"use strict";\n'; + code += this.header(); + code += "return new Promise((function(_resolve, _reject) {\n"; + if (errorHelperUsed) { + code += "var _sync = true;\n"; + code += "function _error(_err) {\n"; + code += "if(_sync)\n"; + code += + "_resolve(Promise.resolve().then((function() { throw _err; })));\n"; + code += "else\n"; + code += "_reject(_err);\n"; + code += "};\n"; + } + code += content; + if (errorHelperUsed) { + code += "_sync = false;\n"; + } + code += "}));\n"; + fn = new Function(this.args(), code); + break; + } + this.deinit(); + return fn; + } + + setup(instance, options) { + instance._x = options.taps.map(t => t.fn); + } + + /** + * @param {{ type: "sync" | "promise" | "async", taps: Array, interceptors: Array }} options + */ + init(options) { + this.options = options; + this._args = options.args.slice(); + } + + deinit() { + this.options = undefined; + this._args = undefined; + } + + contentWithInterceptors(options) { + if (this.options.interceptors.length > 0) { + const onError = options.onError; + const onResult = options.onResult; + const onDone = options.onDone; + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.call) { + code += `${this.getInterceptor(i)}.call(${this.args({ + before: interceptor.context ? "_context" : undefined + })});\n`; + } + } + code += this.content( + Object.assign(options, { + onError: + onError && + (err => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.error) { + code += `${this.getInterceptor(i)}.error(${err});\n`; + } + } + code += onError(err); + return code; + }), + onResult: + onResult && + (result => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.result) { + code += `${this.getInterceptor(i)}.result(${result});\n`; + } + } + code += onResult(result); + return code; + }), + onDone: + onDone && + (() => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.done) { + code += `${this.getInterceptor(i)}.done();\n`; + } + } + code += onDone(); + return code; + }) + }) + ); + return code; + } else { + return this.content(options); + } + } + + header() { + let code = ""; + if (this.needContext()) { + code += "var _context = {};\n"; + } else { + code += "var _context;\n"; + } + code += "var _x = this._x;\n"; + if (this.options.interceptors.length > 0) { + code += "var _taps = this.taps;\n"; + code += "var _interceptors = this.interceptors;\n"; + } + return code; + } + + needContext() { + for (const tap of this.options.taps) if (tap.context) return true; + return false; + } + + callTap(tapIndex, { onError, onResult, onDone, rethrowIfPossible }) { + let code = ""; + let hasTapCached = false; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.tap) { + if (!hasTapCached) { + code += `var _tap${tapIndex} = ${this.getTap(tapIndex)};\n`; + hasTapCached = true; + } + code += `${this.getInterceptor(i)}.tap(${ + interceptor.context ? "_context, " : "" + }_tap${tapIndex});\n`; + } + } + code += `var _fn${tapIndex} = ${this.getTapFn(tapIndex)};\n`; + const tap = this.options.taps[tapIndex]; + switch (tap.type) { + case "sync": + if (!rethrowIfPossible) { + code += `var _hasError${tapIndex} = false;\n`; + code += "try {\n"; + } + if (onResult) { + code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + } else { + code += `_fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + } + if (!rethrowIfPossible) { + code += "} catch(_err) {\n"; + code += `_hasError${tapIndex} = true;\n`; + code += onError("_err"); + code += "}\n"; + code += `if(!_hasError${tapIndex}) {\n`; + } + if (onResult) { + code += onResult(`_result${tapIndex}`); + } + if (onDone) { + code += onDone(); + } + if (!rethrowIfPossible) { + code += "}\n"; + } + break; + case "async": + let cbCode = ""; + if (onResult) + cbCode += `(function(_err${tapIndex}, _result${tapIndex}) {\n`; + else cbCode += `(function(_err${tapIndex}) {\n`; + cbCode += `if(_err${tapIndex}) {\n`; + cbCode += onError(`_err${tapIndex}`); + cbCode += "} else {\n"; + if (onResult) { + cbCode += onResult(`_result${tapIndex}`); + } + if (onDone) { + cbCode += onDone(); + } + cbCode += "}\n"; + cbCode += "})"; + code += `_fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined, + after: cbCode + })});\n`; + break; + case "promise": + code += `var _hasResult${tapIndex} = false;\n`; + code += `var _promise${tapIndex} = _fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + code += `if (!_promise${tapIndex} || !_promise${tapIndex}.then)\n`; + code += ` throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise${tapIndex} + ')');\n`; + code += `_promise${tapIndex}.then((function(_result${tapIndex}) {\n`; + code += `_hasResult${tapIndex} = true;\n`; + if (onResult) { + code += onResult(`_result${tapIndex}`); + } + if (onDone) { + code += onDone(); + } + code += `}), function(_err${tapIndex}) {\n`; + code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`; + code += onError(`_err${tapIndex}`); + code += "});\n"; + break; + } + return code; + } + + callTapsSeries({ + onError, + onResult, + resultReturns, + onDone, + doneReturns, + rethrowIfPossible + }) { + if (this.options.taps.length === 0) return onDone(); + const firstAsync = this.options.taps.findIndex(t => t.type !== "sync"); + const somethingReturns = resultReturns || doneReturns; + let code = ""; + let current = onDone; + let unrollCounter = 0; + for (let j = this.options.taps.length - 1; j >= 0; j--) { + const i = j; + const unroll = + current !== onDone && + (this.options.taps[i].type !== "sync" || unrollCounter++ > 20); + if (unroll) { + unrollCounter = 0; + code += `function _next${i}() {\n`; + code += current(); + code += `}\n`; + current = () => `${somethingReturns ? "return " : ""}_next${i}();\n`; + } + const done = current; + const doneBreak = skipDone => { + if (skipDone) return ""; + return onDone(); + }; + const content = this.callTap(i, { + onError: error => onError(i, error, done, doneBreak), + onResult: + onResult && + (result => { + return onResult(i, result, done, doneBreak); + }), + onDone: !onResult && done, + rethrowIfPossible: + rethrowIfPossible && (firstAsync < 0 || i < firstAsync) + }); + current = () => content; + } + code += current(); + return code; + } + + callTapsLooping({ onError, onDone, rethrowIfPossible }) { + if (this.options.taps.length === 0) return onDone(); + const syncOnly = this.options.taps.every(t => t.type === "sync"); + let code = ""; + if (!syncOnly) { + code += "var _looper = (function() {\n"; + code += "var _loopAsync = false;\n"; + } + code += "var _loop;\n"; + code += "do {\n"; + code += "_loop = false;\n"; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.loop) { + code += `${this.getInterceptor(i)}.loop(${this.args({ + before: interceptor.context ? "_context" : undefined + })});\n`; + } + } + code += this.callTapsSeries({ + onError, + onResult: (i, result, next, doneBreak) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += "_loop = true;\n"; + if (!syncOnly) code += "if(_loopAsync) _looper();\n"; + code += doneBreak(true); + code += `} else {\n`; + code += next(); + code += `}\n`; + return code; + }, + onDone: + onDone && + (() => { + let code = ""; + code += "if(!_loop) {\n"; + code += onDone(); + code += "}\n"; + return code; + }), + rethrowIfPossible: rethrowIfPossible && syncOnly + }); + code += "} while(_loop);\n"; + if (!syncOnly) { + code += "_loopAsync = true;\n"; + code += "});\n"; + code += "_looper();\n"; + } + return code; + } + + callTapsParallel({ + onError, + onResult, + onDone, + rethrowIfPossible, + onTap = (i, run) => run() + }) { + if (this.options.taps.length <= 1) { + return this.callTapsSeries({ + onError, + onResult, + onDone, + rethrowIfPossible + }); + } + let code = ""; + code += "do {\n"; + code += `var _counter = ${this.options.taps.length};\n`; + if (onDone) { + code += "var _done = (function() {\n"; + code += onDone(); + code += "});\n"; + } + for (let i = 0; i < this.options.taps.length; i++) { + const done = () => { + if (onDone) return "if(--_counter === 0) _done();\n"; + else return "--_counter;"; + }; + const doneBreak = skipDone => { + if (skipDone || !onDone) return "_counter = 0;\n"; + else return "_counter = 0;\n_done();\n"; + }; + code += "if(_counter <= 0) break;\n"; + code += onTap( + i, + () => + this.callTap(i, { + onError: error => { + let code = ""; + code += "if(_counter > 0) {\n"; + code += onError(i, error, done, doneBreak); + code += "}\n"; + return code; + }, + onResult: + onResult && + (result => { + let code = ""; + code += "if(_counter > 0) {\n"; + code += onResult(i, result, done, doneBreak); + code += "}\n"; + return code; + }), + onDone: + !onResult && + (() => { + return done(); + }), + rethrowIfPossible + }), + done, + doneBreak + ); + } + code += "} while(false);\n"; + return code; + } + + args({ before, after } = {}) { + let allArgs = this._args; + if (before) allArgs = [before].concat(allArgs); + if (after) allArgs = allArgs.concat(after); + if (allArgs.length === 0) { + return ""; + } else { + return allArgs.join(", "); + } + } + + getTapFn(idx) { + return `_x[${idx}]`; + } + + getTap(idx) { + return `_taps[${idx}]`; + } + + getInterceptor(idx) { + return `_interceptors[${idx}]`; + } +} + +module.exports = HookCodeFactory; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/HookMap.js b/node_modules/mathjs/examples/node_modules/tapable/lib/HookMap.js new file mode 100644 index 0000000..129ad6a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/HookMap.js @@ -0,0 +1,61 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const util = require("util"); + +const defaultFactory = (key, hook) => hook; + +class HookMap { + constructor(factory, name = undefined) { + this._map = new Map(); + this.name = name; + this._factory = factory; + this._interceptors = []; + } + + get(key) { + return this._map.get(key); + } + + for(key) { + const hook = this.get(key); + if (hook !== undefined) { + return hook; + } + let newHook = this._factory(key); + const interceptors = this._interceptors; + for (let i = 0; i < interceptors.length; i++) { + newHook = interceptors[i].factory(key, newHook); + } + this._map.set(key, newHook); + return newHook; + } + + intercept(interceptor) { + this._interceptors.push( + Object.assign( + { + factory: defaultFactory + }, + interceptor + ) + ); + } +} + +HookMap.prototype.tap = util.deprecate(function(key, options, fn) { + return this.for(key).tap(options, fn); +}, "HookMap#tap(key,…) is deprecated. Use HookMap#for(key).tap(…) instead."); + +HookMap.prototype.tapAsync = util.deprecate(function(key, options, fn) { + return this.for(key).tapAsync(options, fn); +}, "HookMap#tapAsync(key,…) is deprecated. Use HookMap#for(key).tapAsync(…) instead."); + +HookMap.prototype.tapPromise = util.deprecate(function(key, options, fn) { + return this.for(key).tapPromise(options, fn); +}, "HookMap#tapPromise(key,…) is deprecated. Use HookMap#for(key).tapPromise(…) instead."); + +module.exports = HookMap; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/MultiHook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/MultiHook.js new file mode 100644 index 0000000..e4fc2ce --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/MultiHook.js @@ -0,0 +1,54 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); + +class MultiHook { + constructor(hooks, name = undefined) { + this.hooks = hooks; + this.name = name; + } + + tap(options, fn) { + for (const hook of this.hooks) { + hook.tap(options, fn); + } + } + + tapAsync(options, fn) { + for (const hook of this.hooks) { + hook.tapAsync(options, fn); + } + } + + tapPromise(options, fn) { + for (const hook of this.hooks) { + hook.tapPromise(options, fn); + } + } + + isUsed() { + for (const hook of this.hooks) { + if (hook.isUsed()) return true; + } + return false; + } + + intercept(interceptor) { + for (const hook of this.hooks) { + hook.intercept(interceptor); + } + } + + withOptions(options) { + return new MultiHook( + this.hooks.map(h => h.withOptions(options)), + this.name + ); + } +} + +module.exports = MultiHook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/SyncBailHook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/SyncBailHook.js new file mode 100644 index 0000000..bdd5b45 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/SyncBailHook.js @@ -0,0 +1,51 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class SyncBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onResult: (i, result, next) => + `if(${result} !== undefined) {\n${onResult( + result + )};\n} else {\n${next()}}\n`, + resultReturns, + onDone, + rethrowIfPossible + }); + } +} + +const factory = new SyncBailHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncBailHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncBailHook"); +}; + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function SyncBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncBailHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; +} + +SyncBailHook.prototype = null; + +module.exports = SyncBailHook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/SyncHook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/SyncHook.js new file mode 100644 index 0000000..e2512be --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/SyncHook.js @@ -0,0 +1,46 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class SyncHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} + +const factory = new SyncHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncHook"); +}; + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function SyncHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; +} + +SyncHook.prototype = null; + +module.exports = SyncHook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/SyncLoopHook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/SyncLoopHook.js new file mode 100644 index 0000000..be0e4fd --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/SyncLoopHook.js @@ -0,0 +1,46 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class SyncLoopHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsLooping({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} + +const factory = new SyncLoopHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncLoopHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncLoopHook"); +}; + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function SyncLoopHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncLoopHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; +} + +SyncLoopHook.prototype = null; + +module.exports = SyncLoopHook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/SyncWaterfallHook.js b/node_modules/mathjs/examples/node_modules/tapable/lib/SyncWaterfallHook.js new file mode 100644 index 0000000..c878b7f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/SyncWaterfallHook.js @@ -0,0 +1,57 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class SyncWaterfallHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onResult: (i, result, next) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += `${this._args[0]} = ${result};\n`; + code += `}\n`; + code += next(); + return code; + }, + onDone: () => onResult(this._args[0]), + doneReturns: resultReturns, + rethrowIfPossible + }); + } +} + +const factory = new SyncWaterfallHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncWaterfallHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncWaterfallHook"); +}; + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function SyncWaterfallHook(args = [], name = undefined) { + if (args.length < 1) + throw new Error("Waterfall hooks must have at least one argument"); + const hook = new Hook(args, name); + hook.constructor = SyncWaterfallHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; +} + +SyncWaterfallHook.prototype = null; + +module.exports = SyncWaterfallHook; diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/index.js b/node_modules/mathjs/examples/node_modules/tapable/lib/index.js new file mode 100644 index 0000000..0a94a53 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/index.js @@ -0,0 +1,19 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +exports.__esModule = true; +exports.SyncHook = require("./SyncHook"); +exports.SyncBailHook = require("./SyncBailHook"); +exports.SyncWaterfallHook = require("./SyncWaterfallHook"); +exports.SyncLoopHook = require("./SyncLoopHook"); +exports.AsyncParallelHook = require("./AsyncParallelHook"); +exports.AsyncParallelBailHook = require("./AsyncParallelBailHook"); +exports.AsyncSeriesHook = require("./AsyncSeriesHook"); +exports.AsyncSeriesBailHook = require("./AsyncSeriesBailHook"); +exports.AsyncSeriesLoopHook = require("./AsyncSeriesLoopHook"); +exports.AsyncSeriesWaterfallHook = require("./AsyncSeriesWaterfallHook"); +exports.HookMap = require("./HookMap"); +exports.MultiHook = require("./MultiHook"); diff --git a/node_modules/mathjs/examples/node_modules/tapable/lib/util-browser.js b/node_modules/mathjs/examples/node_modules/tapable/lib/util-browser.js new file mode 100644 index 0000000..ee4fb9a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/lib/util-browser.js @@ -0,0 +1,16 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +exports.deprecate = (fn, msg) => { + let once = true; + return function() { + if (once) { + console.warn("DeprecationWarning: " + msg); + once = false; + } + return fn.apply(this, arguments); + }; +}; diff --git a/node_modules/mathjs/examples/node_modules/tapable/package.json b/node_modules/mathjs/examples/node_modules/tapable/package.json new file mode 100644 index 0000000..3c13120 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/package.json @@ -0,0 +1,44 @@ +{ + "name": "tapable", + "version": "2.2.1", + "author": "Tobias Koppers @sokra", + "description": "Just a little module for plugins.", + "license": "MIT", + "homepage": "https://github.com/webpack/tapable", + "repository": { + "type": "git", + "url": "http://github.com/webpack/tapable.git" + }, + "devDependencies": { + "@babel/core": "^7.4.4", + "@babel/preset-env": "^7.4.4", + "babel-jest": "^24.8.0", + "codecov": "^3.5.0", + "jest": "^24.8.0", + "prettier": "^1.17.1" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "lib", + "!lib/__tests__", + "tapable.d.ts" + ], + "main": "lib/index.js", + "types": "./tapable.d.ts", + "browser": { + "util": "./lib/util-browser.js" + }, + "scripts": { + "test": "jest", + "travis": "yarn pretty-lint && jest --coverage && codecov", + "pretty-lint": "prettier --check lib/*.js lib/__tests__/*.js", + "pretty": "prettier --loglevel warn --write lib/*.js lib/__tests__/*.js" + }, + "jest": { + "transform": { + "__tests__[\\\\/].+\\.js$": "babel-jest" + } + } +} diff --git a/node_modules/mathjs/examples/node_modules/tapable/tapable.d.ts b/node_modules/mathjs/examples/node_modules/tapable/tapable.d.ts new file mode 100644 index 0000000..0201c9a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/tapable/tapable.d.ts @@ -0,0 +1,116 @@ +type FixedSizeArray = T extends 0 + ? void[] + : ReadonlyArray & { + 0: U; + length: T; + }; +type Measure = T extends 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 + ? T + : never; +type Append = { + 0: [U]; + 1: [T[0], U]; + 2: [T[0], T[1], U]; + 3: [T[0], T[1], T[2], U]; + 4: [T[0], T[1], T[2], T[3], U]; + 5: [T[0], T[1], T[2], T[3], T[4], U]; + 6: [T[0], T[1], T[2], T[3], T[4], T[5], U]; + 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], U]; + 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], U]; +}[Measure]; +type AsArray = T extends any[] ? T : [T]; + +declare class UnsetAdditionalOptions { + _UnsetAdditionalOptions: true +} +type IfSet = X extends UnsetAdditionalOptions ? {} : X; + +type Callback = (error: E | null, result?: T) => void; +type InnerCallback = (error?: E | null | false, result?: T) => void; + +type FullTap = Tap & { + type: "sync" | "async" | "promise", + fn: Function +} + +type Tap = TapOptions & { + name: string; +}; + +type TapOptions = { + before?: string; + stage?: number; +}; + +interface HookInterceptor { + name?: string; + tap?: (tap: FullTap & IfSet) => void; + call?: (...args: any[]) => void; + loop?: (...args: any[]) => void; + error?: (err: Error) => void; + result?: (result: R) => void; + done?: () => void; + register?: (tap: FullTap & IfSet) => FullTap & IfSet; +} + +type ArgumentNames = FixedSizeArray; + +declare class Hook { + constructor(args?: ArgumentNames>, name?: string); + name: string | undefined; + taps: FullTap[]; + intercept(interceptor: HookInterceptor): void; + isUsed(): boolean; + callAsync(...args: Append, Callback>): void; + promise(...args: AsArray): Promise; + tap(options: string | Tap & IfSet, fn: (...args: AsArray) => R): void; + withOptions(options: TapOptions & IfSet): Omit; +} + +export class SyncHook extends Hook { + call(...args: AsArray): R; +} + +export class SyncBailHook extends SyncHook {} +export class SyncLoopHook extends SyncHook {} +export class SyncWaterfallHook extends SyncHook[0], AdditionalOptions> {} + +declare class AsyncHook extends Hook { + tapAsync( + options: string | Tap & IfSet, + fn: (...args: Append, InnerCallback>) => void + ): void; + tapPromise( + options: string | Tap & IfSet, + fn: (...args: AsArray) => Promise + ): void; +} + +export class AsyncParallelHook extends AsyncHook {} +export class AsyncParallelBailHook extends AsyncHook {} +export class AsyncSeriesHook extends AsyncHook {} +export class AsyncSeriesBailHook extends AsyncHook {} +export class AsyncSeriesLoopHook extends AsyncHook {} +export class AsyncSeriesWaterfallHook extends AsyncHook[0], AdditionalOptions> {} + +type HookFactory = (key: any, hook?: H) => H; + +interface HookMapInterceptor { + factory?: HookFactory; +} + +export class HookMap { + constructor(factory: HookFactory, name?: string); + name: string | undefined; + get(key: any): H | undefined; + for(key: any): H; + intercept(interceptor: HookMapInterceptor): void; +} + +export class MultiHook { + constructor(hooks: H[], name?: string); + name: string | undefined; + tap(options: string | Tap, fn?: Function): void; + tapAsync(options: string | Tap, fn?: Function): void; + tapPromise(options: string | Tap, fn?: Function): void; +} diff --git a/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/LICENSE b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/LICENSE new file mode 100644 index 0000000..8c11fc7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +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. diff --git a/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/README.md b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/README.md new file mode 100644 index 0000000..9687223 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/README.md @@ -0,0 +1,742 @@ + + +[![npm][npm]][npm-url] +[![node][node]][node-url] +[![deps][deps]][deps-url] +[![tests][tests]][tests-url] +[![cover][cover]][cover-url] +[![chat][chat]][chat-url] +[![size][size]][size-url] + +# terser-webpack-plugin + +This plugin uses [terser](https://github.com/terser/terser) to minify/minimize your JavaScript. + +## Getting Started + +Webpack v5 comes with the latest `terser-webpack-plugin` out of the box. If you are using Webpack v5 or above and wish to customize the options, you will still need to install `terser-webpack-plugin`. Using Webpack v4, you have to install `terser-webpack-plugin` v4. + +To begin, you'll need to install `terser-webpack-plugin`: + +```console +$ npm install terser-webpack-plugin --save-dev +``` + +Then add the plugin to your `webpack` config. For example: + +**webpack.config.js** + +```js +const TerserPlugin = require("terser-webpack-plugin"); + +module.exports = { + optimization: { + minimize: true, + minimizer: [new TerserPlugin()], + }, +}; +``` + +And run `webpack` via your preferred method. + +## Note about source maps + +**Works only with `source-map`, `inline-source-map`, `hidden-source-map` and `nosources-source-map` values for the [`devtool`](https://webpack.js.org/configuration/devtool/) option.** + +Why? + +- `eval` wraps modules in `eval("string")` and the minimizer does not handle strings. +- `cheap` has not column information and minimizer generate only a single line, which leave only a single mapping. + +Using supported `devtool` values enable source map generation. + +## Options + +| Name | Type | Default | Description | +| :---------------------------------------: | :-----------------------------------------------------------------------------: | :----------------------------------------------------------: | :------------------------------------------------------------------------ | +| **[`test`](#test)** | `String\|RegExp\|Array` | `/\.m?js(\?.*)?$/i` | Test to match files against. | +| **[`include`](#include)** | `String\|RegExp\|Array` | `undefined` | Files to include. | +| **[`exclude`](#exclude)** | `String\|RegExp\|Array` | `undefined` | Files to exclude. | +| **[`parallel`](#parallel)** | `Boolean\|Number` | `true` | Use multi-process parallel running to improve the build speed. | +| **[`minify`](#minify)** | `Function` | `TerserPlugin.terserMinify` | Allows you to override default minify function. | +| **[`terserOptions`](#terseroptions)** | `Object` | [`default`](https://github.com/terser/terser#minify-options) | Terser [minify options](https://github.com/terser/terser#minify-options). | +| **[`extractComments`](#extractcomments)** | `Boolean\|String\|RegExp\|Function<(node, comment) -> Boolean\|Object>\|Object` | `true` | Whether comments shall be extracted to a separate file. | + +### `test` + +Type: `String|RegExp|Array` +Default: `/\.m?js(\?.*)?$/i` + +Test to match files against. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + test: /\.js(\?.*)?$/i, + }), + ], + }, +}; +``` + +### `include` + +Type: `String|RegExp|Array` +Default: `undefined` + +Files to include. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + include: /\/includes/, + }), + ], + }, +}; +``` + +### `exclude` + +Type: `String|RegExp|Array` +Default: `undefined` + +Files to exclude. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + exclude: /\/excludes/, + }), + ], + }, +}; +``` + +### `parallel` + +Type: `Boolean|Number` +Default: `true` + +Use multi-process parallel running to improve the build speed. +Default number of concurrent runs: `os.cpus().length - 1`. + +> ℹ️ Parallelization can speedup your build significantly and is therefore **highly recommended**. + +> ⚠️ If you use **Circle CI** or any other environment that doesn't provide real available count of CPUs then you need to setup explicitly number of CPUs to avoid `Error: Call retries were exceeded` (see [#143](https://github.com/webpack-contrib/terser-webpack-plugin/issues/143), [#202](https://github.com/webpack-contrib/terser-webpack-plugin/issues/202)). + +#### `Boolean` + +Enable/disable multi-process parallel running. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + parallel: true, + }), + ], + }, +}; +``` + +#### `Number` + +Enable multi-process parallel running and set number of concurrent runs. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + parallel: 4, + }), + ], + }, +}; +``` + +### `minify` + +Type: `Function` +Default: `TerserPlugin.terserMinify` + +Allows you to override default minify function. +By default plugin uses [terser](https://github.com/terser/terser) package. +Useful for using and testing unpublished versions or forks. + +> ⚠️ **Always use `require` inside `minify` function when `parallel` option enabled**. + +**webpack.config.js** + +```js +// Can be async +const minify = (input, sourceMap, minimizerOptions, extractsComments) => { + // The `minimizerOptions` option contains option from the `terserOptions` option + // You can use `minimizerOptions.myCustomOption` + + // Custom logic for extract comments + const { map, code } = require("uglify-module") // Or require('./path/to/uglify-module') + .minify(input, { + /* Your options for minification */ + }); + + return { map, code, warnings: [], errors: [], extractedComments: [] }; +}; + +// Used to regenerate `fullhash`/`chunkhash` between different implementation +// Example: you fix a bug in custom minimizer/custom function, but unfortunately webpack doesn't know about it, so you will get the same fullhash/chunkhash +// to avoid this you can provide version of your custom minimizer +// You don't need if you use only `contenthash` +minify.getMinimizerVersion = () => { + let packageJson; + + try { + // eslint-disable-next-line global-require, import/no-extraneous-dependencies + packageJson = require("uglify-module/package.json"); + } catch (error) { + // Ignore + } + + return packageJson && packageJson.version; +}; + +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + myCustomOption: true, + }, + minify, + }), + ], + }, +}; +``` + +### `terserOptions` + +Type: `Object` +Default: [default](https://github.com/terser/terser#minify-options) + +Terser [options](https://github.com/terser/terser#minify-options). + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + ecma: undefined, + parse: {}, + compress: {}, + mangle: true, // Note `mangle.properties` is `false` by default. + module: false, + // Deprecated + output: null, + format: null, + toplevel: false, + nameCache: null, + ie8: false, + keep_classnames: undefined, + keep_fnames: false, + safari10: false, + }, + }), + ], + }, +}; +``` + +### `extractComments` + +Type: `Boolean|String|RegExp|Function<(node, comment) -> Boolean|Object>|Object` +Default: `true` + +Whether comments shall be extracted to a separate file, (see [details](https://github.com/webpack/webpack/commit/71933e979e51c533b432658d5e37917f9e71595a)). +By default extract only comments using `/^\**!|@preserve|@license|@cc_on/i` regexp condition and remove remaining comments. +If the original file is named `foo.js`, then the comments will be stored to `foo.js.LICENSE.txt`. +The `terserOptions.format.comments` option specifies whether the comment will be preserved, i.e. it is possible to preserve some comments (e.g. annotations) while extracting others or even preserving comments that have been extracted. + +#### `Boolean` + +Enable/disable extracting comments. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: true, + }), + ], + }, +}; +``` + +#### `String` + +Extract `all` or `some` (use `/^\**!|@preserve|@license|@cc_on/i` RegExp) comments. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: "all", + }), + ], + }, +}; +``` + +#### `RegExp` + +All comments that match the given expression will be extracted to the separate file. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: /@extract/i, + }), + ], + }, +}; +``` + +#### `Function<(node, comment) -> Boolean>` + +All comments that match the given expression will be extracted to the separate file. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: (astNode, comment) => { + if (/@extract/i.test(comment.value)) { + return true; + } + + return false; + }, + }), + ], + }, +}; +``` + +#### `Object` + +Allow to customize condition for extract comments, specify extracted file name and banner. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: { + condition: /^\**!|@preserve|@license|@cc_on/i, + filename: (fileData) => { + // The "fileData" argument contains object with "filename", "basename", "query" and "hash" + return `${fileData.filename}.LICENSE.txt${fileData.query}`; + }, + banner: (licenseFile) => { + return `License information can be found in ${licenseFile}`; + }, + }, + }), + ], + }, +}; +``` + +##### `condition` + +Type: `Boolean|String|RegExp|Function<(node, comment) -> Boolean|Object>` + +Condition what comments you need extract. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: { + condition: "some", + filename: (fileData) => { + // The "fileData" argument contains object with "filename", "basename", "query" and "hash" + return `${fileData.filename}.LICENSE.txt${fileData.query}`; + }, + banner: (licenseFile) => { + return `License information can be found in ${licenseFile}`; + }, + }, + }), + ], + }, +}; +``` + +##### `filename` + +Type: `String|Function<(string) -> String>` +Default: `[file].LICENSE.txt[query]` + +Available placeholders: `[file]`, `[query]` and `[filebase]` (`[base]` for webpack 5). + +The file where the extracted comments will be stored. +Default is to append the suffix `.LICENSE.txt` to the original filename. + +> ⚠️ We highly recommend using the `txt` extension. Using `js`/`cjs`/`mjs` extensions may conflict with existing assets which leads to broken code. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: { + condition: /^\**!|@preserve|@license|@cc_on/i, + filename: "extracted-comments.js", + banner: (licenseFile) => { + return `License information can be found in ${licenseFile}`; + }, + }, + }), + ], + }, +}; +``` + +##### `banner` + +Type: `Boolean|String|Function<(string) -> String>` +Default: `/*! For license information please see ${commentsFile} */` + +The banner text that points to the extracted file and will be added on top of the original file. +Can be `false` (no banner), a `String`, or a `Function<(string) -> String>` that will be called with the filename where extracted comments have been stored. +Will be wrapped into comment. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: { + condition: true, + filename: (fileData) => { + // The "fileData" argument contains object with "filename", "basename", "query" and "hash" + return `${fileData.filename}.LICENSE.txt${fileData.query}`; + }, + banner: (commentsFile) => { + return `My custom banner about license information ${commentsFile}`; + }, + }, + }), + ], + }, +}; +``` + +## Examples + +### Preserve Comments + +Extract all legal comments (i.e. `/^\**!|@preserve|@license|@cc_on/i`) and preserve `/@license/i` comments. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + format: { + comments: /@license/i, + }, + }, + extractComments: true, + }), + ], + }, +}; +``` + +### Remove Comments + +If you avoid building with comments, use this config: + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + format: { + comments: false, + }, + }, + extractComments: false, + }), + ], + }, +}; +``` + +### [`uglify-js`](https://github.com/mishoo/UglifyJS) + +[`UglifyJS`](https://github.com/mishoo/UglifyJS) is a JavaScript parser, minifier, compressor and beautifier toolkit. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + minify: TerserPlugin.uglifyJsMinify, + // `terserOptions` options will be passed to `uglify-js` + // Link to options - https://github.com/mishoo/UglifyJS#minify-options + terserOptions: {}, + }), + ], + }, +}; +``` + +### [`swc`](https://github.com/swc-project/swc) + +[`swc`](https://github.com/swc-project/swc) is a super-fast compiler written in rust; producing widely-supported javascript from modern standards and typescript. + +> ⚠ the `extractComments` option is not supported and all comments will be removed by default, it will be fixed in future + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + minify: TerserPlugin.swcMinify, + // `terserOptions` options will be passed to `swc` (`@swc/core`) + // Link to options - https://swc.rs/docs/config-js-minify + terserOptions: {}, + }), + ], + }, +}; +``` + +### [`esbuild`](https://github.com/evanw/esbuild) + +[`esbuild`](https://github.com/evanw/esbuild) is an extremely fast JavaScript bundler and minifier. + +> ⚠ the `extractComments` option is not supported and all legal comments (i.e. copyright, licenses and etc) will be preserved + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + minify: TerserPlugin.esbuildMinify, + // `terserOptions` options will be passed to `esbuild` + // Link to options - https://esbuild.github.io/api/#minify + // Note: the `minify` options is true by default (and override other `minify*` options), so if you want to disable the `minifyIdentifiers` option (or other `minify*` options) please use: + // terserOptions: { + // minify: false, + // minifyWhitespace: true, + // minifyIdentifiers: false, + // minifySyntax: true, + // }, + terserOptions: {}, + }), + ], + }, +}; +``` + +### Custom Minify Function + +Override default minify function - use `uglify-js` for minification. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + minify: (file, sourceMap) => { + // https://github.com/mishoo/UglifyJS2#minify-options + const uglifyJsOptions = { + /* your `uglify-js` package options */ + }; + + if (sourceMap) { + uglifyJsOptions.sourceMap = { + content: sourceMap, + }; + } + + return require("uglify-js").minify(file, uglifyJsOptions); + }, + }), + ], + }, +}; +``` + +### Typescript + +With default terser minify function: + +```ts +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + compress: true, + }, + }), + ], + }, +}; +``` + +With built-in minify functions: + +```ts +import type { JsMinifyOptions as SwcOptions } from "@swc/core"; +import type { MinifyOptions as UglifyJSOptions } from "uglify-js"; +import type { TransformOptions as EsbuildOptions } from "esbuild"; +import type { MinifyOptions as TerserOptions } from "terser"; + +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + minify: TerserPlugin.swcMinify, + terserOptions: { + // `swc` options + }, + }), + new TerserPlugin({ + minify: TerserPlugin.uglifyJsMinify, + terserOptions: { + // `uglif-js` options + }, + }), + new TerserPlugin({ + minify: TerserPlugin.esbuildMinify, + terserOptions: { + // `esbuild` options + }, + }), + + // Alternative usage: + new TerserPlugin({ + minify: TerserPlugin.terserMinify, + terserOptions: { + // `terser` options + }, + }), + ], + }, +}; +``` + +## Contributing + +Please take a moment to read our contributing guidelines if you haven't yet done so. + +[CONTRIBUTING](./.github/CONTRIBUTING.md) + +## License + +[MIT](./LICENSE) + +[npm]: https://img.shields.io/npm/v/terser-webpack-plugin.svg +[npm-url]: https://npmjs.com/package/terser-webpack-plugin +[node]: https://img.shields.io/node/v/terser-webpack-plugin.svg +[node-url]: https://nodejs.org +[deps]: https://david-dm.org/webpack-contrib/terser-webpack-plugin.svg +[deps-url]: https://david-dm.org/webpack-contrib/terser-webpack-plugin +[tests]: https://github.com/webpack-contrib/terser-webpack-plugin/workflows/terser-webpack-plugin/badge.svg +[tests-url]: https://github.com/webpack-contrib/terser-webpack-plugin/actions +[cover]: https://codecov.io/gh/webpack-contrib/terser-webpack-plugin/branch/master/graph/badge.svg +[cover-url]: https://codecov.io/gh/webpack-contrib/terser-webpack-plugin +[chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg +[chat-url]: https://gitter.im/webpack/webpack +[size]: https://packagephobia.now.sh/badge?p=terser-webpack-plugin +[size-url]: https://packagephobia.now.sh/result?p=terser-webpack-plugin diff --git a/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/index.js b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/index.js new file mode 100644 index 0000000..ec69fad --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/index.js @@ -0,0 +1,798 @@ +"use strict"; + +const path = require("path"); + +const os = require("os"); + +const { + SourceMapConsumer +} = require("source-map"); + +const { + validate +} = require("schema-utils"); + +const serialize = require("serialize-javascript"); + +const { + Worker +} = require("jest-worker"); + +const { + throttleAll, + terserMinify, + uglifyJsMinify, + swcMinify, + esbuildMinify +} = require("./utils"); + +const schema = require("./options.json"); + +const { + minify +} = require("./minify"); +/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */ + +/** @typedef {import("webpack").Compiler} Compiler */ + +/** @typedef {import("webpack").Compilation} Compilation */ + +/** @typedef {import("webpack").WebpackError} WebpackError */ + +/** @typedef {import("webpack").Asset} Asset */ + +/** @typedef {import("./utils.js").TerserECMA} TerserECMA */ + +/** @typedef {import("./utils.js").TerserOptions} TerserOptions */ + +/** @typedef {import("jest-worker").Worker} JestWorker */ + +/** @typedef {import("source-map").RawSourceMap} RawSourceMap */ + +/** @typedef {RegExp | string} Rule */ + +/** @typedef {Rule[] | Rule} Rules */ + +/** + * @callback ExtractCommentsFunction + * @param {any} astNode + * @param {{ value: string, type: 'comment1' | 'comment2' | 'comment3' | 'comment4', pos: number, line: number, col: number }} comment + * @returns {boolean} + */ + +/** + * @typedef {boolean | 'all' | 'some' | RegExp | ExtractCommentsFunction} ExtractCommentsCondition + */ + +/** + * @typedef {string | ((fileData: any) => string)} ExtractCommentsFilename + */ + +/** + * @typedef {boolean | string | ((commentsFile: string) => string)} ExtractCommentsBanner + */ + +/** + * @typedef {Object} ExtractCommentsObject + * @property {ExtractCommentsCondition} [condition] + * @property {ExtractCommentsFilename} [filename] + * @property {ExtractCommentsBanner} [banner] + */ + +/** + * @typedef {ExtractCommentsCondition | ExtractCommentsObject} ExtractCommentsOptions + */ + +/** + * @typedef {Object} MinimizedResult + * @property {string} code + * @property {RawSourceMap} [map] + * @property {Array} [errors] + * @property {Array} [warnings] + * @property {Array} [extractedComments] + */ + +/** + * @typedef {{ [file: string]: string }} Input + */ + +/** + * @typedef {{ [key: string]: any }} CustomOptions + */ + +/** + * @template T + * @typedef {T extends infer U ? U : CustomOptions} InferDefaultType + */ + +/** + * @typedef {Object} PredefinedOptions + * @property {boolean} [module] + * @property {TerserECMA} [ecma] + */ + +/** + * @template T + * @typedef {PredefinedOptions & InferDefaultType} MinimizerOptions + */ + +/** + * @template T + * @callback BasicMinimizerImplementation + * @param {Input} input + * @param {RawSourceMap | undefined} sourceMap + * @param {MinimizerOptions} minifyOptions + * @param {ExtractCommentsOptions | undefined} extractComments + * @returns {Promise} + */ + +/** + * @typedef {object} MinimizeFunctionHelpers + * @property {() => string | undefined} [getMinimizerVersion] + */ + +/** + * @template T + * @typedef {BasicMinimizerImplementation & MinimizeFunctionHelpers} MinimizerImplementation + */ + +/** + * @template T + * @typedef {Object} InternalOptions + * @property {string} name + * @property {string} input + * @property {RawSourceMap | undefined} inputSourceMap + * @property {ExtractCommentsOptions | undefined} extractComments + * @property {{ implementation: MinimizerImplementation, options: MinimizerOptions }} minimizer + */ + +/** + * @template T + * @typedef {JestWorker & { transform: (options: string) => MinimizedResult, minify: (options: InternalOptions) => MinimizedResult }} MinimizerWorker + */ + +/** + * @typedef {undefined | boolean | number} Parallel + */ + +/** + * @typedef {Object} BasePluginOptions + * @property {Rules} [test] + * @property {Rules} [include] + * @property {Rules} [exclude] + * @property {ExtractCommentsOptions} [extractComments] + * @property {Parallel} [parallel] + */ + +/** + * @template T + * @typedef {T extends TerserOptions ? { minify?: MinimizerImplementation | undefined, terserOptions?: MinimizerOptions | undefined } : { minify: MinimizerImplementation, terserOptions?: MinimizerOptions | undefined }} DefinedDefaultMinimizerAndOptions + */ + +/** + * @template T + * @typedef {BasePluginOptions & { minimizer: { implementation: MinimizerImplementation, options: MinimizerOptions } }} InternalPluginOptions + */ + +/** + * @template [T=TerserOptions] + */ + + +class TerserPlugin { + /** + * @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions} [options] + */ + constructor(options) { + validate( + /** @type {Schema} */ + schema, options || {}, { + name: "Terser Plugin", + baseDataPath: "options" + }); // TODO make `minimizer` option instead `minify` and `terserOptions` in the next major release, also rename `terserMinify` to `terserMinimize` + + const { + minify = + /** @type {MinimizerImplementation} */ + terserMinify, + terserOptions = + /** @type {MinimizerOptions} */ + {}, + test = /\.[cm]?js(\?.*)?$/i, + extractComments = true, + parallel = true, + include, + exclude + } = options || {}; + /** + * @private + * @type {InternalPluginOptions} + */ + + this.options = { + test, + extractComments, + parallel, + include, + exclude, + minimizer: { + implementation: minify, + options: terserOptions + } + }; + } + /** + * @private + * @param {any} input + * @returns {boolean} + */ + + + static isSourceMap(input) { + // All required options for `new SourceMapConsumer(...options)` + // https://github.com/mozilla/source-map#new-sourcemapconsumerrawsourcemap + return Boolean(input && input.version && input.sources && Array.isArray(input.sources) && typeof input.mappings === "string"); + } + /** + * @private + * @param {unknown} warning + * @param {string} file + * @returns {Error} + */ + + + static buildWarning(warning, file) { + /** + * @type {Error & { hideStack: true, file: string }} + */ + // @ts-ignore + const builtWarning = new Error(warning.toString()); + builtWarning.name = "Warning"; + builtWarning.hideStack = true; + builtWarning.file = file; + return builtWarning; + } + /** + * @private + * @param {any} error + * @param {string} file + * @param {SourceMapConsumer} [sourceMap] + * @param {Compilation["requestShortener"]} [requestShortener] + * @returns {Error} + */ + + + static buildError(error, file, sourceMap, requestShortener) { + /** + * @type {Error & { file?: string }} + */ + let builtError; + + if (typeof error === "string") { + builtError = new Error(`${file} from Terser plugin\n${error}`); + builtError.file = file; + return builtError; + } + + if (error.line) { + const original = sourceMap && sourceMap.originalPositionFor({ + line: error.line, + column: error.col + }); + + if (original && original.source && requestShortener) { + builtError = new Error(`${file} from Terser plugin\n${error.message} [${requestShortener.shorten(original.source)}:${original.line},${original.column}][${file}:${error.line},${error.col}]${error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""}`); + builtError.file = file; + return builtError; + } + + builtError = new Error(`${file} from Terser plugin\n${error.message} [${file}:${error.line},${error.col}]${error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""}`); + builtError.file = file; + return builtError; + } + + if (error.stack) { + builtError = new Error(`${file} from Terser plugin\n${typeof error.message !== "undefined" ? error.message : ""}\n${error.stack}`); + builtError.file = file; + return builtError; + } + + builtError = new Error(`${file} from Terser plugin\n${error.message}`); + builtError.file = file; + return builtError; + } + /** + * @private + * @param {Parallel} parallel + * @returns {number} + */ + + + static getAvailableNumberOfCores(parallel) { + // In some cases cpus() returns undefined + // https://github.com/nodejs/node/issues/19022 + const cpus = os.cpus() || { + length: 1 + }; + return parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1); + } + /** + * @private + * @param {Compiler} compiler + * @param {Compilation} compilation + * @param {Record} assets + * @param {{availableNumberOfCores: number}} optimizeOptions + * @returns {Promise} + */ + + + async optimize(compiler, compilation, assets, optimizeOptions) { + const cache = compilation.getCache("TerserWebpackPlugin"); + let numberOfAssets = 0; + const assetsForMinify = await Promise.all(Object.keys(assets).filter(name => { + const { + info + } = + /** @type {Asset} */ + compilation.getAsset(name); + + if ( // Skip double minimize assets from child compilation + info.minimized || // Skip minimizing for extracted comments assets + info.extractedComments) { + return false; + } + + if (!compiler.webpack.ModuleFilenameHelpers.matchObject.bind( // eslint-disable-next-line no-undefined + undefined, this.options)(name)) { + return false; + } + + return true; + }).map(async name => { + const { + info, + source + } = + /** @type {Asset} */ + compilation.getAsset(name); + const eTag = cache.getLazyHashedEtag(source); + const cacheItem = cache.getItemCache(name, eTag); + const output = await cacheItem.getPromise(); + + if (!output) { + numberOfAssets += 1; + } + + return { + name, + info, + inputSource: source, + output, + cacheItem + }; + })); + + if (assetsForMinify.length === 0) { + return; + } + /** @type {undefined | (() => MinimizerWorker)} */ + + + let getWorker; + /** @type {undefined | MinimizerWorker} */ + + let initializedWorker; + /** @type {undefined | number} */ + + let numberOfWorkers; + + if (optimizeOptions.availableNumberOfCores > 0) { + // Do not create unnecessary workers when the number of files is less than the available cores, it saves memory + numberOfWorkers = Math.min(numberOfAssets, optimizeOptions.availableNumberOfCores); // eslint-disable-next-line consistent-return + + getWorker = () => { + if (initializedWorker) { + return initializedWorker; + } + + initializedWorker = + /** @type {MinimizerWorker} */ + new Worker(require.resolve("./minify"), { + numWorkers: numberOfWorkers, + enableWorkerThreads: true + }); // https://github.com/facebook/jest/issues/8872#issuecomment-524822081 + + const workerStdout = initializedWorker.getStdout(); + + if (workerStdout) { + workerStdout.on("data", chunk => process.stdout.write(chunk)); + } + + const workerStderr = initializedWorker.getStderr(); + + if (workerStderr) { + workerStderr.on("data", chunk => process.stderr.write(chunk)); + } + + return initializedWorker; + }; + } + + const { + SourceMapSource, + ConcatSource, + RawSource + } = compiler.webpack.sources; + /** @typedef {{ extractedCommentsSource : import("webpack").sources.RawSource, commentsFilename: string }} ExtractedCommentsInfo */ + + /** @type {Map} */ + + const allExtractedComments = new Map(); + const scheduledTasks = []; + + for (const asset of assetsForMinify) { + scheduledTasks.push(async () => { + const { + name, + inputSource, + info, + cacheItem + } = asset; + let { + output + } = asset; + + if (!output) { + let input; + /** @type {RawSourceMap | undefined} */ + + let inputSourceMap; + const { + source: sourceFromInputSource, + map + } = inputSource.sourceAndMap(); + input = sourceFromInputSource; + + if (map) { + if (!TerserPlugin.isSourceMap(map)) { + compilation.warnings.push( + /** @type {WebpackError} */ + new Error(`${name} contains invalid source map`)); + } else { + inputSourceMap = + /** @type {RawSourceMap} */ + map; + } + } + + if (Buffer.isBuffer(input)) { + input = input.toString(); + } + /** + * @type {InternalOptions} + */ + + + const options = { + name, + input, + inputSourceMap, + minimizer: { + implementation: this.options.minimizer.implementation, + // @ts-ignore https://github.com/Microsoft/TypeScript/issues/10727 + options: { ...this.options.minimizer.options + } + }, + extractComments: this.options.extractComments + }; + + if (typeof options.minimizer.options.module === "undefined") { + if (typeof info.javascriptModule !== "undefined") { + options.minimizer.options.module = info.javascriptModule; + } else if (/\.mjs(\?.*)?$/i.test(name)) { + options.minimizer.options.module = true; + } else if (/\.cjs(\?.*)?$/i.test(name)) { + options.minimizer.options.module = false; + } + } + + if (typeof options.minimizer.options.ecma === "undefined") { + options.minimizer.options.ecma = TerserPlugin.getEcmaVersion(compiler.options.output.environment || {}); + } + + try { + output = await (getWorker ? getWorker().transform(serialize(options)) : minify(options)); + } catch (error) { + const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap); + compilation.errors.push( + /** @type {WebpackError} */ + TerserPlugin.buildError(error, name, hasSourceMap ? new SourceMapConsumer( + /** @type {RawSourceMap} */ + inputSourceMap) : // eslint-disable-next-line no-undefined + undefined, // eslint-disable-next-line no-undefined + hasSourceMap ? compilation.requestShortener : undefined)); + return; + } + + if (typeof output.code === "undefined") { + compilation.errors.push( + /** @type {WebpackError} */ + new Error(`${name} from Terser plugin\nMinimizer doesn't return result`)); + return; + } + + if (output.warnings && output.warnings.length > 0) { + output.warnings = output.warnings.map( + /** + * @param {Error | string} item + */ + item => TerserPlugin.buildWarning(item, name)); + } + + if (output.errors && output.errors.length > 0) { + const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap); + output.errors = output.errors.map( + /** + * @param {Error | string} item + */ + item => TerserPlugin.buildError(item, name, hasSourceMap ? new SourceMapConsumer( + /** @type {RawSourceMap} */ + inputSourceMap) : // eslint-disable-next-line no-undefined + undefined, // eslint-disable-next-line no-undefined + hasSourceMap ? compilation.requestShortener : undefined)); + } + + let shebang; + + if ( + /** @type {ExtractCommentsObject} */ + this.options.extractComments.banner !== false && output.extractedComments && output.extractedComments.length > 0 && output.code.startsWith("#!")) { + const firstNewlinePosition = output.code.indexOf("\n"); + shebang = output.code.substring(0, firstNewlinePosition); + output.code = output.code.substring(firstNewlinePosition + 1); + } + + if (output.map) { + output.source = new SourceMapSource(output.code, name, output.map, input, + /** @type {RawSourceMap} */ + inputSourceMap, true); + } else { + output.source = new RawSource(output.code); + } + + if (output.extractedComments && output.extractedComments.length > 0) { + const commentsFilename = + /** @type {ExtractCommentsObject} */ + this.options.extractComments.filename || "[file].LICENSE.txt[query]"; + let query = ""; + let filename = name; + const querySplit = filename.indexOf("?"); + + if (querySplit >= 0) { + query = filename.substr(querySplit); + filename = filename.substr(0, querySplit); + } + + const lastSlashIndex = filename.lastIndexOf("/"); + const basename = lastSlashIndex === -1 ? filename : filename.substr(lastSlashIndex + 1); + const data = { + filename, + basename, + query + }; + output.commentsFilename = compilation.getPath(commentsFilename, data); + let banner; // Add a banner to the original file + + if ( + /** @type {ExtractCommentsObject} */ + this.options.extractComments.banner !== false) { + banner = + /** @type {ExtractCommentsObject} */ + this.options.extractComments.banner || `For license information please see ${path.relative(path.dirname(name), output.commentsFilename).replace(/\\/g, "/")}`; + + if (typeof banner === "function") { + banner = banner(output.commentsFilename); + } + + if (banner) { + output.source = new ConcatSource(shebang ? `${shebang}\n` : "", `/*! ${banner} */\n`, output.source); + } + } + + const extractedCommentsString = output.extractedComments.sort().join("\n\n"); + output.extractedCommentsSource = new RawSource(`${extractedCommentsString}\n`); + } + + await cacheItem.storePromise({ + source: output.source, + errors: output.errors, + warnings: output.warnings, + commentsFilename: output.commentsFilename, + extractedCommentsSource: output.extractedCommentsSource + }); + } + + if (output.warnings && output.warnings.length > 0) { + for (const warning of output.warnings) { + compilation.warnings.push( + /** @type {WebpackError} */ + warning); + } + } + + if (output.errors && output.errors.length > 0) { + for (const error of output.errors) { + compilation.errors.push( + /** @type {WebpackError} */ + error); + } + } + /** @type {Record} */ + + + const newInfo = { + minimized: true + }; + const { + source, + extractedCommentsSource + } = output; // Write extracted comments to commentsFilename + + if (extractedCommentsSource) { + const { + commentsFilename + } = output; + newInfo.related = { + license: commentsFilename + }; + allExtractedComments.set(name, { + extractedCommentsSource, + commentsFilename + }); + } + + compilation.updateAsset(name, source, newInfo); + }); + } + + const limit = getWorker && numberOfAssets > 0 ? + /** @type {number} */ + numberOfWorkers : scheduledTasks.length; + await throttleAll(limit, scheduledTasks); + + if (initializedWorker) { + await initializedWorker.end(); + } + /** @typedef {{ source: import("webpack").sources.Source, commentsFilename: string, from: string }} ExtractedCommentsInfoWIthFrom */ + + + await Array.from(allExtractedComments).sort().reduce( + /** + * @param {Promise} previousPromise + * @param {[string, ExtractedCommentsInfo]} extractedComments + * @returns {Promise} + */ + async (previousPromise, [from, value]) => { + const previous = + /** @type {ExtractedCommentsInfoWIthFrom | undefined} **/ + await previousPromise; + const { + commentsFilename, + extractedCommentsSource + } = value; + + if (previous && previous.commentsFilename === commentsFilename) { + const { + from: previousFrom, + source: prevSource + } = previous; + const mergedName = `${previousFrom}|${from}`; + const name = `${commentsFilename}|${mergedName}`; + const eTag = [prevSource, extractedCommentsSource].map(item => cache.getLazyHashedEtag(item)).reduce((previousValue, currentValue) => cache.mergeEtags(previousValue, currentValue)); + let source = await cache.getPromise(name, eTag); + + if (!source) { + source = new ConcatSource(Array.from(new Set([... + /** @type {string}*/ + prevSource.source().split("\n\n"), ... + /** @type {string}*/ + extractedCommentsSource.source().split("\n\n")])).join("\n\n")); + await cache.storePromise(name, eTag, source); + } + + compilation.updateAsset(commentsFilename, source); + return { + source, + commentsFilename, + from: mergedName + }; + } + + const existingAsset = compilation.getAsset(commentsFilename); + + if (existingAsset) { + return { + source: existingAsset.source, + commentsFilename, + from: commentsFilename + }; + } + + compilation.emitAsset(commentsFilename, extractedCommentsSource, { + extractedComments: true + }); + return { + source: extractedCommentsSource, + commentsFilename, + from + }; + }, + /** @type {Promise} */ + Promise.resolve()); + } + /** + * @private + * @param {any} environment + * @returns {TerserECMA} + */ + + + static getEcmaVersion(environment) { + // ES 6th + if (environment.arrowFunction || environment.const || environment.destructuring || environment.forOf || environment.module) { + return 2015; + } // ES 11th + + + if (environment.bigIntLiteral || environment.dynamicImport) { + return 2020; + } + + return 5; + } + /** + * @param {Compiler} compiler + * @returns {void} + */ + + + apply(compiler) { + const pluginName = this.constructor.name; + const availableNumberOfCores = TerserPlugin.getAvailableNumberOfCores(this.options.parallel); + compiler.hooks.compilation.tap(pluginName, compilation => { + const hooks = compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation); + const data = serialize({ + minimizer: typeof this.options.minimizer.implementation.getMinimizerVersion !== "undefined" ? this.options.minimizer.implementation.getMinimizerVersion() || "0.0.0" : "0.0.0", + options: this.options.minimizer.options + }); + hooks.chunkHash.tap(pluginName, (chunk, hash) => { + hash.update("TerserPlugin"); + hash.update(data); + }); + compilation.hooks.processAssets.tapPromise({ + name: pluginName, + stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE, + additionalAssets: true + }, assets => this.optimize(compiler, compilation, assets, { + availableNumberOfCores + })); + compilation.hooks.statsPrinter.tap(pluginName, stats => { + stats.hooks.print.for("asset.info.minimized").tap("terser-webpack-plugin", (minimized, { + green, + formatFlag + }) => minimized ? + /** @type {Function} */ + green( + /** @type {Function} */ + formatFlag("minimized")) : ""); + }); + }); + } + +} + +TerserPlugin.terserMinify = terserMinify; +TerserPlugin.uglifyJsMinify = uglifyJsMinify; +TerserPlugin.swcMinify = swcMinify; +TerserPlugin.esbuildMinify = esbuildMinify; +module.exports = TerserPlugin; \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/minify.js b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/minify.js new file mode 100644 index 0000000..7cf6b5a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/minify.js @@ -0,0 +1,50 @@ +"use strict"; + +/** @typedef {import("./index.js").MinimizedResult} MinimizedResult */ + +/** @typedef {import("./index.js").CustomOptions} CustomOptions */ + +/** + * @template T + * @param {import("./index.js").InternalOptions} options + * @returns {Promise} + */ +async function minify(options) { + const { + name, + input, + inputSourceMap, + extractComments + } = options; + const { + implementation, + options: minimizerOptions + } = options.minimizer; + return implementation({ + [name]: input + }, inputSourceMap, minimizerOptions, extractComments); +} +/** + * @param {string} options + * @returns {Promise} + */ + + +async function transform(options) { + // 'use strict' => this === undefined (Clean Scope) + // Safer for possible security issues, albeit not critical at all here + // eslint-disable-next-line no-param-reassign + const evaluatedOptions = + /** + * @template T + * @type {import("./index.js").InternalOptions} + * */ + // eslint-disable-next-line no-new-func + new Function("exports", "require", "module", "__filename", "__dirname", `'use strict'\nreturn ${options}`)(exports, require, module, __filename, __dirname); + return minify(evaluatedOptions); +} + +module.exports = { + minify, + transform +}; \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/options.json b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/options.json new file mode 100644 index 0000000..83d2cfd --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/options.json @@ -0,0 +1,164 @@ +{ + "definitions": { + "Rule": { + "description": "Filtering rule as regex or string.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string", + "minLength": 1 + } + ] + }, + "Rules": { + "description": "Filtering rules.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "A rule condition.", + "oneOf": [ + { + "$ref": "#/definitions/Rule" + } + ] + } + }, + { + "$ref": "#/definitions/Rule" + } + ] + } + }, + "title": "TerserPluginOptions", + "type": "object", + "additionalProperties": false, + "properties": { + "test": { + "description": "Include all modules that pass test assertion.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#test", + "oneOf": [ + { + "$ref": "#/definitions/Rules" + } + ] + }, + "include": { + "description": "Include all modules matching any of these conditions.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#include", + "oneOf": [ + { + "$ref": "#/definitions/Rules" + } + ] + }, + "exclude": { + "description": "Exclude all modules matching any of these conditions.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#exclude", + "oneOf": [ + { + "$ref": "#/definitions/Rules" + } + ] + }, + "terserOptions": { + "description": "Options for `terser` (by default) or custom `minify` function.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions", + "additionalProperties": true, + "type": "object" + }, + "extractComments": { + "description": "Whether comments shall be extracted to a separate file.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#extractcomments", + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "minLength": 1 + }, + { + "instanceof": "RegExp" + }, + { + "instanceof": "Function" + }, + { + "additionalProperties": false, + "properties": { + "condition": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "minLength": 1 + }, + { + "instanceof": "RegExp" + }, + { + "instanceof": "Function" + } + ], + "description": "Condition what comments you need extract.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#condition" + }, + "filename": { + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "instanceof": "Function" + } + ], + "description": "The file where the extracted comments will be stored. Default is to append the suffix .LICENSE.txt to the original filename.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#filename" + }, + "banner": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "minLength": 1 + }, + { + "instanceof": "Function" + } + ], + "description": "The banner text that points to the extracted file and will be added on top of the original file", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#banner" + } + }, + "type": "object" + } + ] + }, + "parallel": { + "description": "Use multi-process parallel running to improve the build speed.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#parallel", + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "integer" + } + ] + }, + "minify": { + "description": "Allows you to override default minify function.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#number", + "instanceof": "Function" + } + } +} diff --git a/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/utils.js b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/utils.js new file mode 100644 index 0000000..79dd425 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/dist/utils.js @@ -0,0 +1,687 @@ +"use strict"; + +/** @typedef {import("source-map").RawSourceMap} RawSourceMap */ + +/** @typedef {import("terser").FormatOptions} TerserFormatOptions */ + +/** @typedef {import("terser").MinifyOptions} TerserOptions */ + +/** @typedef {import("terser").ECMA} TerserECMA */ + +/** @typedef {import("./index.js").ExtractCommentsOptions} ExtractCommentsOptions */ + +/** @typedef {import("./index.js").ExtractCommentsFunction} ExtractCommentsFunction */ + +/** @typedef {import("./index.js").ExtractCommentsCondition} ExtractCommentsCondition */ + +/** @typedef {import("./index.js").Input} Input */ + +/** @typedef {import("./index.js").MinimizedResult} MinimizedResult */ + +/** @typedef {import("./index.js").PredefinedOptions} PredefinedOptions */ + +/** @typedef {import("./index.js").CustomOptions} CustomOptions */ + +/** + * @typedef {Array} ExtractedComments + */ +const notSettled = Symbol(`not-settled`); +/** + * @template T + * @typedef {() => Promise} Task + */ + +/** + * Run tasks with limited concurency. + * @template T + * @param {number} limit - Limit of tasks that run at once. + * @param {Task[]} tasks - List of tasks to run. + * @returns {Promise} A promise that fulfills to an array of the results + */ + +function throttleAll(limit, tasks) { + if (!Number.isInteger(limit) || limit < 1) { + throw new TypeError(`Expected \`limit\` to be a finite number > 0, got \`${limit}\` (${typeof limit})`); + } + + if (!Array.isArray(tasks) || !tasks.every(task => typeof task === `function`)) { + throw new TypeError(`Expected \`tasks\` to be a list of functions returning a promise`); + } + + return new Promise((resolve, reject) => { + const result = Array(tasks.length).fill(notSettled); + const entries = tasks.entries(); + + const next = () => { + const { + done, + value + } = entries.next(); + + if (done) { + const isLast = !result.includes(notSettled); + if (isLast) resolve( + /** @type{T[]} **/ + result); + return; + } + + const [index, task] = value; + /** + * @param {T} x + */ + + const onFulfilled = x => { + result[index] = x; + next(); + }; + + task().then(onFulfilled, reject); + }; + + Array(limit).fill(0).forEach(next); + }); +} +/* istanbul ignore next */ + +/** + * @param {Input} input + * @param {RawSourceMap | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @param {ExtractCommentsOptions | undefined} extractComments + * @return {Promise} + */ + + +async function terserMinify(input, sourceMap, minimizerOptions, extractComments) { + /** + * @param {any} value + * @returns {boolean} + */ + const isObject = value => { + const type = typeof value; + return value != null && (type === "object" || type === "function"); + }; + /** + * @param {TerserOptions & { sourceMap: undefined } & ({ output: TerserFormatOptions & { beautify: boolean } } | { format: TerserFormatOptions & { beautify: boolean } })} terserOptions + * @param {ExtractedComments} extractedComments + * @returns {ExtractCommentsFunction} + */ + + + const buildComments = (terserOptions, extractedComments) => { + /** @type {{ [index: string]: ExtractCommentsCondition }} */ + const condition = {}; + let comments; + + if (terserOptions.format) { + ({ + comments + } = terserOptions.format); + } else if (terserOptions.output) { + ({ + comments + } = terserOptions.output); + } + + condition.preserve = typeof comments !== "undefined" ? comments : false; + + if (typeof extractComments === "boolean" && extractComments) { + condition.extract = "some"; + } else if (typeof extractComments === "string" || extractComments instanceof RegExp) { + condition.extract = extractComments; + } else if (typeof extractComments === "function") { + condition.extract = extractComments; + } else if (extractComments && isObject(extractComments)) { + condition.extract = typeof extractComments.condition === "boolean" && extractComments.condition ? "some" : typeof extractComments.condition !== "undefined" ? extractComments.condition : "some"; + } else { + // No extract + // Preserve using "commentsOpts" or "some" + condition.preserve = typeof comments !== "undefined" ? comments : "some"; + condition.extract = false; + } // Ensure that both conditions are functions + + + ["preserve", "extract"].forEach(key => { + /** @type {undefined | string} */ + let regexStr; + /** @type {undefined | RegExp} */ + + let regex; + + switch (typeof condition[key]) { + case "boolean": + condition[key] = condition[key] ? () => true : () => false; + break; + + case "function": + break; + + case "string": + if (condition[key] === "all") { + condition[key] = () => true; + + break; + } + + if (condition[key] === "some") { + condition[key] = + /** @type {ExtractCommentsFunction} */ + (astNode, comment) => (comment.type === "comment2" || comment.type === "comment1") && /@preserve|@lic|@cc_on|^\**!/i.test(comment.value); + + break; + } + + regexStr = + /** @type {string} */ + condition[key]; + + condition[key] = + /** @type {ExtractCommentsFunction} */ + (astNode, comment) => new RegExp( + /** @type {string} */ + regexStr).test(comment.value); + + break; + + default: + regex = + /** @type {RegExp} */ + condition[key]; + + condition[key] = + /** @type {ExtractCommentsFunction} */ + (astNode, comment) => + /** @type {RegExp} */ + regex.test(comment.value); + + } + }); // Redefine the comments function to extract and preserve + // comments according to the two conditions + + return (astNode, comment) => { + if ( + /** @type {{ extract: ExtractCommentsFunction }} */ + condition.extract(astNode, comment)) { + const commentText = comment.type === "comment2" ? `/*${comment.value}*/` : `//${comment.value}`; // Don't include duplicate comments + + if (!extractedComments.includes(commentText)) { + extractedComments.push(commentText); + } + } + + return ( + /** @type {{ preserve: ExtractCommentsFunction }} */ + condition.preserve(astNode, comment) + ); + }; + }; + /** + * @param {PredefinedOptions & TerserOptions} [terserOptions={}] + * @returns {TerserOptions & { sourceMap: undefined } & ({ output: TerserFormatOptions & { beautify: boolean } } | { format: TerserFormatOptions & { beautify: boolean } })} + */ + + + const buildTerserOptions = (terserOptions = {}) => { + // Need deep copy objects to avoid https://github.com/terser/terser/issues/366 + return { ...terserOptions, + compress: typeof terserOptions.compress === "boolean" ? terserOptions.compress : { ...terserOptions.compress + }, + // ecma: terserOptions.ecma, + // ie8: terserOptions.ie8, + // keep_classnames: terserOptions.keep_classnames, + // keep_fnames: terserOptions.keep_fnames, + mangle: terserOptions.mangle == null ? true : typeof terserOptions.mangle === "boolean" ? terserOptions.mangle : { ...terserOptions.mangle + }, + // module: terserOptions.module, + // nameCache: { ...terserOptions.toplevel }, + // the `output` option is deprecated + ...(terserOptions.format ? { + format: { + beautify: false, + ...terserOptions.format + } + } : { + output: { + beautify: false, + ...terserOptions.output + } + }), + parse: { ...terserOptions.parse + }, + // safari10: terserOptions.safari10, + // Ignoring sourceMap from options + // eslint-disable-next-line no-undefined + sourceMap: undefined // toplevel: terserOptions.toplevel + + }; + }; // eslint-disable-next-line global-require + + + const { + minify + } = require("terser"); // Copy `terser` options + + + const terserOptions = buildTerserOptions(minimizerOptions); // Let terser generate a SourceMap + + if (sourceMap) { + // @ts-ignore + terserOptions.sourceMap = { + asObject: true + }; + } + /** @type {ExtractedComments} */ + + + const extractedComments = []; + + if (terserOptions.output) { + terserOptions.output.comments = buildComments(terserOptions, extractedComments); + } else if (terserOptions.format) { + terserOptions.format.comments = buildComments(terserOptions, extractedComments); + } + + const [[filename, code]] = Object.entries(input); + const result = await minify({ + [filename]: code + }, terserOptions); + return { + code: + /** @type {string} **/ + result.code, + // @ts-ignore + // eslint-disable-next-line no-undefined + map: result.map ? + /** @type {RawSourceMap} **/ + result.map : undefined, + extractedComments + }; +} +/** + * @returns {string | undefined} + */ + + +terserMinify.getMinimizerVersion = () => { + let packageJson; + + try { + // eslint-disable-next-line global-require + packageJson = require("terser/package.json"); + } catch (error) {// Ignore + } + + return packageJson && packageJson.version; +}; +/* istanbul ignore next */ + +/** + * @param {Input} input + * @param {RawSourceMap | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @param {ExtractCommentsOptions | undefined} extractComments + * @return {Promise} + */ + + +async function uglifyJsMinify(input, sourceMap, minimizerOptions, extractComments) { + /** + * @param {any} value + * @returns {boolean} + */ + const isObject = value => { + const type = typeof value; + return value != null && (type === "object" || type === "function"); + }; + /** + * @param {import("uglify-js").MinifyOptions & { sourceMap: undefined } & { output: import("uglify-js").OutputOptions & { beautify: boolean }}} uglifyJsOptions + * @param {ExtractedComments} extractedComments + * @returns {ExtractCommentsFunction} + */ + + + const buildComments = (uglifyJsOptions, extractedComments) => { + /** @type {{ [index: string]: ExtractCommentsCondition }} */ + const condition = {}; + const { + comments + } = uglifyJsOptions.output; + condition.preserve = typeof comments !== "undefined" ? comments : false; + + if (typeof extractComments === "boolean" && extractComments) { + condition.extract = "some"; + } else if (typeof extractComments === "string" || extractComments instanceof RegExp) { + condition.extract = extractComments; + } else if (typeof extractComments === "function") { + condition.extract = extractComments; + } else if (extractComments && isObject(extractComments)) { + condition.extract = typeof extractComments.condition === "boolean" && extractComments.condition ? "some" : typeof extractComments.condition !== "undefined" ? extractComments.condition : "some"; + } else { + // No extract + // Preserve using "commentsOpts" or "some" + condition.preserve = typeof comments !== "undefined" ? comments : "some"; + condition.extract = false; + } // Ensure that both conditions are functions + + + ["preserve", "extract"].forEach(key => { + /** @type {undefined | string} */ + let regexStr; + /** @type {undefined | RegExp} */ + + let regex; + + switch (typeof condition[key]) { + case "boolean": + condition[key] = condition[key] ? () => true : () => false; + break; + + case "function": + break; + + case "string": + if (condition[key] === "all") { + condition[key] = () => true; + + break; + } + + if (condition[key] === "some") { + condition[key] = + /** @type {ExtractCommentsFunction} */ + (astNode, comment) => (comment.type === "comment2" || comment.type === "comment1") && /@preserve|@lic|@cc_on|^\**!/i.test(comment.value); + + break; + } + + regexStr = + /** @type {string} */ + condition[key]; + + condition[key] = + /** @type {ExtractCommentsFunction} */ + (astNode, comment) => new RegExp( + /** @type {string} */ + regexStr).test(comment.value); + + break; + + default: + regex = + /** @type {RegExp} */ + condition[key]; + + condition[key] = + /** @type {ExtractCommentsFunction} */ + (astNode, comment) => + /** @type {RegExp} */ + regex.test(comment.value); + + } + }); // Redefine the comments function to extract and preserve + // comments according to the two conditions + + return (astNode, comment) => { + if ( + /** @type {{ extract: ExtractCommentsFunction }} */ + condition.extract(astNode, comment)) { + const commentText = comment.type === "comment2" ? `/*${comment.value}*/` : `//${comment.value}`; // Don't include duplicate comments + + if (!extractedComments.includes(commentText)) { + extractedComments.push(commentText); + } + } + + return ( + /** @type {{ preserve: ExtractCommentsFunction }} */ + condition.preserve(astNode, comment) + ); + }; + }; + /** + * @param {PredefinedOptions & import("uglify-js").MinifyOptions} [uglifyJsOptions={}] + * @returns {import("uglify-js").MinifyOptions & { sourceMap: undefined } & { output: import("uglify-js").OutputOptions & { beautify: boolean }}} + */ + + + const buildUglifyJsOptions = (uglifyJsOptions = {}) => { + // eslint-disable-next-line no-param-reassign + delete minimizerOptions.ecma; // eslint-disable-next-line no-param-reassign + + delete minimizerOptions.module; // Need deep copy objects to avoid https://github.com/terser/terser/issues/366 + + return { ...uglifyJsOptions, + // warnings: uglifyJsOptions.warnings, + parse: { ...uglifyJsOptions.parse + }, + compress: typeof uglifyJsOptions.compress === "boolean" ? uglifyJsOptions.compress : { ...uglifyJsOptions.compress + }, + mangle: uglifyJsOptions.mangle == null ? true : typeof uglifyJsOptions.mangle === "boolean" ? uglifyJsOptions.mangle : { ...uglifyJsOptions.mangle + }, + output: { + beautify: false, + ...uglifyJsOptions.output + }, + // Ignoring sourceMap from options + // eslint-disable-next-line no-undefined + sourceMap: undefined // toplevel: uglifyJsOptions.toplevel + // nameCache: { ...uglifyJsOptions.toplevel }, + // ie8: uglifyJsOptions.ie8, + // keep_fnames: uglifyJsOptions.keep_fnames, + + }; + }; // eslint-disable-next-line global-require, import/no-extraneous-dependencies + + + const { + minify + } = require("uglify-js"); // Copy `uglify-js` options + + + const uglifyJsOptions = buildUglifyJsOptions(minimizerOptions); // Let terser generate a SourceMap + + if (sourceMap) { + // @ts-ignore + uglifyJsOptions.sourceMap = true; + } + /** @type {ExtractedComments} */ + + + const extractedComments = []; // @ts-ignore + + uglifyJsOptions.output.comments = buildComments(uglifyJsOptions, extractedComments); + const [[filename, code]] = Object.entries(input); + const result = await minify({ + [filename]: code + }, uglifyJsOptions); + return { + code: result.code, + // eslint-disable-next-line no-undefined + map: result.map ? JSON.parse(result.map) : undefined, + errors: result.error ? [result.error] : [], + warnings: result.warnings || [], + extractedComments + }; +} +/** + * @returns {string | undefined} + */ + + +uglifyJsMinify.getMinimizerVersion = () => { + let packageJson; + + try { + // eslint-disable-next-line global-require, import/no-extraneous-dependencies + packageJson = require("uglify-js/package.json"); + } catch (error) {// Ignore + } + + return packageJson && packageJson.version; +}; +/* istanbul ignore next */ + +/** + * @param {Input} input + * @param {RawSourceMap | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @return {Promise} + */ + + +async function swcMinify(input, sourceMap, minimizerOptions) { + /** + * @param {PredefinedOptions & import("@swc/core").JsMinifyOptions} [swcOptions={}] + * @returns {import("@swc/core").JsMinifyOptions & { sourceMap: undefined }} + */ + const buildSwcOptions = (swcOptions = {}) => { + // Need deep copy objects to avoid https://github.com/terser/terser/issues/366 + return { ...swcOptions, + compress: typeof swcOptions.compress === "boolean" ? swcOptions.compress : { ...swcOptions.compress + }, + mangle: swcOptions.mangle == null ? true : typeof swcOptions.mangle === "boolean" ? swcOptions.mangle : { ...swcOptions.mangle + }, + // ecma: swcOptions.ecma, + // keep_classnames: swcOptions.keep_classnames, + // keep_fnames: swcOptions.keep_fnames, + // module: swcOptions.module, + // safari10: swcOptions.safari10, + // toplevel: swcOptions.toplevel + // eslint-disable-next-line no-undefined + sourceMap: undefined + }; + }; // eslint-disable-next-line import/no-extraneous-dependencies, global-require + + + const swc = require("@swc/core"); // Copy `swc` options + + + const swcOptions = buildSwcOptions(minimizerOptions); // Let `swc` generate a SourceMap + + if (sourceMap) { + // @ts-ignore + swcOptions.sourceMap = true; + } + + const [[filename, code]] = Object.entries(input); + const result = await swc.minify(code, swcOptions); + let map; + + if (result.map) { + map = JSON.parse(result.map); // TODO workaround for swc because `filename` is not preset as in `swc` signature as for `terser` + + map.sources = [filename]; + delete map.sourcesContent; + } + + return { + code: result.code, + map + }; +} +/** + * @returns {string | undefined} + */ + + +swcMinify.getMinimizerVersion = () => { + let packageJson; + + try { + // eslint-disable-next-line global-require, import/no-extraneous-dependencies + packageJson = require("@swc/core/package.json"); + } catch (error) {// Ignore + } + + return packageJson && packageJson.version; +}; +/* istanbul ignore next */ + +/** + * @param {Input} input + * @param {RawSourceMap | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @return {Promise} + */ + + +async function esbuildMinify(input, sourceMap, minimizerOptions) { + /** + * @param {PredefinedOptions & import("esbuild").TransformOptions} [esbuildOptions={}] + * @returns {import("esbuild").TransformOptions} + */ + const buildEsbuildOptions = (esbuildOptions = {}) => { + // eslint-disable-next-line no-param-reassign + delete esbuildOptions.ecma; + + if (esbuildOptions.module) { + // eslint-disable-next-line no-param-reassign + esbuildOptions.format = "esm"; + } // eslint-disable-next-line no-param-reassign + + + delete esbuildOptions.module; // Need deep copy objects to avoid https://github.com/terser/terser/issues/366 + + return { + minify: true, + legalComments: "inline", + ...esbuildOptions, + sourcemap: false + }; + }; // eslint-disable-next-line import/no-extraneous-dependencies, global-require + + + const esbuild = require("esbuild"); // Copy `esbuild` options + + + const esbuildOptions = buildEsbuildOptions(minimizerOptions); // Let `esbuild` generate a SourceMap + + if (sourceMap) { + esbuildOptions.sourcemap = true; + esbuildOptions.sourcesContent = false; + } + + const [[filename, code]] = Object.entries(input); + esbuildOptions.sourcefile = filename; + const result = await esbuild.transform(code, esbuildOptions); + return { + code: result.code, + // eslint-disable-next-line no-undefined + map: result.map ? JSON.parse(result.map) : undefined, + warnings: result.warnings.length > 0 ? result.warnings.map(item => { + return { + name: "Warning", + source: item.location && item.location.file, + line: item.location && item.location.line, + column: item.location && item.location.column, + plugin: item.pluginName, + message: `${item.text}${item.detail ? `\nDetails:\n${item.detail}` : ""}${item.notes.length > 0 ? `\n\nNotes:\n${item.notes.map(note => `${note.location ? `[${note.location.file}:${note.location.line}:${note.location.column}] ` : ""}${note.text}${note.location ? `\nSuggestion: ${note.location.suggestion}` : ""}${note.location ? `\nLine text:\n${note.location.lineText}\n` : ""}`).join("\n")}` : ""}` + }; + }) : [] + }; +} +/** + * @returns {string | undefined} + */ + + +esbuildMinify.getMinimizerVersion = () => { + let packageJson; + + try { + // eslint-disable-next-line global-require, import/no-extraneous-dependencies + packageJson = require("esbuild/package.json"); + } catch (error) {// Ignore + } + + return packageJson && packageJson.version; +}; + +module.exports = { + throttleAll, + terserMinify, + uglifyJsMinify, + swcMinify, + esbuildMinify +}; \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/package.json b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/package.json new file mode 100644 index 0000000..5708a9b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/package.json @@ -0,0 +1,114 @@ +{ + "name": "terser-webpack-plugin", + "version": "5.3.1", + "description": "Terser plugin for webpack", + "license": "MIT", + "repository": "webpack-contrib/terser-webpack-plugin", + "author": "webpack Contrib Team", + "homepage": "https://github.com/webpack-contrib/terser-webpack-plugin", + "bugs": "https://github.com/webpack-contrib/terser-webpack-plugin/issues", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "main": "dist/index.js", + "types": "types/index.d.ts", + "engines": { + "node": ">= 10.13.0" + }, + "scripts": { + "clean": "del-cli dist types", + "prebuild": "npm run clean", + "build:types": "tsc --declaration --emitDeclarationOnly --outDir types && prettier \"types/**/*.ts\" --write", + "build:code": "cross-env NODE_ENV=production babel src -d dist --copy-files", + "build": "npm-run-all -p \"build:**\"", + "commitlint": "commitlint --from=master", + "security": "npm audit --production", + "lint:prettier": "prettier --list-different .", + "lint:js": "eslint --cache .", + "lint:types": "tsc --pretty --noEmit", + "lint": "npm-run-all -l -p \"lint:**\"", + "test:only": "cross-env NODE_ENV=test jest", + "test:watch": "npm run test:only -- --watch", + "test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage", + "pretest": "npm run lint", + "test": "npm run test:coverage", + "prepare": "husky install && npm run build", + "release": "standard-version" + }, + "files": [ + "dist", + "types" + ], + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "uglify-js": { + "optional": true + }, + "esbuild": { + "optional": true + } + }, + "dependencies": { + "jest-worker": "^27.4.5", + "schema-utils": "^3.1.1", + "serialize-javascript": "^6.0.0", + "source-map": "^0.6.1", + "terser": "^5.7.2" + }, + "devDependencies": { + "@babel/cli": "^7.16.7", + "@babel/core": "^7.16.7", + "@babel/preset-env": "^7.16.7", + "@commitlint/cli": "^15.0.0", + "@commitlint/config-conventional": "^15.0.0", + "@swc/core": "^1.2.126", + "@types/serialize-javascript": "^5.0.2", + "@types/uglify-js": "^3.13.1", + "@webpack-contrib/eslint-config-webpack": "^3.0.0", + "babel-jest": "^27.4.5", + "copy-webpack-plugin": "^9.0.1", + "cross-env": "^7.0.3", + "del": "^6.0.0", + "del-cli": "^3.0.1", + "esbuild": "^0.14.10", + "eslint": "^7.32.0", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-import": "^2.25.4", + "file-loader": "^6.2.0", + "husky": "^7.0.2", + "jest": "^27.4.5", + "lint-staged": "^11.0.1", + "memfs": "^3.4.1", + "npm-run-all": "^4.1.5", + "prettier": "^2.3.2", + "standard-version": "^9.3.1", + "typescript": "^4.5.4", + "uglify-js": "^3.14.5", + "webpack": "^5.48.0", + "webpack-cli": "^4.9.1", + "worker-loader": "^3.0.8" + }, + "keywords": [ + "uglify", + "uglify-js", + "uglify-es", + "terser", + "webpack", + "webpack-plugin", + "minification", + "compress", + "compressor", + "min", + "minification", + "minifier", + "minify", + "optimize", + "optimizer" + ] +} diff --git a/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/types/index.d.ts b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/types/index.d.ts new file mode 100644 index 0000000..7adb303 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/types/index.d.ts @@ -0,0 +1,329 @@ +export = TerserPlugin; +/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */ +/** @typedef {import("webpack").Compiler} Compiler */ +/** @typedef {import("webpack").Compilation} Compilation */ +/** @typedef {import("webpack").WebpackError} WebpackError */ +/** @typedef {import("webpack").Asset} Asset */ +/** @typedef {import("./utils.js").TerserECMA} TerserECMA */ +/** @typedef {import("./utils.js").TerserOptions} TerserOptions */ +/** @typedef {import("jest-worker").Worker} JestWorker */ +/** @typedef {import("source-map").RawSourceMap} RawSourceMap */ +/** @typedef {RegExp | string} Rule */ +/** @typedef {Rule[] | Rule} Rules */ +/** + * @callback ExtractCommentsFunction + * @param {any} astNode + * @param {{ value: string, type: 'comment1' | 'comment2' | 'comment3' | 'comment4', pos: number, line: number, col: number }} comment + * @returns {boolean} + */ +/** + * @typedef {boolean | 'all' | 'some' | RegExp | ExtractCommentsFunction} ExtractCommentsCondition + */ +/** + * @typedef {string | ((fileData: any) => string)} ExtractCommentsFilename + */ +/** + * @typedef {boolean | string | ((commentsFile: string) => string)} ExtractCommentsBanner + */ +/** + * @typedef {Object} ExtractCommentsObject + * @property {ExtractCommentsCondition} [condition] + * @property {ExtractCommentsFilename} [filename] + * @property {ExtractCommentsBanner} [banner] + */ +/** + * @typedef {ExtractCommentsCondition | ExtractCommentsObject} ExtractCommentsOptions + */ +/** + * @typedef {Object} MinimizedResult + * @property {string} code + * @property {RawSourceMap} [map] + * @property {Array} [errors] + * @property {Array} [warnings] + * @property {Array} [extractedComments] + */ +/** + * @typedef {{ [file: string]: string }} Input + */ +/** + * @typedef {{ [key: string]: any }} CustomOptions + */ +/** + * @template T + * @typedef {T extends infer U ? U : CustomOptions} InferDefaultType + */ +/** + * @typedef {Object} PredefinedOptions + * @property {boolean} [module] + * @property {TerserECMA} [ecma] + */ +/** + * @template T + * @typedef {PredefinedOptions & InferDefaultType} MinimizerOptions + */ +/** + * @template T + * @callback BasicMinimizerImplementation + * @param {Input} input + * @param {RawSourceMap | undefined} sourceMap + * @param {MinimizerOptions} minifyOptions + * @param {ExtractCommentsOptions | undefined} extractComments + * @returns {Promise} + */ +/** + * @typedef {object} MinimizeFunctionHelpers + * @property {() => string | undefined} [getMinimizerVersion] + */ +/** + * @template T + * @typedef {BasicMinimizerImplementation & MinimizeFunctionHelpers} MinimizerImplementation + */ +/** + * @template T + * @typedef {Object} InternalOptions + * @property {string} name + * @property {string} input + * @property {RawSourceMap | undefined} inputSourceMap + * @property {ExtractCommentsOptions | undefined} extractComments + * @property {{ implementation: MinimizerImplementation, options: MinimizerOptions }} minimizer + */ +/** + * @template T + * @typedef {JestWorker & { transform: (options: string) => MinimizedResult, minify: (options: InternalOptions) => MinimizedResult }} MinimizerWorker + */ +/** + * @typedef {undefined | boolean | number} Parallel + */ +/** + * @typedef {Object} BasePluginOptions + * @property {Rules} [test] + * @property {Rules} [include] + * @property {Rules} [exclude] + * @property {ExtractCommentsOptions} [extractComments] + * @property {Parallel} [parallel] + */ +/** + * @template T + * @typedef {T extends TerserOptions ? { minify?: MinimizerImplementation | undefined, terserOptions?: MinimizerOptions | undefined } : { minify: MinimizerImplementation, terserOptions?: MinimizerOptions | undefined }} DefinedDefaultMinimizerAndOptions + */ +/** + * @template T + * @typedef {BasePluginOptions & { minimizer: { implementation: MinimizerImplementation, options: MinimizerOptions } }} InternalPluginOptions + */ +/** + * @template [T=TerserOptions] + */ +declare class TerserPlugin { + /** + * @private + * @param {any} input + * @returns {boolean} + */ + private static isSourceMap; + /** + * @private + * @param {unknown} warning + * @param {string} file + * @returns {Error} + */ + private static buildWarning; + /** + * @private + * @param {any} error + * @param {string} file + * @param {SourceMapConsumer} [sourceMap] + * @param {Compilation["requestShortener"]} [requestShortener] + * @returns {Error} + */ + private static buildError; + /** + * @private + * @param {Parallel} parallel + * @returns {number} + */ + private static getAvailableNumberOfCores; + /** + * @private + * @param {any} environment + * @returns {TerserECMA} + */ + private static getEcmaVersion; + /** + * @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions} [options] + */ + constructor( + options?: + | (BasePluginOptions & DefinedDefaultMinimizerAndOptions) + | undefined + ); + /** + * @private + * @type {InternalPluginOptions} + */ + private options; + /** + * @private + * @param {Compiler} compiler + * @param {Compilation} compilation + * @param {Record} assets + * @param {{availableNumberOfCores: number}} optimizeOptions + * @returns {Promise} + */ + private optimize; + /** + * @param {Compiler} compiler + * @returns {void} + */ + apply(compiler: Compiler): void; +} +declare namespace TerserPlugin { + export { + terserMinify, + uglifyJsMinify, + swcMinify, + esbuildMinify, + Schema, + Compiler, + Compilation, + WebpackError, + Asset, + TerserECMA, + TerserOptions, + JestWorker, + RawSourceMap, + Rule, + Rules, + ExtractCommentsFunction, + ExtractCommentsCondition, + ExtractCommentsFilename, + ExtractCommentsBanner, + ExtractCommentsObject, + ExtractCommentsOptions, + MinimizedResult, + Input, + CustomOptions, + InferDefaultType, + PredefinedOptions, + MinimizerOptions, + BasicMinimizerImplementation, + MinimizeFunctionHelpers, + MinimizerImplementation, + InternalOptions, + MinimizerWorker, + Parallel, + BasePluginOptions, + DefinedDefaultMinimizerAndOptions, + InternalPluginOptions, + }; +} +type Compiler = import("webpack").Compiler; +type BasePluginOptions = { + test?: Rules | undefined; + include?: Rules | undefined; + exclude?: Rules | undefined; + extractComments?: ExtractCommentsOptions | undefined; + parallel?: Parallel; +}; +type DefinedDefaultMinimizerAndOptions = T extends TerserOptions + ? { + minify?: MinimizerImplementation | undefined; + terserOptions?: MinimizerOptions | undefined; + } + : { + minify: MinimizerImplementation; + terserOptions?: MinimizerOptions | undefined; + }; +import { terserMinify } from "./utils"; +import { uglifyJsMinify } from "./utils"; +import { swcMinify } from "./utils"; +import { esbuildMinify } from "./utils"; +type Schema = import("schema-utils/declarations/validate").Schema; +type Compilation = import("webpack").Compilation; +type WebpackError = import("webpack").WebpackError; +type Asset = import("webpack").Asset; +type TerserECMA = import("./utils.js").TerserECMA; +type TerserOptions = import("./utils.js").TerserOptions; +type JestWorker = import("jest-worker").Worker; +type RawSourceMap = import("source-map").RawSourceMap; +type Rule = RegExp | string; +type Rules = Rule[] | Rule; +type ExtractCommentsFunction = ( + astNode: any, + comment: { + value: string; + type: "comment1" | "comment2" | "comment3" | "comment4"; + pos: number; + line: number; + col: number; + } +) => boolean; +type ExtractCommentsCondition = + | boolean + | "all" + | "some" + | RegExp + | ExtractCommentsFunction; +type ExtractCommentsFilename = string | ((fileData: any) => string); +type ExtractCommentsBanner = + | string + | boolean + | ((commentsFile: string) => string); +type ExtractCommentsObject = { + condition?: ExtractCommentsCondition | undefined; + filename?: ExtractCommentsFilename | undefined; + banner?: ExtractCommentsBanner | undefined; +}; +type ExtractCommentsOptions = ExtractCommentsCondition | ExtractCommentsObject; +type MinimizedResult = { + code: string; + map?: import("source-map").RawSourceMap | undefined; + errors?: (string | Error)[] | undefined; + warnings?: (string | Error)[] | undefined; + extractedComments?: string[] | undefined; +}; +type Input = { + [file: string]: string; +}; +type CustomOptions = { + [key: string]: any; +}; +type InferDefaultType = T extends infer U ? U : CustomOptions; +type PredefinedOptions = { + module?: boolean | undefined; + ecma?: import("terser").ECMA | undefined; +}; +type MinimizerOptions = PredefinedOptions & InferDefaultType; +type BasicMinimizerImplementation = ( + input: Input, + sourceMap: RawSourceMap | undefined, + minifyOptions: MinimizerOptions, + extractComments: ExtractCommentsOptions | undefined +) => Promise; +type MinimizeFunctionHelpers = { + getMinimizerVersion?: (() => string | undefined) | undefined; +}; +type MinimizerImplementation = BasicMinimizerImplementation & + MinimizeFunctionHelpers; +type InternalOptions = { + name: string; + input: string; + inputSourceMap: RawSourceMap | undefined; + extractComments: ExtractCommentsOptions | undefined; + minimizer: { + implementation: MinimizerImplementation; + options: MinimizerOptions; + }; +}; +type MinimizerWorker = Worker & { + transform: (options: string) => MinimizedResult; + minify: (options: InternalOptions) => MinimizedResult; +}; +type Parallel = undefined | boolean | number; +type InternalPluginOptions = BasePluginOptions & { + minimizer: { + implementation: MinimizerImplementation; + options: MinimizerOptions; + }; +}; +import { minify } from "./minify"; +import { Worker } from "jest-worker"; diff --git a/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/types/minify.d.ts b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/types/minify.d.ts new file mode 100644 index 0000000..0213d74 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/types/minify.d.ts @@ -0,0 +1,17 @@ +export type MinimizedResult = import("./index.js").MinimizedResult; +export type CustomOptions = import("./index.js").CustomOptions; +/** @typedef {import("./index.js").MinimizedResult} MinimizedResult */ +/** @typedef {import("./index.js").CustomOptions} CustomOptions */ +/** + * @template T + * @param {import("./index.js").InternalOptions} options + * @returns {Promise} + */ +export function minify( + options: import("./index.js").InternalOptions +): Promise; +/** + * @param {string} options + * @returns {Promise} + */ +export function transform(options: string): Promise; diff --git a/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/types/utils.d.ts b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/types/utils.d.ts new file mode 100644 index 0000000..141b5ac --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser-webpack-plugin/types/utils.d.ts @@ -0,0 +1,100 @@ +export type Task = () => Promise; +export type RawSourceMap = import("source-map").RawSourceMap; +export type TerserFormatOptions = import("terser").FormatOptions; +export type TerserOptions = import("terser").MinifyOptions; +export type TerserECMA = import("terser").ECMA; +export type ExtractCommentsOptions = + import("./index.js").ExtractCommentsOptions; +export type ExtractCommentsFunction = + import("./index.js").ExtractCommentsFunction; +export type ExtractCommentsCondition = + import("./index.js").ExtractCommentsCondition; +export type Input = import("./index.js").Input; +export type MinimizedResult = import("./index.js").MinimizedResult; +export type PredefinedOptions = import("./index.js").PredefinedOptions; +export type CustomOptions = import("./index.js").CustomOptions; +export type ExtractedComments = Array; +/** + * @template T + * @typedef {() => Promise} Task + */ +/** + * Run tasks with limited concurency. + * @template T + * @param {number} limit - Limit of tasks that run at once. + * @param {Task[]} tasks - List of tasks to run. + * @returns {Promise} A promise that fulfills to an array of the results + */ +export function throttleAll(limit: number, tasks: Task[]): Promise; +/** + * @param {Input} input + * @param {RawSourceMap | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @param {ExtractCommentsOptions | undefined} extractComments + * @return {Promise} + */ +export function terserMinify( + input: Input, + sourceMap: RawSourceMap | undefined, + minimizerOptions: PredefinedOptions & CustomOptions, + extractComments: ExtractCommentsOptions | undefined +): Promise; +export namespace terserMinify { + /** + * @returns {string | undefined} + */ + function getMinimizerVersion(): string | undefined; +} +/** + * @param {Input} input + * @param {RawSourceMap | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @param {ExtractCommentsOptions | undefined} extractComments + * @return {Promise} + */ +export function uglifyJsMinify( + input: Input, + sourceMap: RawSourceMap | undefined, + minimizerOptions: PredefinedOptions & CustomOptions, + extractComments: ExtractCommentsOptions | undefined +): Promise; +export namespace uglifyJsMinify { + /** + * @returns {string | undefined} + */ + function getMinimizerVersion(): string | undefined; +} +/** + * @param {Input} input + * @param {RawSourceMap | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @return {Promise} + */ +export function swcMinify( + input: Input, + sourceMap: RawSourceMap | undefined, + minimizerOptions: PredefinedOptions & CustomOptions +): Promise; +export namespace swcMinify { + /** + * @returns {string | undefined} + */ + function getMinimizerVersion(): string | undefined; +} +/** + * @param {Input} input + * @param {RawSourceMap | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @return {Promise} + */ +export function esbuildMinify( + input: Input, + sourceMap: RawSourceMap | undefined, + minimizerOptions: PredefinedOptions & CustomOptions +): Promise; +export namespace esbuildMinify { + /** + * @returns {string | undefined} + */ + function getMinimizerVersion(): string | undefined; +} diff --git a/node_modules/mathjs/examples/node_modules/terser/CHANGELOG.md b/node_modules/mathjs/examples/node_modules/terser/CHANGELOG.md new file mode 100644 index 0000000..2ae1a24 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/CHANGELOG.md @@ -0,0 +1,480 @@ +# Changelog + +## v5.12.1 + + - Fixed an issue with function definitions inside blocks (#1155) + - Fixed parens of `new` in some situations (closes #1159) + +## v5.12.0 + + - `TERSER_DEBUG_DIR` environment variable + - @copyright comments are now preserved with the comments="some" option (#1153) + +## v5.11.0 + + - Unicode code point escapes (`\u{abcde}`) are not emitted inside RegExp literals anymore (#1147) + - acorn is now a regular dependency + +## v5.10.0 + + - Massive optimization to max_line_len (#1109) + - Basic support for import assertions + - Marked ES2022 Object.hasOwn as a pure function + - Fix `delete optional?.property` + - New CI/CD pipeline with github actions (#1057) + - Fix reordering of switch branches (#1092), (#1084) + - Fix error when creating a class property called `get` + - Acorn dependency is now an optional peerDependency + - Fix mangling collision with exported variables (#1072) + - Fix an issue with `return someVariable = (async () => { ... })()` (#1073) + +## v5.9.0 + + - Collapsing switch cases with the same bodies (even if they're not next to each other) (#1070). + - Fix evaluation of optional chain expressions (#1062) + - Fix mangling collision in ESM exports (#1063) + - Fix issue with mutating function objects after a second pass (#1047) + - Fix for inlining object spread `{ ...obj }` (#1071) + - Typescript typings fix (#1069) + +## v5.8.0 + + - Fixed shadowing variables while moving code in some cases (#1065) + - Stop mangling computed & quoted properties when keep_quoted is enabled. + - Fix for mangling private getter/setter and .#private access (#1060, #1068) + - Array.from has a new optimization when the unsafe option is set (#737) + - Mangle/propmangle let you generate your own identifiers through the nth_identifier option (#1061) + - More optimizations to switch statements (#1044) + +## v5.7.2 + + - Fixed issues with compressing functions defined in `global_defs` option (#1036) + - New recipe for using Terser in gulp was added to RECIPES.md (#1035) + - Fixed issues with `??` and `?.` (#1045) + - Future reserved words such as `package` no longer require you to disable strict mode to be used as names. + - Refactored huge compressor file into multiple more focused files. + - Avoided unparenthesized `in` operator in some for loops (it breaks parsing because of for..in loops) + - Improved documentation (#1021, #1025) + - More type definitions (#1021) + +## v5.7.1 + + - Avoided collapsing assignments together if it would place a chain assignment on the left hand side, which is invalid syntax (`a?.b = c`) + - Removed undefined from object expansions (`{ ...void 0 }` -> `{}`) + - Fix crash when checking if something is nullish or undefined (#1009) + - Fixed comparison of private class properties (#1015) + - Minor performance improvements (#993) + - Fixed scope of function defs in strict mode (they are block scoped) + +## v5.7.0 + + - Several compile-time evaluation and inlining fixes + - Allow `reduce_funcs` to be disabled again. + - Add `spidermonkey` options to parse and format (#974) + - Accept `{get = "default val"}` and `{set = "default val"}` in destructuring arguments. + - Change package.json export map to help require.resolve (#971) + - Improve docs + - Fix `export default` of an anonymous class with `extends` + +## v5.6.1 + + - Mark assignments to the `.prototype` of a class as pure + - Parenthesize `await` on the left of `**` (while accepting legacy non-parenthesised input) + - Avoided outputting NUL bytes in optimized RegExps, to stop the output from breaking other tools + - Added `exports` to domprops (#939) + - Fixed a crash when spreading `...this` + - Fixed the computed size of arrow functions, which improves their inlining + +## v5.6.0 + + - Added top-level await + - Beautify option has been removed in #895 + - Private properties, getters and setters have been added in #913 and some more commits + - Docs improvements: #896, #903, #916 + +## v5.5.1 + + - Fixed object properties with unicode surrogates on safari. + +## v5.5.0 + + - Fixed crash when inlining uninitialized variable into template string. + - The sourcemap for dist was removed for being too large. + +## v5.4.0 + + - Logical assignment + - Change `let x = undefined` to just `let x` + - Removed some optimizations for template strings, placing them behind `unsafe` options. Reason: adding strings is not equivalent to template strings, due to valueOf differences. + - The AST_Token class was slimmed down in order to use less memory. + +## v5.3.8 + + - Restore node 13 support + +## v5.3.7 + +Hotfix release, fixes package.json "engines" syntax + +## v5.3.6 + + - Fixed parentheses when outputting `??` mixed with `||` and `&&` + - Improved hygiene of the symbol generator + +## v5.3.5 + + - Avoid moving named functions into default exports. + - Enabled transform() for chain expressions. This allows AST transformers to reach inside chain expressions. + +## v5.3.4 + + - Fixed a crash when hoisting (with `hoist_vars`) a destructuring variable declaration + +## v5.3.3 + + - `source-map` library has been updated, bringing memory usage and CPU time improvements when reading input source maps (the SourceMapConsumer is now WASM based). + - The `wrap_func_args` option now also wraps arrow functions, as opposed to only function expressions. + +## v5.3.2 + + - Prevented spread operations from being expanded when the expanded array/object contains getters, setters, or array holes. + - Fixed _very_ slow self-recursion in some cases of removing extraneous parentheses from `+` operations. + +## v5.3.1 + + - An issue with destructuring declarations when `pure_getters` is enabled has been fixed + - Fixed a crash when chain expressions need to be shallowly compared + - Made inlining functions more conservative to make sure a function that contains a reference to itself isn't moved into a place that can create multiple instances of itself. + +## v5.3.0 + + - Fixed a crash when compressing object spreads in some cases + - Fixed compiletime evaluation of optional chains (caused typeof a?.b to always return "object") + - domprops has been updated to contain every single possible prop + +## v5.2.1 + + - The parse step now doesn't accept an `ecma` option, so that all ES code is accepted. + - Optional dotted chains now accept keywords, just like dotted expressions (`foo?.default`) + +## v5.2.0 + + - Optional chaining syntax is now supported. + - Consecutive await expressions don't have unnecessary parens + - Taking the variable name's length (after mangling) into consideration when deciding to inline + +## v5.1.0 + + - `import.meta` is now supported + - Typescript typings have been improved + +## v5.0.0 + + - `in` operator now taken into account during property mangle. + - Fixed infinite loop in face of a reference loop in some situations. + - Kept exports and imports around even if there's something which will throw before them. + - The main exported bundle for commonjs, dist/bundle.min.js is no longer minified. + +## v5.0.0-beta.0 + + - BREAKING: `minify()` is now async and rejects a promise instead of returning an error. + - BREAKING: Internal AST is no longer exposed, so that it can be improved without releasing breaking changes. + - BREAKING: Lowest supported node version is 10 + - BREAKING: There are no more warnings being emitted + - Module is now distributed as a dual package - You can `import` and `require()` too. + - Inline improvements were made + +## v4.8.0 + + - Support for numeric separators (`million = 1_000_000`) was added. + - Assigning properties to a class is now assumed to be pure. + - Fixed bug where `yield` wasn't considered a valid property key in generators. + +## v4.7.0 + + - A bug was fixed where an arrow function would have the wrong size + - `arguments` object is now considered safe to retrieve properties from (useful for `length`, or `0`) even when `pure_getters` is not set. + - Fixed erroneous `const` declarations without value (which is invalid) in some corner cases when using `collapse_vars`. + +## v4.6.13 + + - Fixed issue where ES5 object properties were being turned into ES6 object properties due to more lax unicode rules. + - Fixed parsing of BigInt with lowercase `e` in them. + +## v4.6.12 + + - Fixed subtree comparison code, making it see that `[1,[2, 3]]` is different from `[1, 2, [3]]` + - Printing of unicode identifiers has been improved + +## v4.6.11 + + - Read unused classes' properties and method keys, to figure out if they use other variables. + - Prevent inlining into block scopes when there are name collisions + - Functions are no longer inlined into parameter defaults, because they live in their own special scope. + - When inlining identity functions, take into account the fact they may be used to drop `this` in function calls. + - Nullish coalescing operator (`x ?? y`), plus basic optimization for it. + - Template literals in binary expressions such as `+` have been further optimized + +## v4.6.10 + + - Do not use reduce_vars when classes are present + +## v4.6.9 + + - Check if block scopes actually exist in blocks + +## v4.6.8 + + - Take into account "executed bits" of classes like static properties or computed keys, when checking if a class evaluation might throw or have side effects. + +## v4.6.7 + + - Some new performance gains through a `AST_Node.size()` method which measures a node's source code length without printing it to a string first. + - An issue with setting `--comments` to `false` in the CLI has been fixed. + - Fixed some issues with inlining + - `unsafe_symbols` compress option was added, which turns `Symbol("name")` into just `Symbol()` + - Brought back compress performance improvement through the `AST_Node.equivalent_to(other)` method (which was reverted in v4.6.6). + +## v4.6.6 + +(hotfix release) + + - Reverted code to 4.6.4 to allow for more time to investigate an issue. + +## v4.6.5 (REVERTED) + + - Improved compress performance through using a new method to see if two nodes are equivalent, instead of printing them to a string. + +## v4.6.4 + + - The `"some"` value in the `comments` output option now preserves `@lic` and other important comments when using `//` + - `` is now better escaped in regex, and in comments, when using the `inline_script` output option + - Fixed an issue when transforming `new RegExp` into `/.../` when slashes are included in the source + - `AST_Node.prototype.constructor` now exists, allowing for easier debugging of crashes + - Multiple if statements with the same consequents are now collapsed + - Typescript typings improvements + - Optimizations while looking for surrogate pairs in strings + +## v4.6.3 + + - Annotations such as `/*#__NOINLINE__*/` and `/*#__PURE__*/` may now be preserved using the `preserve_annotations` output option + - A TypeScript definition update for the `keep_quoted` output option. + +## v4.6.2 + + - A bug where functions were inlined into other functions with scope conflicts has been fixed. + - `/*#__NOINLINE__*/` annotation fixed for more use cases where inlining happens. + +## v4.6.1 + + - Fixed an issue where a class is duplicated by reduce_vars when there's a recursive reference to the class. + +## v4.6.0 + + - Fixed issues with recursive class references. + - BigInt evaluation has been prevented, stopping Terser from evaluating BigInts like it would do regular numbers. + - Class property support has been added + +## v4.5.1 + +(hotfix release) + + - Fixed issue where `() => ({})[something]` was not parenthesised correctly. + +## v4.5.0 + + - Inlining has been improved + - An issue where keep_fnames combined with functions declared through variables was causing name shadowing has been fixed + - You can now set the ES version through their year + - The output option `keep_numbers` has been added, which prevents Terser from turning `1000` into `1e3` and such + - Internal small optimisations and refactors + +## v4.4.3 + + - Number and BigInt parsing has been fixed + - `/*#__INLINE__*/` annotation fixed for arrow functions with non-block bodies. + - Functional tests have been added, using [this repository](https://github.com/terser/terser-functional-tests). + - A memory leak, where the entire AST lives on after compression, has been plugged. + +## v4.4.2 + + - Fixed a problem with inlining identity functions + +## v4.4.1 + +*note:* This introduced a feature, therefore it should have been a minor release. + + - Fixed a crash when `unsafe` was enabled. + - An issue has been fixed where `let` statements might be collapsed out of their scope. + - Some error messages have been improved by adding quotes around variable names. + +## v4.4.0 + + - Added `/*#__INLINE__*/` and `/*#__NOINLINE__*/` annotations for calls. If a call has one of these, it either forces or forbids inlining. + +## v4.3.11 + + - Fixed a problem where `window` was considered safe to access, even though there are situations where it isn't (Node.js, workers...) + - Fixed an error where `++` and `--` were considered side-effect free + - `Number(x)` now needs both `unsafe` and and `unsafe_math` to be compressed into `+x` because `x` might be a `BigInt` + - `keep_fnames` now correctly supports regexes when the function is in a variable declaration + +## v4.3.10 + + - Fixed syntax error when repeated semicolons were encountered in classes + - Fixed invalid output caused by the creation of empty sequences internally + - Scopes are now updated when scopes are inlined into them + +## v4.3.9 + - Fixed issue with mangle's `keep_fnames` option, introduced when adding code to keep variable names of anonymous functions + +## v4.3.8 + + - Typescript typings fix + +## v4.3.7 + + - Parsing of regex options in the CLI (which broke in v4.3.5) was fixed. + - typescript definition updates + +## v4.3.6 + +(crash hotfix) + +## v4.3.5 + + - Fixed an issue with DOS line endings strings separated by `\` and a new line. + - Improved fix for the output size regression related to unused references within the extends section of a class. + - Variable names of anonymous functions (eg: `const x = () => { ... }` or `var func = function () {...}`) are now preserved when keep_fnames is true. + - Fixed performance degradation introduced for large payloads in v4.2.0 + +## v4.3.4 + + - Fixed a regression where the output size was increased when unused classes were referred to in the extends clause of a class. + - Small typescript typings fixes. + - Comments with `@preserve`, `@license`, `@cc_on` as well as comments starting with `/*!` and `/**!` are now preserved by default. + +## v4.3.3 + + - Fixed a problem where parsing template strings would mix up octal notation and a slash followed by a zero representing a null character. + - Started accepting the name `async` in destructuring arguments with default value. + - Now Terser takes into account side effects inside class `extends` clauses. + - Added parens whenever there's a comment between a return statement and the returned value, to prevent issues with ASI. + - Stopped using raw RegExp objects, since the spec is going to continue to evolve. This ensures Terser is able to process new, unknown RegExp flags and features. This is a breaking change in the AST node AST_RegExp. + +## v4.3.2 + + - Typescript typing fix + - Ensure that functions can't be inlined, by reduce_vars, into places where they're accessing variables with the same name, but from somewhere else. + +## v4.3.1 + + - Fixed an issue from 4.3.0 where any block scope within a for loop erroneously had its parent set to the function scopee + - Fixed an issue where compressing IIFEs with argument expansions would result in some parameters becoming undefined + - addEventListener options argument's properties are now part of the DOM properties list. + +## v4.3.0 + + - Do not drop computed object keys with side effects + - Functions passed to other functions in calls are now wrapped in parentheses by default, which speeds up loading most modules + - Objects with computed properties are now less likely to be hoisted + - Speed and memory efficiency optimizations + - Fixed scoping issues with `try` and `switch` + +## v4.2.1 + + - Minor refactors + - Fixed a bug similar to #369 in collapse_vars + - Functions can no longer be inlined into a place where they're going to be compared with themselves. + - reduce_funcs option is now legacy, as using reduce_vars without reduce_funcs caused some weird corner cases. As a result, it is now implied in reduce_vars and can't be turned off without turning off reduce_vars. + - Bug which would cause a random stack overflow has now been fixed. + +## v4.2.0 + + - When the source map URL is `inline`, don't write it to a file. + - Fixed output parens when a lambda literal is the tag on a tagged template string. + - The `mangle.properties.undeclared` option was added. This enables the property mangler to mangle properties of variables which can be found in the name cache, but whose properties are not known to this Terser run. + - The v8 bug where the toString and source representations of regexes like `RegExp("\\\n")` includes an actual newline is now fixed. + - Now we're guaranteed to not have duplicate comments in the output + - Domprops updates + +## v4.1.4 + + - Fixed a crash when inlining a function into somewhere else when it has interdependent, non-removable variables. + +## v4.1.3 + + - Several issues with the `reduce_vars` option were fixed. + - Starting this version, we only have a dist/bundle.min.js + +## v4.1.2 + + - The hotfix was hotfixed + +## v4.1.1 + + - Fixed a bug where toplevel scopes were being mixed up with lambda scopes + +## v4.1.0 + + - Internal functions were replaced by `Object.assign`, `Array.prototype.some`, `Array.prototype.find` and `Array.prototype.every`. + - A serious issue where some ESM-native code was broken was fixed. + - Performance improvements were made. + - Support for BigInt was added. + - Inline efficiency was improved. Functions are now being inlined more proactively instead of being inlined only after another Compressor pass. + +## v4.0.2 + +(Hotfix release. Reverts unmapped segments PR [#342](https://github.com/terser/terser/pull/342), which will be put back on Terser when the upstream issue is resolved) + +## v4.0.1 + + - Collisions between the arguments of inlined functions and names in the outer scope are now being avoided while inlining + - Unmapped segments are now preserved when compressing a file which has source maps + - Default values of functions are now correctly converted from Mozilla AST to Terser AST + - JSON ⊂ ECMAScript spec (if you don't know what this is you don't need to) + - Export AST_* classes to library users + - Fixed issue with `collapse_vars` when functions are created with the same name as a variable which already exists + - Added `MutationObserverInit` (Object with options for initialising a mutation observer) properties to the DOM property list + - Custom `Error` subclasses are now internally used instead of old-school Error inheritance hacks. + - Documentation fixes + - Performance optimizations + +## v4.0.0 + + - **breaking change**: The `variables` property of all scopes has become a standard JavaScript `Map` as opposed to the old bespoke `Dictionary` object. + - Typescript definitions were fixed + - `terser --help` was fixed + - The public interface was cleaned up + - Fixed optimisation of `Array` and `new Array` + - Added the `keep_quoted=strict` mode to mangle_props, which behaves more like Google Closure Compiler by mangling all unquoted property names, instead of reserving quoted property names automatically. + - Fixed parent functions' parameters being shadowed in some cases + - Allowed Terser to run in a situation where there are custom functions attached to Object.prototype + - And more bug fixes, optimisations and internal changes + +## v3.17.0 + + - More DOM properties added to --mangle-properties's DOM property list + - Closed issue where if 2 functions had the same argument name, Terser would not inline them together properly + - Fixed issue with `hasOwnProperty.call` + - You can now list files to minify in a Terser config file + - Started replacing `new Array()` with an array literal + - Started using ES6 capabilities like `Set` and the `includes` method for strings and arrays + +## v3.16.1 + + - Fixed issue where Terser being imported with `import` would cause it not to work due to the `__esModule` property. (PR #254 was submitted, which was nice, but since it wasn't a pure commonJS approach I decided to go with my own solution) + +## v3.16.0 + + - No longer leaves names like Array or Object or window as a SimpleStatement (statement which is just a single expression). + - Add support for sections sourcemaps (IndexedSourceMapConsumer) + - Drops node.js v4 and starts using commonJS + - Is now built with rollup + +## v3.15.0 + + - Inlined spread syntax (`[...[1, 2, 3], 4, 5] => [1, 2, 3, 4, 5]`) in arrays and objects. + - Fixed typo in compressor warning + - Fixed inline source map input bug + - Fixed parsing of template literals with unnecessary escapes (Like `\\a`) diff --git a/node_modules/mathjs/examples/node_modules/terser/LICENSE b/node_modules/mathjs/examples/node_modules/terser/LICENSE new file mode 100644 index 0000000..f99e1fb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/LICENSE @@ -0,0 +1,29 @@ +Terser is released under the BSD license: + +Copyright 2012-2018 (c) Mihai Bazon + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, +OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. diff --git a/node_modules/mathjs/examples/node_modules/terser/PATRONS.md b/node_modules/mathjs/examples/node_modules/terser/PATRONS.md new file mode 100644 index 0000000..b2c8949 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/PATRONS.md @@ -0,0 +1,15 @@ +# Our patrons + +These are the first-tier patrons from [Patreon](https://www.patreon.com/fabiosantoscode). My appreciation goes to everyone on this list for supporting the project! + + * 38elements + * Alan Orozco + * Aria Buckles + * CKEditor + * Mariusz Nowak + * Nakshatra Mukhopadhyay + * Philippe Léger + * Piotrek Koszuliński + * Serhiy Shyyko + * Viktor Hubert + * 龙腾道 diff --git a/node_modules/mathjs/examples/node_modules/terser/README.md b/node_modules/mathjs/examples/node_modules/terser/README.md new file mode 100644 index 0000000..2e19701 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/README.md @@ -0,0 +1,1374 @@ +

    Terser

    + + [![NPM Version][npm-image]][npm-url] + [![NPM Downloads][downloads-image]][downloads-url] + [![Travis Build][travis-image]][travis-url] + [![Opencollective financial contributors][opencollective-contributors]][opencollective-url] + +A JavaScript mangler/compressor toolkit for ES6+. + +*note*: You can support this project on patreon: patron. Check out [PATRONS.md](https://github.com/terser/terser/blob/master/PATRONS.md) for our first-tier patrons. + +Terser recommends you use RollupJS to bundle your modules, as that produces smaller code overall. + +*Beautification* has been undocumented and is *being removed* from terser, we recommend you use [prettier](https://npmjs.com/package/prettier). + +Find the changelog in [CHANGELOG.md](https://github.com/terser/terser/blob/master/CHANGELOG.md) + + + +[npm-image]: https://img.shields.io/npm/v/terser.svg +[npm-url]: https://npmjs.org/package/terser +[downloads-image]: https://img.shields.io/npm/dm/terser.svg +[downloads-url]: https://npmjs.org/package/terser +[travis-image]: https://app.travis-ci.com/terser/terser.svg?branch=master +[travis-url]: https://app.travis-ci.com/github/terser/terser +[opencollective-contributors]: https://opencollective.com/terser/tiers/badge.svg +[opencollective-url]: https://opencollective.com/terser + +Why choose terser? +------------------ + +`uglify-es` is [no longer maintained](https://github.com/mishoo/UglifyJS2/issues/3156#issuecomment-392943058) and `uglify-js` does not support ES6+. + +**`terser`** is a fork of `uglify-es` that mostly retains API and CLI compatibility +with `uglify-es` and `uglify-js@3`. + +Install +------- + +First make sure you have installed the latest version of [node.js](http://nodejs.org/) +(You may need to restart your computer after this step). + +From NPM for use as a command line app: + + npm install terser -g + +From NPM for programmatic use: + + npm install terser + +# Command line usage + + + + terser [input files] [options] + +Terser can take multiple input files. It's recommended that you pass the +input files first, then pass the options. Terser will parse input files +in sequence and apply any compression options. The files are parsed in the +same global scope, that is, a reference from a file to some +variable/function declared in another file will be matched properly. + +Command line arguments that take options (like --parse, --compress, --mangle and +--format) can take in a comma-separated list of default option overrides. For +instance: + + terser input.js --compress ecma=2015,computed_props=false + +If no input file is specified, Terser will read from STDIN. + +If you wish to pass your options before the input files, separate the two with +a double dash to prevent input files being used as option arguments: + + terser --compress --mangle -- input.js + +### Command line options + +``` + -h, --help Print usage information. + `--help options` for details on available options. + -V, --version Print version number. + -p, --parse Specify parser options: + `acorn` Use Acorn for parsing. + `bare_returns` Allow return outside of functions. + Useful when minifying CommonJS + modules and Userscripts that may + be anonymous function wrapped (IIFE) + by the .user.js engine `caller`. + `expression` Parse a single expression, rather than + a program (for parsing JSON). + `spidermonkey` Assume input files are SpiderMonkey + AST format (as JSON). + -c, --compress [options] Enable compressor/specify compressor options: + `pure_funcs` List of functions that can be safely + removed when their return values are + not used. + -m, --mangle [options] Mangle names/specify mangler options: + `reserved` List of names that should not be mangled. + --mangle-props [options] Mangle properties/specify mangler options: + `builtins` Mangle property names that overlaps + with standard JavaScript globals and DOM + API props. + `debug` Add debug prefix and suffix. + `keep_quoted` Only mangle unquoted properties, quoted + properties are automatically reserved. + `strict` disables quoted properties + being automatically reserved. + `regex` Only mangle matched property names. + `reserved` List of names that should not be mangled. + -f, --format [options] Specify format options. + `preamble` Preamble to prepend to the output. You + can use this to insert a comment, for + example for licensing information. + This will not be parsed, but the source + map will adjust for its presence. + `quote_style` Quote style: + 0 - auto + 1 - single + 2 - double + 3 - original + `wrap_iife` Wrap IIFEs in parenthesis. Note: you may + want to disable `negate_iife` under + compressor options. + `wrap_func_args` Wrap function arguments in parenthesis. + -o, --output Output file path (default STDOUT). Specify `ast` or + `spidermonkey` to write Terser or SpiderMonkey AST + as JSON to STDOUT respectively. + --comments [filter] Preserve copyright comments in the output. By + default this works like Google Closure, keeping + JSDoc-style comments that contain e.g. "@license", + or start with "!". You can optionally pass one of the + following arguments to this flag: + - "all" to keep all comments + - `false` to omit comments in the output + - a valid JS RegExp like `/foo/` or `/^!/` to + keep only matching comments. + Note that currently not *all* comments can be + kept when compression is on, because of dead + code removal or cascading statements into + sequences. + --config-file Read `minify()` options from JSON file. + -d, --define [=value] Global definitions. + --ecma Specify ECMAScript release: 5, 2015, 2016, etc. + -e, --enclose [arg[:value]] Embed output in a big function with configurable + arguments and values. + --ie8 Support non-standard Internet Explorer 8. + Equivalent to setting `ie8: true` in `minify()` + for `compress`, `mangle` and `format` options. + By default Terser will not try to be IE-proof. + --keep-classnames Do not mangle/drop class names. + --keep-fnames Do not mangle/drop function names. Useful for + code relying on Function.prototype.name. + --module Input is an ES6 module. If `compress` or `mangle` is + enabled then the `toplevel` option will be enabled. + --name-cache File to hold mangled name mappings. + --safari10 Support non-standard Safari 10/11. + Equivalent to setting `safari10: true` in `minify()` + for `mangle` and `format` options. + By default `terser` will not work around + Safari 10/11 bugs. + --source-map [options] Enable source map/specify source map options: + `base` Path to compute relative paths from input files. + `content` Input source map, useful if you're compressing + JS that was generated from some other original + code. Specify "inline" if the source map is + included within the sources. + `filename` Name and/or location of the output source. + `includeSources` Pass this flag if you want to include + the content of source files in the + source map as sourcesContent property. + `root` Path to the original source to be included in + the source map. + `url` If specified, path to the source map to append in + `//# sourceMappingURL`. + --timings Display operations run time on STDERR. + --toplevel Compress and/or mangle variables in top level scope. + --wrap Embed everything in a big function, making the + “exports” and “global” variables available. You + need to pass an argument to this option to + specify the name that your module will take + when included in, say, a browser. +``` + +Specify `--output` (`-o`) to declare the output file. Otherwise the output +goes to STDOUT. + +## CLI source map options + +Terser can generate a source map file, which is highly useful for +debugging your compressed JavaScript. To get a source map, pass +`--source-map --output output.js` (source map will be written out to +`output.js.map`). + +Additional options: + +- `--source-map "filename=''"` to specify the name of the source map. + +- `--source-map "root=''"` to pass the URL where the original files can be found. + +- `--source-map "url=''"` to specify the URL where the source map can be found. + Otherwise Terser assumes HTTP `X-SourceMap` is being used and will omit the + `//# sourceMappingURL=` directive. + +For example: + + terser js/file1.js js/file2.js \ + -o foo.min.js -c -m \ + --source-map "root='http://foo.com/src',url='foo.min.js.map'" + +The above will compress and mangle `file1.js` and `file2.js`, will drop the +output in `foo.min.js` and the source map in `foo.min.js.map`. The source +mapping will refer to `http://foo.com/src/js/file1.js` and +`http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src` +as the source map root, and the original files as `js/file1.js` and +`js/file2.js`). + +### Composed source map + +When you're compressing JS code that was output by a compiler such as +CoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd +like to map back to the original code (i.e. CoffeeScript). Terser has an +option to take an input source map. Assuming you have a mapping from +CoffeeScript → compiled JS, Terser can generate a map from CoffeeScript → +compressed JS by mapping every token in the compiled JS to its original +location. + +To use this feature pass `--source-map "content='/path/to/input/source.map'"` +or `--source-map "content=inline"` if the source map is included inline with +the sources. + +## CLI compress options + +You need to pass `--compress` (`-c`) to enable the compressor. Optionally +you can pass a comma-separated list of [compress options](#compress-options). + +Options are in the form `foo=bar`, or just `foo` (the latter implies +a boolean option that you want to set `true`; it's effectively a +shortcut for `foo=true`). + +Example: + + terser file.js -c toplevel,sequences=false + +## CLI mangle options + +To enable the mangler you need to pass `--mangle` (`-m`). The following +(comma-separated) options are supported: + +- `toplevel` (default `false`) -- mangle names declared in the top level scope. + +- `eval` (default `false`) -- mangle names visible in scopes where `eval` or `with` are used. + +When mangling is enabled but you want to prevent certain names from being +mangled, you can declare those names with `--mangle reserved` — pass a +comma-separated list of names. For example: + + terser ... -m reserved=['$','require','exports'] + +to prevent the `require`, `exports` and `$` names from being changed. + +### CLI mangling property names (`--mangle-props`) + +**Note:** THIS **WILL** BREAK YOUR CODE. A good rule of thumb is not to use this unless you know exactly what you're doing and how this works and read this section until the end. + +Mangling property names is a separate step, different from variable name mangling. Pass +`--mangle-props` to enable it. The least dangerous +way to use this is to use the `regex` option like so: + +``` +terser example.js -c -m --mangle-props regex=/_$/ +``` + +This will mangle all properties that end with an +underscore. So you can use it to mangle internal methods. + +By default, it will mangle all properties in the +input code with the exception of built in DOM properties and properties +in core JavaScript classes, which is what will break your code if you don't: + +1. Control all the code you're mangling +2. Avoid using a module bundler, as they usually will call Terser on each file individually, making it impossible to pass mangled objects between modules. +3. Avoid calling functions like `defineProperty` or `hasOwnProperty`, because they refer to object properties using strings and will break your code if you don't know what you are doing. + +An example: + +```javascript +// example.js +var x = { + baz_: 0, + foo_: 1, + calc: function() { + return this.foo_ + this.baz_; + } +}; +x.bar_ = 2; +x["baz_"] = 3; +console.log(x.calc()); +``` +Mangle all properties (except for JavaScript `builtins`) (**very** unsafe): +```bash +$ terser example.js -c passes=2 -m --mangle-props +``` +```javascript +var x={o:3,t:1,i:function(){return this.t+this.o},s:2};console.log(x.i()); +``` +Mangle all properties except for `reserved` properties (still very unsafe): +```bash +$ terser example.js -c passes=2 -m --mangle-props reserved=[foo_,bar_] +``` +```javascript +var x={o:3,foo_:1,t:function(){return this.foo_+this.o},bar_:2};console.log(x.t()); +``` +Mangle all properties matching a `regex` (not as unsafe but still unsafe): +```bash +$ terser example.js -c passes=2 -m --mangle-props regex=/_$/ +``` +```javascript +var x={o:3,t:1,calc:function(){return this.t+this.o},i:2};console.log(x.calc()); +``` + +Combining mangle properties options: +```bash +$ terser example.js -c passes=2 -m --mangle-props regex=/_$/,reserved=[bar_] +``` +```javascript +var x={o:3,t:1,calc:function(){return this.t+this.o},bar_:2};console.log(x.calc()); +``` + +In order for this to be of any use, we avoid mangling standard JS names and DOM +API properties by default (`--mangle-props builtins` to override). + +A regular expression can be used to define which property names should be +mangled. For example, `--mangle-props regex=/^_/` will only mangle property +names that start with an underscore. + +When you compress multiple files using this option, in order for them to +work together in the end we need to ensure somehow that one property gets +mangled to the same name in all of them. For this, pass `--name-cache filename.json` +and Terser will maintain these mappings in a file which can then be reused. +It should be initially empty. Example: + +```bash +$ rm -f /tmp/cache.json # start fresh +$ terser file1.js file2.js --mangle-props --name-cache /tmp/cache.json -o part1.js +$ terser file3.js file4.js --mangle-props --name-cache /tmp/cache.json -o part2.js +``` + +Now, `part1.js` and `part2.js` will be consistent with each other in terms +of mangled property names. + +Using the name cache is not necessary if you compress all your files in a +single call to Terser. + +### Mangling unquoted names (`--mangle-props keep_quoted`) + +Using quoted property name (`o["foo"]`) reserves the property name (`foo`) +so that it is not mangled throughout the entire script even when used in an +unquoted style (`o.foo`). Example: + +```javascript +// stuff.js +var o = { + "foo": 1, + bar: 3 +}; +o.foo += o.bar; +console.log(o.foo); +``` +```bash +$ terser stuff.js --mangle-props keep_quoted -c -m +``` +```javascript +var o={foo:1,o:3};o.foo+=o.o,console.log(o.foo); +``` + +### Debugging property name mangling + +You can also pass `--mangle-props debug` in order to mangle property names +without completely obscuring them. For example the property `o.foo` +would mangle to `o._$foo$_` with this option. This allows property mangling +of a large codebase while still being able to debug the code and identify +where mangling is breaking things. + +```bash +$ terser stuff.js --mangle-props debug -c -m +``` +```javascript +var o={_$foo$_:1,_$bar$_:3};o._$foo$_+=o._$bar$_,console.log(o._$foo$_); +``` + +You can also pass a custom suffix using `--mangle-props debug=XYZ`. This would then +mangle `o.foo` to `o._$foo$XYZ_`. You can change this each time you compile a +script to identify how a property got mangled. One technique is to pass a +random number on every compile to simulate mangling changing with different +inputs (e.g. as you update the input script with new properties), and to help +identify mistakes like writing mangled keys to storage. + + + +# API Reference + + + +Assuming installation via NPM, you can load Terser in your application +like this: + +```javascript +const { minify } = require("terser"); +``` + +Or, + +```javascript +import { minify } from "terser"; +``` + +Browser loading is also supported: +```html + + +``` + +There is a single async high level function, **`async minify(code, options)`**, +which will perform all minification [phases](#minify-options) in a configurable +manner. By default `minify()` will enable [`compress`](#compress-options) +and [`mangle`](#mangle-options). Example: +```javascript +var code = "function add(first, second) { return first + second; }"; +var result = await minify(code, { sourceMap: true }); +console.log(result.code); // minified output: function add(n,d){return n+d} +console.log(result.map); // source map +``` + +You can `minify` more than one JavaScript file at a time by using an object +for the first argument where the keys are file names and the values are source +code: +```javascript +var code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; +var result = await minify(code); +console.log(result.code); +// function add(d,n){return d+n}console.log(add(3,7)); +``` + +The `toplevel` option: +```javascript +var code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; +var options = { toplevel: true }; +var result = await minify(code, options); +console.log(result.code); +// console.log(3+7); +``` + +The `nameCache` option: +```javascript +var options = { + mangle: { + toplevel: true, + }, + nameCache: {} +}; +var result1 = await minify({ + "file1.js": "function add(first, second) { return first + second; }" +}, options); +var result2 = await minify({ + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}, options); +console.log(result1.code); +// function n(n,r){return n+r} +console.log(result2.code); +// console.log(n(3,7)); +``` + +You may persist the name cache to the file system in the following way: +```javascript +var cacheFileName = "/tmp/cache.json"; +var options = { + mangle: { + properties: true, + }, + nameCache: JSON.parse(fs.readFileSync(cacheFileName, "utf8")) +}; +fs.writeFileSync("part1.js", await minify({ + "file1.js": fs.readFileSync("file1.js", "utf8"), + "file2.js": fs.readFileSync("file2.js", "utf8") +}, options).code, "utf8"); +fs.writeFileSync("part2.js", await minify({ + "file3.js": fs.readFileSync("file3.js", "utf8"), + "file4.js": fs.readFileSync("file4.js", "utf8") +}, options).code, "utf8"); +fs.writeFileSync(cacheFileName, JSON.stringify(options.nameCache), "utf8"); +``` + +An example of a combination of `minify()` options: +```javascript +var code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; +var options = { + toplevel: true, + compress: { + global_defs: { + "@console.log": "alert" + }, + passes: 2 + }, + format: { + preamble: "/* minified */" + } +}; +var result = await minify(code, options); +console.log(result.code); +// /* minified */ +// alert(10);" +``` + +An error example: +```javascript +try { + const result = await minify({"foo.js" : "if (0) else console.log(1);"}); + // Do something with result +} catch (error) { + const { message, filename, line, col, pos } = error; + // Do something with error +} +``` + +## Minify options + +- `ecma` (default `undefined`) - pass `5`, `2015`, `2016`, etc to override + `compress` and `format`'s `ecma` options. + +- `enclose` (default `false`) - pass `true`, or a string in the format + of `"args[:values]"`, where `args` and `values` are comma-separated + argument names and values, respectively, to embed the output in a big + function with the configurable arguments and values. + +- `parse` (default `{}`) — pass an object if you wish to specify some + additional [parse options](#parse-options). + +- `compress` (default `{}`) — pass `false` to skip compressing entirely. + Pass an object to specify custom [compress options](#compress-options). + +- `mangle` (default `true`) — pass `false` to skip mangling names, or pass + an object to specify [mangle options](#mangle-options) (see below). + + - `mangle.properties` (default `false`) — a subcategory of the mangle option. + Pass an object to specify custom [mangle property options](#mangle-properties-options). + +- `module` (default `false`) — Use when minifying an ES6 module. "use strict" + is implied and names can be mangled on the top scope. If `compress` or + `mangle` is enabled then the `toplevel` option will be enabled. + +- `format` or `output` (default `null`) — pass an object if you wish to specify + additional [format options](#format-options). The defaults are optimized + for best compression. + +- `sourceMap` (default `false`) - pass an object if you wish to specify + [source map options](#source-map-options). + +- `toplevel` (default `false`) - set to `true` if you wish to enable top level + variable and function name mangling and to drop unused variables and functions. + +- `nameCache` (default `null`) - pass an empty object `{}` or a previously + used `nameCache` object if you wish to cache mangled variable and + property names across multiple invocations of `minify()`. Note: this is + a read/write property. `minify()` will read the name cache state of this + object and update it during minification so that it may be + reused or externally persisted by the user. + +- `ie8` (default `false`) - set to `true` to support IE8. + +- `keep_classnames` (default: `undefined`) - pass `true` to prevent discarding or mangling + of class names. Pass a regular expression to only keep class names matching that regex. + +- `keep_fnames` (default: `false`) - pass `true` to prevent discarding or mangling + of function names. Pass a regular expression to only keep function names matching that regex. + Useful for code relying on `Function.prototype.name`. If the top level minify option + `keep_classnames` is `undefined` it will be overridden with the value of the top level + minify option `keep_fnames`. + +- `safari10` (default: `false`) - pass `true` to work around Safari 10/11 bugs in + loop scoping and `await`. See `safari10` options in [`mangle`](#mangle-options) + and [`format`](#format-options) for details. + +## Minify options structure + +```javascript +{ + parse: { + // parse options + }, + compress: { + // compress options + }, + mangle: { + // mangle options + + properties: { + // mangle property options + } + }, + format: { + // format options (can also use `output` for backwards compatibility) + }, + sourceMap: { + // source map options + }, + ecma: 5, // specify one of: 5, 2015, 2016, etc. + enclose: false, // or specify true, or "args:values" + keep_classnames: false, + keep_fnames: false, + ie8: false, + module: false, + nameCache: null, // or specify a name cache object + safari10: false, + toplevel: false +} +``` + +### Source map options + +To generate a source map: +```javascript +var result = await minify({"file1.js": "var a = function() {};"}, { + sourceMap: { + filename: "out.js", + url: "out.js.map" + } +}); +console.log(result.code); // minified output +console.log(result.map); // source map +``` + +Note that the source map is not saved in a file, it's just returned in +`result.map`. The value passed for `sourceMap.url` is only used to set +`//# sourceMappingURL=out.js.map` in `result.code`. The value of +`filename` is only used to set `file` attribute (see [the spec][sm-spec]) +in source map file. + +You can set option `sourceMap.url` to be `"inline"` and source map will +be appended to code. + +You can also specify sourceRoot property to be included in source map: +```javascript +var result = await minify({"file1.js": "var a = function() {};"}, { + sourceMap: { + root: "http://example.com/src", + url: "out.js.map" + } +}); +``` + +If you're compressing compiled JavaScript and have a source map for it, you +can use `sourceMap.content`: +```javascript +var result = await minify({"compiled.js": "compiled code"}, { + sourceMap: { + content: "content from compiled.js.map", + url: "minified.js.map" + } +}); +// same as before, it returns `code` and `map` +``` + +If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.url`. + +If you happen to need the source map as a raw object, set `sourceMap.asObject` to `true`. + +## Parse options + +- `bare_returns` (default `false`) -- support top level `return` statements + +- `html5_comments` (default `true`) + +- `shebang` (default `true`) -- support `#!command` as the first line + +- `spidermonkey` (default `false`) -- accept a Spidermonkey (Mozilla) AST + +## Compress options + +- `defaults` (default: `true`) -- Pass `false` to disable most default + enabled `compress` transforms. Useful when you only want to enable a few + `compress` options while disabling the rest. + +- `arrows` (default: `true`) -- Class and object literal methods are converted + will also be converted to arrow expressions if the resultant code is shorter: + `m(){return x}` becomes `m:()=>x`. To do this to regular ES5 functions which + don't use `this` or `arguments`, see `unsafe_arrows`. + +- `arguments` (default: `false`) -- replace `arguments[index]` with function + parameter name whenever possible. + +- `booleans` (default: `true`) -- various optimizations for boolean context, + for example `!!a ? b : c → a ? b : c` + +- `booleans_as_integers` (default: `false`) -- Turn booleans into 0 and 1, also + makes comparisons with booleans use `==` and `!=` instead of `===` and `!==`. + +- `collapse_vars` (default: `true`) -- Collapse single-use non-constant variables, + side effects permitting. + +- `comparisons` (default: `true`) -- apply certain optimizations to binary nodes, + e.g. `!(a <= b) → a > b` (only when `unsafe_comps`), attempts to negate binary + nodes, e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc. + +- `computed_props` (default: `true`) -- Transforms constant computed properties + into regular ones: `{["computed"]: 1}` is converted to `{computed: 1}`. + +- `conditionals` (default: `true`) -- apply optimizations for `if`-s and conditional + expressions + +- `dead_code` (default: `true`) -- remove unreachable code + +- `directives` (default: `true`) -- remove redundant or non-standard directives + +- `drop_console` (default: `false`) -- Pass `true` to discard calls to + `console.*` functions. If you wish to drop a specific function call + such as `console.info` and/or retain side effects from function arguments + after dropping the function call then use `pure_funcs` instead. + +- `drop_debugger` (default: `true`) -- remove `debugger;` statements + +- `ecma` (default: `5`) -- Pass `2015` or greater to enable `compress` options that + will transform ES5 code into smaller ES6+ equivalent forms. + +- `evaluate` (default: `true`) -- attempt to evaluate constant expressions + +- `expression` (default: `false`) -- Pass `true` to preserve completion values + from terminal statements without `return`, e.g. in bookmarklets. + +- `global_defs` (default: `{}`) -- see [conditional compilation](#conditional-compilation) + +- `hoist_funs` (default: `false`) -- hoist function declarations + +- `hoist_props` (default: `true`) -- hoist properties from constant object and + array literals into regular variables subject to a set of constraints. For example: + `var o={p:1, q:2}; f(o.p, o.q);` is converted to `f(1, 2);`. Note: `hoist_props` + works best with `mangle` enabled, the `compress` option `passes` set to `2` or higher, + and the `compress` option `toplevel` enabled. + +- `hoist_vars` (default: `false`) -- hoist `var` declarations (this is `false` + by default because it seems to increase the size of the output in general) + +- `if_return` (default: `true`) -- optimizations for if/return and if/continue + +- `inline` (default: `true`) -- inline calls to function with simple/`return` statement: + - `false` -- same as `0` + - `0` -- disabled inlining + - `1` -- inline simple functions + - `2` -- inline functions with arguments + - `3` -- inline functions with arguments and variables + - `true` -- same as `3` + +- `join_vars` (default: `true`) -- join consecutive `var` statements + +- `keep_classnames` (default: `false`) -- Pass `true` to prevent the compressor from + discarding class names. Pass a regular expression to only keep class names matching + that regex. See also: the `keep_classnames` [mangle option](#mangle-options). + +- `keep_fargs` (default: `true`) -- Prevents the compressor from discarding unused + function arguments. You need this for code which relies on `Function.length`. + +- `keep_fnames` (default: `false`) -- Pass `true` to prevent the + compressor from discarding function names. Pass a regular expression to only keep + function names matching that regex. Useful for code relying on `Function.prototype.name`. + See also: the `keep_fnames` [mangle option](#mangle-options). + +- `keep_infinity` (default: `false`) -- Pass `true` to prevent `Infinity` from + being compressed into `1/0`, which may cause performance issues on Chrome. + +- `loops` (default: `true`) -- optimizations for `do`, `while` and `for` loops + when we can statically determine the condition. + +- `module` (default `false`) -- Pass `true` when compressing an ES6 module. Strict + mode is implied and the `toplevel` option as well. + +- `negate_iife` (default: `true`) -- negate "Immediately-Called Function Expressions" + where the return value is discarded, to avoid the parens that the + code generator would insert. + +- `passes` (default: `1`) -- The maximum number of times to run compress. + In some cases more than one pass leads to further compressed code. Keep in + mind more passes will take more time. + +- `properties` (default: `true`) -- rewrite property access using the dot notation, for + example `foo["bar"] → foo.bar` + +- `pure_funcs` (default: `null`) -- You can pass an array of names and + Terser will assume that those functions do not produce side + effects. DANGER: will not check if the name is redefined in scope. + An example case here, for instance `var q = Math.floor(a/b)`. If + variable `q` is not used elsewhere, Terser will drop it, but will + still keep the `Math.floor(a/b)`, not knowing what it does. You can + pass `pure_funcs: [ 'Math.floor' ]` to let it know that this + function won't produce any side effect, in which case the whole + statement would get discarded. The current implementation adds some + overhead (compression will be slower). + +- `pure_getters` (default: `"strict"`) -- If you pass `true` for + this, Terser will assume that object property access + (e.g. `foo.bar` or `foo["bar"]`) doesn't have any side effects. + Specify `"strict"` to treat `foo.bar` as side-effect-free only when + `foo` is certain to not throw, i.e. not `null` or `undefined`. + +- `reduce_vars` (default: `true`) -- Improve optimization on variables assigned with and + used as constant values. + +- `reduce_funcs` (default: `true`) -- Inline single-use functions when + possible. Depends on `reduce_vars` being enabled. Disabling this option + sometimes improves performance of the output code. + +- `sequences` (default: `true`) -- join consecutive simple statements using the + comma operator. May be set to a positive integer to specify the maximum number + of consecutive comma sequences that will be generated. If this option is set to + `true` then the default `sequences` limit is `200`. Set option to `false` or `0` + to disable. The smallest `sequences` length is `2`. A `sequences` value of `1` + is grandfathered to be equivalent to `true` and as such means `200`. On rare + occasions the default sequences limit leads to very slow compress times in which + case a value of `20` or less is recommended. + +- `side_effects` (default: `true`) -- Remove expressions which have no side effects + and whose results aren't used. + +- `switches` (default: `true`) -- de-duplicate and remove unreachable `switch` branches + +- `toplevel` (default: `false`) -- drop unreferenced functions (`"funcs"`) and/or + variables (`"vars"`) in the top level scope (`false` by default, `true` to drop + both unreferenced functions and variables) + +- `top_retain` (default: `null`) -- prevent specific toplevel functions and + variables from `unused` removal (can be array, comma-separated, RegExp or + function. Implies `toplevel`) + +- `typeofs` (default: `true`) -- Transforms `typeof foo == "undefined"` into + `foo === void 0`. Note: recommend to set this value to `false` for IE10 and + earlier versions due to known issues. + +- `unsafe` (default: `false`) -- apply "unsafe" transformations + ([details](#the-unsafe-compress-option)). + +- `unsafe_arrows` (default: `false`) -- Convert ES5 style anonymous function + expressions to arrow functions if the function body does not reference `this`. + Note: it is not always safe to perform this conversion if code relies on the + the function having a `prototype`, which arrow functions lack. + This transform requires that the `ecma` compress option is set to `2015` or greater. + +- `unsafe_comps` (default: `false`) -- Reverse `<` and `<=` to `>` and `>=` to + allow improved compression. This might be unsafe when an at least one of two + operands is an object with computed values due the use of methods like `get`, + or `valueOf`. This could cause change in execution order after operands in the + comparison are switching. Compression only works if both `comparisons` and + `unsafe_comps` are both set to true. + +- `unsafe_Function` (default: `false`) -- compress and mangle `Function(args, code)` + when both `args` and `code` are string literals. + +- `unsafe_math` (default: `false`) -- optimize numerical expressions like + `2 * x * 3` into `6 * x`, which may give imprecise floating point results. + +- `unsafe_symbols` (default: `false`) -- removes keys from native Symbol + declarations, e.g `Symbol("kDog")` becomes `Symbol()`. + +- `unsafe_methods` (default: false) -- Converts `{ m: function(){} }` to + `{ m(){} }`. `ecma` must be set to `6` or greater to enable this transform. + If `unsafe_methods` is a RegExp then key/value pairs with keys matching the + RegExp will be converted to concise methods. + Note: if enabled there is a risk of getting a "`` is not a + constructor" TypeError should any code try to `new` the former function. + +- `unsafe_proto` (default: `false`) -- optimize expressions like + `Array.prototype.slice.call(a)` into `[].slice.call(a)` + +- `unsafe_regexp` (default: `false`) -- enable substitutions of variables with + `RegExp` values the same way as if they are constants. + +- `unsafe_undefined` (default: `false`) -- substitute `void 0` if there is a + variable named `undefined` in scope (variable name will be mangled, typically + reduced to a single character) + +- `unused` (default: `true`) -- drop unreferenced functions and variables (simple + direct variable assignments do not count as references unless set to `"keep_assign"`) + +## Mangle options + +- `eval` (default `false`) -- Pass `true` to mangle names visible in scopes + where `eval` or `with` are used. + +- `keep_classnames` (default `false`) -- Pass `true` to not mangle class names. + Pass a regular expression to only keep class names matching that regex. + See also: the `keep_classnames` [compress option](#compress-options). + +- `keep_fnames` (default `false`) -- Pass `true` to not mangle function names. + Pass a regular expression to only keep function names matching that regex. + Useful for code relying on `Function.prototype.name`. See also: the `keep_fnames` + [compress option](#compress-options). + +- `module` (default `false`) -- Pass `true` an ES6 modules, where the toplevel + scope is not the global scope. Implies `toplevel`. + +- `nth_identifier` (default: an internal mangler that weights based on character + frequency analysis) -- Pass an object with a `get(n)` function that converts an + ordinal into the nth most favored (usually shortest) identifier. + Optionally also provide `reset()`, `sort()`, and `consider(chars, delta)` to + use character frequency analysis of the source code. + +- `reserved` (default `[]`) -- Pass an array of identifiers that should be + excluded from mangling. Example: `["foo", "bar"]`. + +- `toplevel` (default `false`) -- Pass `true` to mangle names declared in the + top level scope. + +- `safari10` (default `false`) -- Pass `true` to work around the Safari 10 loop + iterator [bug](https://bugs.webkit.org/show_bug.cgi?id=171041) + "Cannot declare a let variable twice". + See also: the `safari10` [format option](#format-options). + +Examples: + +```javascript +// test.js +var globalVar; +function funcName(firstLongName, anotherLongName) { + var myVariable = firstLongName + anotherLongName; +} +``` +```javascript +var code = fs.readFileSync("test.js", "utf8"); + +await minify(code).code; +// 'function funcName(a,n){}var globalVar;' + +await minify(code, { mangle: { reserved: ['firstLongName'] } }).code; +// 'function funcName(firstLongName,a){}var globalVar;' + +await minify(code, { mangle: { toplevel: true } }).code; +// 'function n(n,a){}var a;' +``` + +### Mangle properties options + +- `builtins` (default: `false`) — Use `true` to allow the mangling of builtin + DOM properties. Not recommended to override this setting. + +- `debug` (default: `false`) — Mangle names with the original name still present. + Pass an empty string `""` to enable, or a non-empty string to set the debug suffix. + +- `keep_quoted` (default: `false`) — How quoting properties (`{"prop": ...}` and `obj["prop"]`) controls what gets mangled. + - `"strict"` (recommended) -- `obj.prop` is mangled. + - `false` -- `obj["prop"]` is mangled. + - `true` -- `obj.prop` is mangled unless there is `obj["prop"]` elsewhere in the code. + +- `nth_identifer` (default: an internal mangler that weights based on character + frequency analysis) -- Pass an object with a `get(n)` function that converts an + ordinal into the nth most favored (usually shortest) identifier. + Optionally also provide `reset()`, `sort()`, and `consider(chars, delta)` to + use character frequency analysis of the source code. + +- `regex` (default: `null`) — Pass a [RegExp literal or pattern string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to only mangle property matching the regular expression. + +- `reserved` (default: `[]`) — Do not mangle property names listed in the + `reserved` array. + +- `undeclared` (default: `false`) - Mangle those names when they are accessed + as properties of known top level variables but their declarations are never + found in input code. May be useful when only minifying parts of a project. + See [#397](https://github.com/terser/terser/issues/397) for more details. + + +## Format options + +These options control the format of Terser's output code. Previously known +as "output options". + +- `ascii_only` (default `false`) -- escape Unicode characters in strings and + regexps (affects directives with non-ascii characters becoming invalid) + +- `beautify` (default `false`) -- (DEPRECATED) whether to beautify the output. + When using the legacy `-b` CLI flag, this is set to true by default. + +- `braces` (default `false`) -- always insert braces in `if`, `for`, + `do`, `while` or `with` statements, even if their body is a single + statement. + +- `comments` (default `"some"`) -- by default it keeps JSDoc-style comments + that contain "@license", "@copyright", "@preserve" or start with `!`, pass `true` + or `"all"` to preserve all comments, `false` to omit comments in the output, + a regular expression string (e.g. `/^!/`) or a function. + +- `ecma` (default `5`) -- set desired EcmaScript standard version for output. + Set `ecma` to `2015` or greater to emit shorthand object properties - i.e.: + `{a}` instead of `{a: a}`. The `ecma` option will only change the output in + direct control of the beautifier. Non-compatible features in your input will + still be output as is. For example: an `ecma` setting of `5` will **not** + convert modern code to ES5. + +- `indent_level` (default `4`) + +- `indent_start` (default `0`) -- prefix all lines by that many spaces + +- `inline_script` (default `true`) -- escape HTML comments and the slash in + occurrences of `` in strings + +- `keep_numbers` (default `false`) -- keep number literals as it was in original code + (disables optimizations like converting `1000000` into `1e6`) + +- `keep_quoted_props` (default `false`) -- when turned on, prevents stripping + quotes from property names in object literals. + +- `max_line_len` (default `false`) -- maximum line length (for minified code) + +- `preamble` (default `null`) -- when passed it must be a string and + it will be prepended to the output literally. The source map will + adjust for this text. Can be used to insert a comment containing + licensing information, for example. + +- `quote_keys` (default `false`) -- pass `true` to quote all keys in literal + objects + +- `quote_style` (default `0`) -- preferred quote style for strings (affects + quoted property names and directives as well): + - `0` -- prefers double quotes, switches to single quotes when there are + more double quotes in the string itself. `0` is best for gzip size. + - `1` -- always use single quotes + - `2` -- always use double quotes + - `3` -- always use the original quotes + +- `preserve_annotations` -- (default `false`) -- Preserve [Terser annotations](#annotations) in the output. + +- `safari10` (default `false`) -- set this option to `true` to work around + the [Safari 10/11 await bug](https://bugs.webkit.org/show_bug.cgi?id=176685). + See also: the `safari10` [mangle option](#mangle-options). + +- `semicolons` (default `true`) -- separate statements with semicolons. If + you pass `false` then whenever possible we will use a newline instead of a + semicolon, leading to more readable output of minified code (size before + gzip could be smaller; size after gzip insignificantly larger). + +- `shebang` (default `true`) -- preserve shebang `#!` in preamble (bash scripts) + +- `spidermonkey` (default `false`) -- produce a Spidermonkey (Mozilla) AST + +- `webkit` (default `false`) -- enable workarounds for WebKit bugs. + PhantomJS users should set this option to `true`. + +- `wrap_iife` (default `false`) -- pass `true` to wrap immediately invoked + function expressions. See + [#640](https://github.com/mishoo/UglifyJS2/issues/640) for more details. + +- `wrap_func_args` (default `true`) -- pass `false` if you do not want to wrap + function expressions that are passed as arguments, in parenthesis. See + [OptimizeJS](https://github.com/nolanlawson/optimize-js) for more details. + +# Miscellaneous + +### Keeping copyright notices or other comments + +You can pass `--comments` to retain certain comments in the output. By +default it will keep comments starting with "!" and JSDoc-style comments that +contain "@preserve", "@copyright", "@license" or "@cc_on" (conditional compilation for IE). +You can pass `--comments all` to keep all the comments, or a valid JavaScript regexp to +keep only comments that match this regexp. For example `--comments /^!/` +will keep comments like `/*! Copyright Notice */`. + +Note, however, that there might be situations where comments are lost. For +example: +```javascript +function f() { + /** @preserve Foo Bar */ + function g() { + // this function is never called + } + return something(); +} +``` + +Even though it has "@preserve", the comment will be lost because the inner +function `g` (which is the AST node to which the comment is attached to) is +discarded by the compressor as not referenced. + +The safest comments where to place copyright information (or other info that +needs to be kept in the output) are comments attached to toplevel nodes. + +### The `unsafe` `compress` option + +It enables some transformations that *might* break code logic in certain +contrived cases, but should be fine for most code. It assumes that standard +built-in ECMAScript functions and classes have not been altered or replaced. +You might want to try it on your own code; it should reduce the minified size. +Some examples of the optimizations made when this option is enabled: + +- `new Array(1, 2, 3)` or `Array(1, 2, 3)` → `[ 1, 2, 3 ]` +- `Array.from([1, 2, 3])` → `[1, 2, 3]` +- `new Object()` → `{}` +- `String(exp)` or `exp.toString()` → `"" + exp` +- `new Object/RegExp/Function/Error/Array (...)` → we discard the `new` +- `"foo bar".substr(4)` → `"bar"` + +### Conditional compilation + +You can use the `--define` (`-d`) switch in order to declare global +variables that Terser will assume to be constants (unless defined in +scope). For example if you pass `--define DEBUG=false` then, coupled with +dead code removal Terser will discard the following from the output: +```javascript +if (DEBUG) { + console.log("debug stuff"); +} +``` + +You can specify nested constants in the form of `--define env.DEBUG=false`. + +Another way of doing that is to declare your globals as constants in a +separate file and include it into the build. For example you can have a +`build/defines.js` file with the following: +```javascript +var DEBUG = false; +var PRODUCTION = true; +// etc. +``` + +and build your code like this: + + terser build/defines.js js/foo.js js/bar.js... -c + +Terser will notice the constants and, since they cannot be altered, it +will evaluate references to them to the value itself and drop unreachable +code as usual. The build will contain the `const` declarations if you use +them. If you are targeting < ES6 environments which does not support `const`, +using `var` with `reduce_vars` (enabled by default) should suffice. + +### Conditional compilation API + +You can also use conditional compilation via the programmatic API. With the difference that the +property name is `global_defs` and is a compressor property: + +```javascript +var result = await minify(fs.readFileSync("input.js", "utf8"), { + compress: { + dead_code: true, + global_defs: { + DEBUG: false + } + } +}); +``` + +To replace an identifier with an arbitrary non-constant expression it is +necessary to prefix the `global_defs` key with `"@"` to instruct Terser +to parse the value as an expression: +```javascript +await minify("alert('hello');", { + compress: { + global_defs: { + "@alert": "console.log" + } + } +}).code; +// returns: 'console.log("hello");' +``` + +Otherwise it would be replaced as string literal: +```javascript +await minify("alert('hello');", { + compress: { + global_defs: { + "alert": "console.log" + } + } +}).code; +// returns: '"console.log"("hello");' +``` + +### Annotations + +Annotations in Terser are a way to tell it to treat a certain function call differently. The following annotations are available: + + * `/*@__INLINE__*/` - forces a function to be inlined somewhere. + * `/*@__NOINLINE__*/` - Makes sure the called function is not inlined into the call site. + * `/*@__PURE__*/` - Marks a function call as pure. That means, it can safely be dropped. + +You can use either a `@` sign at the start, or a `#`. + +Here are some examples on how to use them: + +```javascript +/*@__INLINE__*/ +function_always_inlined_here() + +/*#__NOINLINE__*/ +function_cant_be_inlined_into_here() + +const x = /*#__PURE__*/i_am_dropped_if_x_is_not_used() +``` + +### ESTree / SpiderMonkey AST + +Terser has its own abstract syntax tree format; for +[practical reasons](http://lisperator.net/blog/uglifyjs-why-not-switching-to-spidermonkey-ast/) +we can't easily change to using the SpiderMonkey AST internally. However, +Terser now has a converter which can import a SpiderMonkey AST. + +For example [Acorn][acorn] is a super-fast parser that produces a +SpiderMonkey AST. It has a small CLI utility that parses one file and dumps +the AST in JSON on the standard output. To use Terser to mangle and +compress that: + + acorn file.js | terser -p spidermonkey -m -c + +The `-p spidermonkey` option tells Terser that all input files are not +JavaScript, but JS code described in SpiderMonkey AST in JSON. Therefore we +don't use our own parser in this case, but just transform that AST into our +internal AST. + +`spidermonkey` is also available in `minify` as `parse` and `format` options to +accept and/or produce a spidermonkey AST. + +### Use Acorn for parsing + +More for fun, I added the `-p acorn` option which will use Acorn to do all +the parsing. If you pass this option, Terser will `require("acorn")`. + +Acorn is really fast (e.g. 250ms instead of 380ms on some 650K code), but +converting the SpiderMonkey tree that Acorn produces takes another 150ms so +in total it's a bit more than just using Terser's own parser. + +[acorn]: https://github.com/ternjs/acorn +[sm-spec]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k + +### Terser Fast Minify Mode + +It's not well known, but whitespace removal and symbol mangling accounts +for 95% of the size reduction in minified code for most JavaScript - not +elaborate code transforms. One can simply disable `compress` to speed up +Terser builds by 3 to 4 times. + +| d3.js | size | gzip size | time (s) | +| --- | ---: | ---: | ---: | +| original | 451,131 | 108,733 | - | +| terser@3.7.5 mangle=false, compress=false | 316,600 | 85,245 | 0.82 | +| terser@3.7.5 mangle=true, compress=false | 220,216 | 72,730 | 1.45 | +| terser@3.7.5 mangle=true, compress=true | 212,046 | 70,954 | 5.87 | +| babili@0.1.4 | 210,713 | 72,140 | 12.64 | +| babel-minify@0.4.3 | 210,321 | 72,242 | 48.67 | +| babel-minify@0.5.0-alpha.01eac1c3 | 210,421 | 72,238 | 14.17 | + +To enable fast minify mode from the CLI use: +``` +terser file.js -m +``` +To enable fast minify mode with the API use: +```js +await minify(code, { compress: false, mangle: true }); +``` + +#### Source maps and debugging + +Various `compress` transforms that simplify, rearrange, inline and remove code +are known to have an adverse effect on debugging with source maps. This is +expected as code is optimized and mappings are often simply not possible as +some code no longer exists. For highest fidelity in source map debugging +disable the `compress` option and just use `mangle`. + +### Compiler assumptions + +To allow for better optimizations, the compiler makes various assumptions: + +- `.toString()` and `.valueOf()` don't have side effects, and for built-in + objects they have not been overridden. +- `undefined`, `NaN` and `Infinity` have not been externally redefined. +- `arguments.callee`, `arguments.caller` and `Function.prototype.caller` are not used. +- The code doesn't expect the contents of `Function.prototype.toString()` or + `Error.prototype.stack` to be anything in particular. +- Getting and setting properties on a plain object does not cause other side effects + (using `.watch()` or `Proxy`). +- Object properties can be added, removed and modified (not prevented with + `Object.defineProperty()`, `Object.defineProperties()`, `Object.freeze()`, + `Object.preventExtensions()` or `Object.seal()`). +- `document.all` is not `== null` +- Assigning properties to a class doesn't have side effects and does not throw. + +### Build Tools and Adaptors using Terser + +https://www.npmjs.com/browse/depended/terser + +### Replacing `uglify-es` with `terser` in a project using `yarn` + +A number of JS bundlers and uglify wrappers are still using buggy versions +of `uglify-es` and have not yet upgraded to `terser`. If you are using `yarn` +you can add the following alias to your project's `package.json` file: + +```js + "resolutions": { + "uglify-es": "npm:terser" + } +``` + +to use `terser` instead of `uglify-es` in all deeply nested dependencies +without changing any code. + +Note: for this change to take effect you must run the following commands +to remove the existing `yarn` lock file and reinstall all packages: + +``` +$ rm -rf node_modules yarn.lock +$ yarn +``` + + + +# Reporting issues + +In the terser CLI we use [source-map-support](https://npmjs.com/source-map-support) to produce good error stacks. In your own app, you're expected to enable source-map-support (read their docs) to have nice stack traces that will help you write good issues. + +## Obtaining the source code given to Terser + +Because users often don't control the call to `await minify()` or its arguments, Terser provides a `TERSER_DEBUG_DIR` environment variable to make terser output some debug logs. If you're using a bundler or a project that includes a bundler and are not sure what went wrong with your code, pass that variable like so: + +``` +$ TERSER_DEBUG_DIR=/path/to/logs command-that-uses-terser +$ ls /path/to/logs +terser-debug-123456.log +``` + +If you're not sure how to set an environment variable on your shell (the above example works in bash), you can try using cross-env: + +``` +> npx cross-env TERSER_DEBUG_DIR=/path/to/logs command-that-uses-terser +``` + +# README.md Patrons: + +*note*: You can support this project on patreon: patron. Check out [PATRONS.md](https://github.com/terser/terser/blob/master/PATRONS.md) for our first-tier patrons. + +These are the second-tier patrons. Great thanks for your support! + + * CKEditor ![](https://c10.patreonusercontent.com/3/eyJoIjoxMDAsInciOjEwMH0%3D/patreon-media/p/user/15452278/f8548dcf48d740619071e8d614459280/1?token-time=2145916800&token-hash=SIQ54PhIPHv3M7CVz9LxS8_8v4sOw4H304HaXsXj8MM%3D) + * 38elements ![](https://c10.patreonusercontent.com/3/eyJ3IjoyMDB9/patreon-media/p/user/12501844/88e7fc5dd62d45c6a5626533bbd48cfb/1?token-time=2145916800&token-hash=c3AsQ5T0IQWic0zKxFHu-bGGQJkXQFvafvJ4bPerFR4%3D) + +## Contributors + +### Code Contributors + +This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. + + +### Financial Contributors + +Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/terser/contribute)] + +#### Individuals + + + +#### Organizations + +Support this project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/terser/contribute)] + + + + + + + + + + + diff --git a/node_modules/mathjs/examples/node_modules/terser/bin/package.json b/node_modules/mathjs/examples/node_modules/terser/bin/package.json new file mode 100644 index 0000000..d937a6f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/bin/package.json @@ -0,0 +1,10 @@ +{ + "name": "bin", + "private": true, + "version": "1.0.0", + "main": "terser", + "type": "commonjs", + "author": "", + "license": "BSD-2-Clause", + "description": "A package to hold the Terser bin bundle as commonjs while keeping the rest of it ESM." +} diff --git a/node_modules/mathjs/examples/node_modules/terser/bin/terser b/node_modules/mathjs/examples/node_modules/terser/bin/terser new file mode 100644 index 0000000..b0cdc7c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/bin/terser @@ -0,0 +1,21 @@ +#!/usr/bin/env node + +"use strict"; + +require("../tools/exit.cjs"); + +try { + require("source-map-support").install(); +} catch (err) {} + +const fs = require("fs"); +const path = require("path"); +const program = require("commander"); + +const packageJson = require("../package.json"); +const { _run_cli: run_cli } = require(".."); + +run_cli({ program, packageJson, fs, path }).catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/node_modules/mathjs/examples/node_modules/terser/bin/uglifyjs b/node_modules/mathjs/examples/node_modules/terser/bin/uglifyjs new file mode 100644 index 0000000..f193025 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/bin/uglifyjs @@ -0,0 +1,10 @@ +#!/usr/bin/env node +// -*- js -*- +/* eslint-env node */ + +"use strict"; + +process.stderr.write( "DEPRECATION WARNING: uglifyjs binary will soon be discontinued!\n"); +process.stderr.write("Please use \"terser\" instead.\n\n"); + +require("./terser"); diff --git a/node_modules/mathjs/examples/node_modules/terser/dist/.gitkeep b/node_modules/mathjs/examples/node_modules/terser/dist/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mathjs/examples/node_modules/terser/dist/bundle.min.js b/node_modules/mathjs/examples/node_modules/terser/dist/bundle.min.js new file mode 100644 index 0000000..b8e48eb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/dist/bundle.min.js @@ -0,0 +1,28332 @@ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('source-map')) : +typeof define === 'function' && define.amd ? define(['exports', 'source-map'], factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Terser = {}, global.sourceMap)); +}(this, (function (exports, MOZ_SourceMap) { 'use strict'; + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var MOZ_SourceMap__default = /*#__PURE__*/_interopDefaultLegacy(MOZ_SourceMap); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +function characters(str) { + return str.split(""); +} + +function member(name, array) { + return array.includes(name); +} + +class DefaultsError extends Error { + constructor(msg, defs) { + super(); + + this.name = "DefaultsError"; + this.message = msg; + this.defs = defs; + } +} + +function defaults(args, defs, croak) { + if (args === true) { + args = {}; + } else if (args != null && typeof args === "object") { + args = {...args}; + } + + const ret = args || {}; + + if (croak) for (const i in ret) if (HOP(ret, i) && !HOP(defs, i)) { + throw new DefaultsError("`" + i + "` is not a supported option", defs); + } + + for (const i in defs) if (HOP(defs, i)) { + if (!args || !HOP(args, i)) { + ret[i] = defs[i]; + } else if (i === "ecma") { + let ecma = args[i] | 0; + if (ecma > 5 && ecma < 2015) ecma += 2009; + ret[i] = ecma; + } else { + ret[i] = (args && HOP(args, i)) ? args[i] : defs[i]; + } + } + + return ret; +} + +function noop() {} +function return_false() { return false; } +function return_true() { return true; } +function return_this() { return this; } +function return_null() { return null; } + +var MAP = (function() { + function MAP(a, f, backwards) { + var ret = [], top = [], i; + function doit() { + var val = f(a[i], i); + var is_last = val instanceof Last; + if (is_last) val = val.v; + if (val instanceof AtTop) { + val = val.v; + if (val instanceof Splice) { + top.push.apply(top, backwards ? val.v.slice().reverse() : val.v); + } else { + top.push(val); + } + } else if (val !== skip) { + if (val instanceof Splice) { + ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v); + } else { + ret.push(val); + } + } + return is_last; + } + if (Array.isArray(a)) { + if (backwards) { + for (i = a.length; --i >= 0;) if (doit()) break; + ret.reverse(); + top.reverse(); + } else { + for (i = 0; i < a.length; ++i) if (doit()) break; + } + } else { + for (i in a) if (HOP(a, i)) if (doit()) break; + } + return top.concat(ret); + } + MAP.at_top = function(val) { return new AtTop(val); }; + MAP.splice = function(val) { return new Splice(val); }; + MAP.last = function(val) { return new Last(val); }; + var skip = MAP.skip = {}; + function AtTop(val) { this.v = val; } + function Splice(val) { this.v = val; } + function Last(val) { this.v = val; } + return MAP; +})(); + +function make_node(ctor, orig, props) { + if (!props) props = {}; + if (orig) { + if (!props.start) props.start = orig.start; + if (!props.end) props.end = orig.end; + } + return new ctor(props); +} + +function push_uniq(array, el) { + if (!array.includes(el)) + array.push(el); +} + +function string_template(text, props) { + return text.replace(/{(.+?)}/g, function(str, p) { + return props && props[p]; + }); +} + +function remove(array, el) { + for (var i = array.length; --i >= 0;) { + if (array[i] === el) array.splice(i, 1); + } +} + +function mergeSort(array, cmp) { + if (array.length < 2) return array.slice(); + function merge(a, b) { + var r = [], ai = 0, bi = 0, i = 0; + while (ai < a.length && bi < b.length) { + cmp(a[ai], b[bi]) <= 0 + ? r[i++] = a[ai++] + : r[i++] = b[bi++]; + } + if (ai < a.length) r.push.apply(r, a.slice(ai)); + if (bi < b.length) r.push.apply(r, b.slice(bi)); + return r; + } + function _ms(a) { + if (a.length <= 1) + return a; + var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m); + left = _ms(left); + right = _ms(right); + return merge(left, right); + } + return _ms(array); +} + +function makePredicate(words) { + if (!Array.isArray(words)) words = words.split(" "); + + return new Set(words.sort()); +} + +function map_add(map, key, value) { + if (map.has(key)) { + map.get(key).push(value); + } else { + map.set(key, [ value ]); + } +} + +function map_from_object(obj) { + var map = new Map(); + for (var key in obj) { + if (HOP(obj, key) && key.charAt(0) === "$") { + map.set(key.substr(1), obj[key]); + } + } + return map; +} + +function map_to_object(map) { + var obj = Object.create(null); + map.forEach(function (value, key) { + obj["$" + key] = value; + }); + return obj; +} + +function HOP(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +function keep_name(keep_setting, name) { + return keep_setting === true + || (keep_setting instanceof RegExp && keep_setting.test(name)); +} + +var lineTerminatorEscape = { + "\0": "0", + "\n": "n", + "\r": "r", + "\u2028": "u2028", + "\u2029": "u2029", +}; +function regexp_source_fix(source) { + // V8 does not escape line terminators in regexp patterns in node 12 + // We'll also remove literal \0 + return source.replace(/[\0\n\r\u2028\u2029]/g, function (match, offset) { + var escaped = source[offset - 1] == "\\" + && (source[offset - 2] != "\\" + || /(?:^|[^\\])(?:\\{2})*$/.test(source.slice(0, offset - 1))); + return (escaped ? "" : "\\") + lineTerminatorEscape[match]; + }); +} +const all_flags = "gimuy"; +function sort_regexp_flags(flags) { + const existing_flags = new Set(flags.split("")); + let out = ""; + for (const flag of all_flags) { + if (existing_flags.has(flag)) { + out += flag; + existing_flags.delete(flag); + } + } + if (existing_flags.size) { + // Flags Terser doesn't know about + existing_flags.forEach(flag => { out += flag; }); + } + return out; +} + +function has_annotation(node, annotation) { + return node._annotations & annotation; +} + +function set_annotation(node, annotation) { + node._annotations |= annotation; +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/). + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +var LATEST_RAW = ""; // Only used for numbers and template strings +var LATEST_TEMPLATE_END = true; + +var KEYWORDS = "break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with"; +var KEYWORDS_ATOM = "false null true"; +var RESERVED_WORDS = "enum import super this " + KEYWORDS_ATOM + " " + KEYWORDS; +var ALL_RESERVED_WORDS = "implements interface package private protected public static " + RESERVED_WORDS; +var KEYWORDS_BEFORE_EXPRESSION = "return new delete throw else case yield await"; + +KEYWORDS = makePredicate(KEYWORDS); +RESERVED_WORDS = makePredicate(RESERVED_WORDS); +KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION); +KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM); +ALL_RESERVED_WORDS = makePredicate(ALL_RESERVED_WORDS); + +var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^")); + +var RE_NUM_LITERAL = /[0-9a-f]/i; +var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; +var RE_OCT_NUMBER = /^0[0-7]+$/; +var RE_ES6_OCT_NUMBER = /^0o[0-7]+$/i; +var RE_BIN_NUMBER = /^0b[01]+$/i; +var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i; +var RE_BIG_INT = /^(0[xob])?[0-9a-f]+n$/i; + +var OPERATORS = makePredicate([ + "in", + "instanceof", + "typeof", + "new", + "void", + "delete", + "++", + "--", + "+", + "-", + "!", + "~", + "&", + "|", + "^", + "*", + "**", + "/", + "%", + ">>", + "<<", + ">>>", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "?", + "=", + "+=", + "-=", + "||=", + "&&=", + "??=", + "/=", + "*=", + "**=", + "%=", + ">>=", + "<<=", + ">>>=", + "|=", + "^=", + "&=", + "&&", + "??", + "||", +]); + +var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\uFEFF")); + +var NEWLINE_CHARS = makePredicate(characters("\n\r\u2028\u2029")); + +var PUNC_AFTER_EXPRESSION = makePredicate(characters(";]),:")); + +var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,;:")); + +var PUNC_CHARS = makePredicate(characters("[]{}(),;:")); + +/* -----[ Tokenizer ]----- */ + +// surrogate safe regexps adapted from https://github.com/mathiasbynens/unicode-8.0.0/tree/89b412d8a71ecca9ed593d9e9fa073ab64acfebe/Binary_Property +var UNICODE = { + ID_Start: /[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + ID_Continue: /(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF])+/, +}; + +function get_full_char(str, pos) { + if (is_surrogate_pair_head(str.charCodeAt(pos))) { + if (is_surrogate_pair_tail(str.charCodeAt(pos + 1))) { + return str.charAt(pos) + str.charAt(pos + 1); + } + } else if (is_surrogate_pair_tail(str.charCodeAt(pos))) { + if (is_surrogate_pair_head(str.charCodeAt(pos - 1))) { + return str.charAt(pos - 1) + str.charAt(pos); + } + } + return str.charAt(pos); +} + +function get_full_char_code(str, pos) { + // https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates + if (is_surrogate_pair_head(str.charCodeAt(pos))) { + return 0x10000 + (str.charCodeAt(pos) - 0xd800 << 10) + str.charCodeAt(pos + 1) - 0xdc00; + } + return str.charCodeAt(pos); +} + +function get_full_char_length(str) { + var surrogates = 0; + + for (var i = 0; i < str.length; i++) { + if (is_surrogate_pair_head(str.charCodeAt(i)) && is_surrogate_pair_tail(str.charCodeAt(i + 1))) { + surrogates++; + i++; + } + } + + return str.length - surrogates; +} + +function from_char_code(code) { + // Based on https://github.com/mathiasbynens/String.fromCodePoint/blob/master/fromcodepoint.js + if (code > 0xFFFF) { + code -= 0x10000; + return (String.fromCharCode((code >> 10) + 0xD800) + + String.fromCharCode((code % 0x400) + 0xDC00)); + } + return String.fromCharCode(code); +} + +function is_surrogate_pair_head(code) { + return code >= 0xd800 && code <= 0xdbff; +} + +function is_surrogate_pair_tail(code) { + return code >= 0xdc00 && code <= 0xdfff; +} + +function is_digit(code) { + return code >= 48 && code <= 57; +} + +function is_identifier_start(ch) { + return UNICODE.ID_Start.test(ch); +} + +function is_identifier_char(ch) { + return UNICODE.ID_Continue.test(ch); +} + +const BASIC_IDENT = /^[a-z_$][a-z0-9_$]*$/i; + +function is_basic_identifier_string(str) { + return BASIC_IDENT.test(str); +} + +function is_identifier_string(str, allow_surrogates) { + if (BASIC_IDENT.test(str)) { + return true; + } + if (!allow_surrogates && /[\ud800-\udfff]/.test(str)) { + return false; + } + var match = UNICODE.ID_Start.exec(str); + if (!match || match.index !== 0) { + return false; + } + + str = str.slice(match[0].length); + if (!str) { + return true; + } + + match = UNICODE.ID_Continue.exec(str); + return !!match && match[0].length === str.length; +} + +function parse_js_number(num, allow_e = true) { + if (!allow_e && num.includes("e")) { + return NaN; + } + if (RE_HEX_NUMBER.test(num)) { + return parseInt(num.substr(2), 16); + } else if (RE_OCT_NUMBER.test(num)) { + return parseInt(num.substr(1), 8); + } else if (RE_ES6_OCT_NUMBER.test(num)) { + return parseInt(num.substr(2), 8); + } else if (RE_BIN_NUMBER.test(num)) { + return parseInt(num.substr(2), 2); + } else if (RE_DEC_NUMBER.test(num)) { + return parseFloat(num); + } else { + var val = parseFloat(num); + if (val == num) return val; + } +} + +class JS_Parse_Error extends Error { + constructor(message, filename, line, col, pos) { + super(); + + this.name = "SyntaxError"; + this.message = message; + this.filename = filename; + this.line = line; + this.col = col; + this.pos = pos; + } +} + +function js_error(message, filename, line, col, pos) { + throw new JS_Parse_Error(message, filename, line, col, pos); +} + +function is_token(token, type, val) { + return token.type == type && (val == null || token.value == val); +} + +var EX_EOF = {}; + +function tokenizer($TEXT, filename, html5_comments, shebang) { + var S = { + text : $TEXT, + filename : filename, + pos : 0, + tokpos : 0, + line : 1, + tokline : 0, + col : 0, + tokcol : 0, + newline_before : false, + regex_allowed : false, + brace_counter : 0, + template_braces : [], + comments_before : [], + directives : {}, + directive_stack : [] + }; + + function peek() { return get_full_char(S.text, S.pos); } + + // Used because parsing ?. involves a lookahead for a digit + function is_option_chain_op() { + const must_be_dot = S.text.charCodeAt(S.pos + 1) === 46; + if (!must_be_dot) return false; + + const cannot_be_digit = S.text.charCodeAt(S.pos + 2); + return cannot_be_digit < 48 || cannot_be_digit > 57; + } + + function next(signal_eof, in_string) { + var ch = get_full_char(S.text, S.pos++); + if (signal_eof && !ch) + throw EX_EOF; + if (NEWLINE_CHARS.has(ch)) { + S.newline_before = S.newline_before || !in_string; + ++S.line; + S.col = 0; + if (ch == "\r" && peek() == "\n") { + // treat a \r\n sequence as a single \n + ++S.pos; + ch = "\n"; + } + } else { + if (ch.length > 1) { + ++S.pos; + ++S.col; + } + ++S.col; + } + return ch; + } + + function forward(i) { + while (i--) next(); + } + + function looking_at(str) { + return S.text.substr(S.pos, str.length) == str; + } + + function find_eol() { + var text = S.text; + for (var i = S.pos, n = S.text.length; i < n; ++i) { + var ch = text[i]; + if (NEWLINE_CHARS.has(ch)) + return i; + } + return -1; + } + + function find(what, signal_eof) { + var pos = S.text.indexOf(what, S.pos); + if (signal_eof && pos == -1) throw EX_EOF; + return pos; + } + + function start_token() { + S.tokline = S.line; + S.tokcol = S.col; + S.tokpos = S.pos; + } + + var prev_was_dot = false; + var previous_token = null; + function token(type, value, is_comment) { + S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX.has(value)) || + (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION.has(value)) || + (type == "punc" && PUNC_BEFORE_EXPRESSION.has(value))) || + (type == "arrow"); + if (type == "punc" && (value == "." || value == "?.")) { + prev_was_dot = true; + } else if (!is_comment) { + prev_was_dot = false; + } + const line = S.tokline; + const col = S.tokcol; + const pos = S.tokpos; + const nlb = S.newline_before; + const file = filename; + let comments_before = []; + let comments_after = []; + + if (!is_comment) { + comments_before = S.comments_before; + comments_after = S.comments_before = []; + } + S.newline_before = false; + const tok = new AST_Token(type, value, line, col, pos, nlb, comments_before, comments_after, file); + + if (!is_comment) previous_token = tok; + return tok; + } + + function skip_whitespace() { + while (WHITESPACE_CHARS.has(peek())) + next(); + } + + function read_while(pred) { + var ret = "", ch, i = 0; + while ((ch = peek()) && pred(ch, i++)) + ret += next(); + return ret; + } + + function parse_error(err) { + js_error(err, filename, S.tokline, S.tokcol, S.tokpos); + } + + function read_num(prefix) { + var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".", is_big_int = false, numeric_separator = false; + var num = read_while(function(ch, i) { + if (is_big_int) return false; + + var code = ch.charCodeAt(0); + switch (code) { + case 95: // _ + return (numeric_separator = true); + case 98: case 66: // bB + return (has_x = true); // Can occur in hex sequence, don't return false yet + case 111: case 79: // oO + case 120: case 88: // xX + return has_x ? false : (has_x = true); + case 101: case 69: // eE + return has_x ? true : has_e ? false : (has_e = after_e = true); + case 45: // - + return after_e || (i == 0 && !prefix); + case 43: // + + return after_e; + case (after_e = false, 46): // . + return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false; + } + + if (ch === "n") { + is_big_int = true; + + return true; + } + + return RE_NUM_LITERAL.test(ch); + }); + if (prefix) num = prefix + num; + + LATEST_RAW = num; + + if (RE_OCT_NUMBER.test(num) && next_token.has_directive("use strict")) { + parse_error("Legacy octal literals are not allowed in strict mode"); + } + if (numeric_separator) { + if (num.endsWith("_")) { + parse_error("Numeric separators are not allowed at the end of numeric literals"); + } else if (num.includes("__")) { + parse_error("Only one underscore is allowed as numeric separator"); + } + num = num.replace(/_/g, ""); + } + if (num.endsWith("n")) { + const without_n = num.slice(0, -1); + const allow_e = RE_HEX_NUMBER.test(without_n); + const valid = parse_js_number(without_n, allow_e); + if (!has_dot && RE_BIG_INT.test(num) && !isNaN(valid)) + return token("big_int", without_n); + parse_error("Invalid or unexpected token"); + } + var valid = parse_js_number(num); + if (!isNaN(valid)) { + return token("num", valid); + } else { + parse_error("Invalid syntax: " + num); + } + } + + function is_octal(ch) { + return ch >= "0" && ch <= "7"; + } + + function read_escaped_char(in_string, strict_hex, template_string) { + var ch = next(true, in_string); + switch (ch.charCodeAt(0)) { + case 110 : return "\n"; + case 114 : return "\r"; + case 116 : return "\t"; + case 98 : return "\b"; + case 118 : return "\u000b"; // \v + case 102 : return "\f"; + case 120 : return String.fromCharCode(hex_bytes(2, strict_hex)); // \x + case 117 : // \u + if (peek() == "{") { + next(true); + if (peek() === "}") + parse_error("Expecting hex-character between {}"); + while (peek() == "0") next(true); // No significance + var result, length = find("}", true) - S.pos; + // Avoid 32 bit integer overflow (1 << 32 === 1) + // We know first character isn't 0 and thus out of range anyway + if (length > 6 || (result = hex_bytes(length, strict_hex)) > 0x10FFFF) { + parse_error("Unicode reference out of bounds"); + } + next(true); + return from_char_code(result); + } + return String.fromCharCode(hex_bytes(4, strict_hex)); + case 10 : return ""; // newline + case 13 : // \r + if (peek() == "\n") { // DOS newline + next(true, in_string); + return ""; + } + } + if (is_octal(ch)) { + if (template_string && strict_hex) { + const represents_null_character = ch === "0" && !is_octal(peek()); + if (!represents_null_character) { + parse_error("Octal escape sequences are not allowed in template strings"); + } + } + return read_octal_escape_sequence(ch, strict_hex); + } + return ch; + } + + function read_octal_escape_sequence(ch, strict_octal) { + // Read + var p = peek(); + if (p >= "0" && p <= "7") { + ch += next(true); + if (ch[0] <= "3" && (p = peek()) >= "0" && p <= "7") + ch += next(true); + } + + // Parse + if (ch === "0") return "\0"; + if (ch.length > 0 && next_token.has_directive("use strict") && strict_octal) + parse_error("Legacy octal escape sequences are not allowed in strict mode"); + return String.fromCharCode(parseInt(ch, 8)); + } + + function hex_bytes(n, strict_hex) { + var num = 0; + for (; n > 0; --n) { + if (!strict_hex && isNaN(parseInt(peek(), 16))) { + return parseInt(num, 16) || ""; + } + var digit = next(true); + if (isNaN(parseInt(digit, 16))) + parse_error("Invalid hex-character pattern in string"); + num += digit; + } + return parseInt(num, 16); + } + + var read_string = with_eof_error("Unterminated string constant", function() { + const start_pos = S.pos; + var quote = next(), ret = []; + for (;;) { + var ch = next(true, true); + if (ch == "\\") ch = read_escaped_char(true, true); + else if (ch == "\r" || ch == "\n") parse_error("Unterminated string constant"); + else if (ch == quote) break; + ret.push(ch); + } + var tok = token("string", ret.join("")); + LATEST_RAW = S.text.slice(start_pos, S.pos); + tok.quote = quote; + return tok; + }); + + var read_template_characters = with_eof_error("Unterminated template", function(begin) { + if (begin) { + S.template_braces.push(S.brace_counter); + } + var content = "", raw = "", ch, tok; + next(true, true); + while ((ch = next(true, true)) != "`") { + if (ch == "\r") { + if (peek() == "\n") ++S.pos; + ch = "\n"; + } else if (ch == "$" && peek() == "{") { + next(true, true); + S.brace_counter++; + tok = token(begin ? "template_head" : "template_substitution", content); + LATEST_RAW = raw; + LATEST_TEMPLATE_END = false; + return tok; + } + + raw += ch; + if (ch == "\\") { + var tmp = S.pos; + var prev_is_tag = previous_token && (previous_token.type === "name" || previous_token.type === "punc" && (previous_token.value === ")" || previous_token.value === "]")); + ch = read_escaped_char(true, !prev_is_tag, true); + raw += S.text.substr(tmp, S.pos - tmp); + } + + content += ch; + } + S.template_braces.pop(); + tok = token(begin ? "template_head" : "template_substitution", content); + LATEST_RAW = raw; + LATEST_TEMPLATE_END = true; + return tok; + }); + + function skip_line_comment(type) { + var regex_allowed = S.regex_allowed; + var i = find_eol(), ret; + if (i == -1) { + ret = S.text.substr(S.pos); + S.pos = S.text.length; + } else { + ret = S.text.substring(S.pos, i); + S.pos = i; + } + S.col = S.tokcol + (S.pos - S.tokpos); + S.comments_before.push(token(type, ret, true)); + S.regex_allowed = regex_allowed; + return next_token; + } + + var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function() { + var regex_allowed = S.regex_allowed; + var i = find("*/", true); + var text = S.text.substring(S.pos, i).replace(/\r\n|\r|\u2028|\u2029/g, "\n"); + // update stream position + forward(get_full_char_length(text) /* text length doesn't count \r\n as 2 char while S.pos - i does */ + 2); + S.comments_before.push(token("comment2", text, true)); + S.newline_before = S.newline_before || text.includes("\n"); + S.regex_allowed = regex_allowed; + return next_token; + }); + + var read_name = with_eof_error("Unterminated identifier name", function() { + var name = [], ch, escaped = false; + var read_escaped_identifier_char = function() { + escaped = true; + next(); + if (peek() !== "u") { + parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}"); + } + return read_escaped_char(false, true); + }; + + // Read first character (ID_Start) + if ((ch = peek()) === "\\") { + ch = read_escaped_identifier_char(); + if (!is_identifier_start(ch)) { + parse_error("First identifier char is an invalid identifier char"); + } + } else if (is_identifier_start(ch)) { + next(); + } else { + return ""; + } + + name.push(ch); + + // Read ID_Continue + while ((ch = peek()) != null) { + if ((ch = peek()) === "\\") { + ch = read_escaped_identifier_char(); + if (!is_identifier_char(ch)) { + parse_error("Invalid escaped identifier char"); + } + } else { + if (!is_identifier_char(ch)) { + break; + } + next(); + } + name.push(ch); + } + const name_str = name.join(""); + if (RESERVED_WORDS.has(name_str) && escaped) { + parse_error("Escaped characters are not allowed in keywords"); + } + return name_str; + }); + + var read_regexp = with_eof_error("Unterminated regular expression", function(source) { + var prev_backslash = false, ch, in_class = false; + while ((ch = next(true))) if (NEWLINE_CHARS.has(ch)) { + parse_error("Unexpected line terminator"); + } else if (prev_backslash) { + source += "\\" + ch; + prev_backslash = false; + } else if (ch == "[") { + in_class = true; + source += ch; + } else if (ch == "]" && in_class) { + in_class = false; + source += ch; + } else if (ch == "/" && !in_class) { + break; + } else if (ch == "\\") { + prev_backslash = true; + } else { + source += ch; + } + const flags = read_name(); + return token("regexp", "/" + source + "/" + flags); + }); + + function read_operator(prefix) { + function grow(op) { + if (!peek()) return op; + var bigger = op + peek(); + if (OPERATORS.has(bigger)) { + next(); + return grow(bigger); + } else { + return op; + } + } + return token("operator", grow(prefix || next())); + } + + function handle_slash() { + next(); + switch (peek()) { + case "/": + next(); + return skip_line_comment("comment1"); + case "*": + next(); + return skip_multiline_comment(); + } + return S.regex_allowed ? read_regexp("") : read_operator("/"); + } + + function handle_eq_sign() { + next(); + if (peek() === ">") { + next(); + return token("arrow", "=>"); + } else { + return read_operator("="); + } + } + + function handle_dot() { + next(); + if (is_digit(peek().charCodeAt(0))) { + return read_num("."); + } + if (peek() === ".") { + next(); // Consume second dot + next(); // Consume third dot + return token("expand", "..."); + } + + return token("punc", "."); + } + + function read_word() { + var word = read_name(); + if (prev_was_dot) return token("name", word); + return KEYWORDS_ATOM.has(word) ? token("atom", word) + : !KEYWORDS.has(word) ? token("name", word) + : OPERATORS.has(word) ? token("operator", word) + : token("keyword", word); + } + + function read_private_word() { + next(); + return token("privatename", read_name()); + } + + function with_eof_error(eof_error, cont) { + return function(x) { + try { + return cont(x); + } catch(ex) { + if (ex === EX_EOF) parse_error(eof_error); + else throw ex; + } + }; + } + + function next_token(force_regexp) { + if (force_regexp != null) + return read_regexp(force_regexp); + if (shebang && S.pos == 0 && looking_at("#!")) { + start_token(); + forward(2); + skip_line_comment("comment5"); + } + for (;;) { + skip_whitespace(); + start_token(); + if (html5_comments) { + if (looking_at("") && S.newline_before) { + forward(3); + skip_line_comment("comment4"); + continue; + } + } + var ch = peek(); + if (!ch) return token("eof"); + var code = ch.charCodeAt(0); + switch (code) { + case 34: case 39: return read_string(); + case 46: return handle_dot(); + case 47: { + var tok = handle_slash(); + if (tok === next_token) continue; + return tok; + } + case 61: return handle_eq_sign(); + case 63: { + if (!is_option_chain_op()) break; // Handled below + + next(); // ? + next(); // . + + return token("punc", "?."); + } + case 96: return read_template_characters(true); + case 123: + S.brace_counter++; + break; + case 125: + S.brace_counter--; + if (S.template_braces.length > 0 + && S.template_braces[S.template_braces.length - 1] === S.brace_counter) + return read_template_characters(false); + break; + } + if (is_digit(code)) return read_num(); + if (PUNC_CHARS.has(ch)) return token("punc", next()); + if (OPERATOR_CHARS.has(ch)) return read_operator(); + if (code == 92 || is_identifier_start(ch)) return read_word(); + if (code == 35) return read_private_word(); + break; + } + parse_error("Unexpected character '" + ch + "'"); + } + + next_token.next = next; + next_token.peek = peek; + + next_token.context = function(nc) { + if (nc) S = nc; + return S; + }; + + next_token.add_directive = function(directive) { + S.directive_stack[S.directive_stack.length - 1].push(directive); + + if (S.directives[directive] === undefined) { + S.directives[directive] = 1; + } else { + S.directives[directive]++; + } + }; + + next_token.push_directives_stack = function() { + S.directive_stack.push([]); + }; + + next_token.pop_directives_stack = function() { + var directives = S.directive_stack[S.directive_stack.length - 1]; + + for (var i = 0; i < directives.length; i++) { + S.directives[directives[i]]--; + } + + S.directive_stack.pop(); + }; + + next_token.has_directive = function(directive) { + return S.directives[directive] > 0; + }; + + return next_token; + +} + +/* -----[ Parser (constants) ]----- */ + +var UNARY_PREFIX = makePredicate([ + "typeof", + "void", + "delete", + "--", + "++", + "!", + "~", + "-", + "+" +]); + +var UNARY_POSTFIX = makePredicate([ "--", "++" ]); + +var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "??=", "&&=", "||=", "/=", "*=", "**=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); + +var LOGICAL_ASSIGNMENT = makePredicate([ "??=", "&&=", "||=" ]); + +var PRECEDENCE = (function(a, ret) { + for (var i = 0; i < a.length; ++i) { + var b = a[i]; + for (var j = 0; j < b.length; ++j) { + ret[b[j]] = i + 1; + } + } + return ret; +})( + [ + ["||"], + ["??"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"], + ["**"] + ], + {} +); + +var ATOMIC_START_TOKEN = makePredicate([ "atom", "num", "big_int", "string", "regexp", "name" ]); + +/* -----[ Parser ]----- */ + +function parse($TEXT, options) { + // maps start tokens to count of comments found outside of their parens + // Example: /* I count */ ( /* I don't */ foo() ) + // Useful because comments_before property of call with parens outside + // contains both comments inside and outside these parens. Used to find the + + const outer_comments_before_counts = new WeakMap(); + + options = defaults(options, { + bare_returns : false, + ecma : null, // Legacy + expression : false, + filename : null, + html5_comments : true, + module : false, + shebang : true, + strict : false, + toplevel : null, + }, true); + + var S = { + input : (typeof $TEXT == "string" + ? tokenizer($TEXT, options.filename, + options.html5_comments, options.shebang) + : $TEXT), + token : null, + prev : null, + peeked : null, + in_function : 0, + in_async : -1, + in_generator : -1, + in_directives : true, + in_loop : 0, + labels : [] + }; + + S.token = next(); + + function is(type, value) { + return is_token(S.token, type, value); + } + + function peek() { return S.peeked || (S.peeked = S.input()); } + + function next() { + S.prev = S.token; + + if (!S.peeked) peek(); + S.token = S.peeked; + S.peeked = null; + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + } + + function prev() { + return S.prev; + } + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + ctx.filename, + line != null ? line : ctx.tokline, + col != null ? col : ctx.tokcol, + pos != null ? pos : ctx.tokpos); + } + + function token_error(token, msg) { + croak(msg, token.line, token.col); + } + + function unexpected(token) { + if (token == null) + token = S.token; + token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); + } + + function expect_token(type, val) { + if (is(type, val)) { + return next(); + } + token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); + } + + function expect(punc) { return expect_token("punc", punc); } + + function has_newline_before(token) { + return token.nlb || !token.comments_before.every((comment) => !comment.nlb); + } + + function can_insert_semicolon() { + return !options.strict + && (is("eof") || is("punc", "}") || has_newline_before(S.token)); + } + + function is_in_generator() { + return S.in_generator === S.in_function; + } + + function is_in_async() { + return S.in_async === S.in_function; + } + + function can_await() { + return ( + S.in_async === S.in_function + || S.in_function === 0 && S.input.has_directive("use strict") + ); + } + + function semicolon(optional) { + if (is("punc", ";")) next(); + else if (!optional && !can_insert_semicolon()) unexpected(); + } + + function parenthesised() { + expect("("); + var exp = expression(true); + expect(")"); + return exp; + } + + function embed_tokens(parser) { + return function _embed_tokens_wrapper(...args) { + const start = S.token; + const expr = parser(...args); + expr.start = start; + expr.end = prev(); + return expr; + }; + } + + function handle_regexp() { + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + } + + var statement = embed_tokens(function statement(is_export_default, is_for_body, is_if_body) { + handle_regexp(); + switch (S.token.type) { + case "string": + if (S.in_directives) { + var token = peek(); + if (!LATEST_RAW.includes("\\") + && (is_token(token, "punc", ";") + || is_token(token, "punc", "}") + || has_newline_before(token) + || is_token(token, "eof"))) { + S.input.add_directive(S.token.value); + } else { + S.in_directives = false; + } + } + var dir = S.in_directives, stat = simple_statement(); + return dir && stat.body instanceof AST_String ? new AST_Directive(stat.body) : stat; + case "template_head": + case "num": + case "big_int": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + if (S.token.value == "async" && is_token(peek(), "keyword", "function")) { + next(); + next(); + if (is_for_body) { + croak("functions are not allowed as the body of a loop"); + } + return function_(AST_Defun, false, true, is_export_default); + } + if (S.token.value == "import" && !is_token(peek(), "punc", "(") && !is_token(peek(), "punc", ".")) { + next(); + var node = import_statement(); + semicolon(); + return node; + } + return is_token(peek(), "punc", ":") + ? labeled_statement() + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return new AST_BlockStatement({ + start : S.token, + body : block_(), + end : prev() + }); + case "[": + case "(": + return simple_statement(); + case ";": + S.in_directives = false; + next(); + return new AST_EmptyStatement(); + default: + unexpected(); + } + + case "keyword": + switch (S.token.value) { + case "break": + next(); + return break_cont(AST_Break); + + case "continue": + next(); + return break_cont(AST_Continue); + + case "debugger": + next(); + semicolon(); + return new AST_Debugger(); + + case "do": + next(); + var body = in_loop(statement); + expect_token("keyword", "while"); + var condition = parenthesised(); + semicolon(true); + return new AST_Do({ + body : body, + condition : condition + }); + + case "while": + next(); + return new AST_While({ + condition : parenthesised(), + body : in_loop(function() { return statement(false, true); }) + }); + + case "for": + next(); + return for_(); + + case "class": + next(); + if (is_for_body) { + croak("classes are not allowed as the body of a loop"); + } + if (is_if_body) { + croak("classes are not allowed as the body of an if"); + } + return class_(AST_DefClass, is_export_default); + + case "function": + next(); + if (is_for_body) { + croak("functions are not allowed as the body of a loop"); + } + return function_(AST_Defun, false, false, is_export_default); + + case "if": + next(); + return if_(); + + case "return": + if (S.in_function == 0 && !options.bare_returns) + croak("'return' outside of function"); + next(); + var value = null; + if (is("punc", ";")) { + next(); + } else if (!can_insert_semicolon()) { + value = expression(true); + semicolon(); + } + return new AST_Return({ + value: value + }); + + case "switch": + next(); + return new AST_Switch({ + expression : parenthesised(), + body : in_loop(switch_body_) + }); + + case "throw": + next(); + if (has_newline_before(S.token)) + croak("Illegal newline after 'throw'"); + var value = expression(true); + semicolon(); + return new AST_Throw({ + value: value + }); + + case "try": + next(); + return try_(); + + case "var": + next(); + var node = var_(); + semicolon(); + return node; + + case "let": + next(); + var node = let_(); + semicolon(); + return node; + + case "const": + next(); + var node = const_(); + semicolon(); + return node; + + case "with": + if (S.input.has_directive("use strict")) { + croak("Strict mode may not include a with statement"); + } + next(); + return new AST_With({ + expression : parenthesised(), + body : statement() + }); + + case "export": + if (!is_token(peek(), "punc", "(")) { + next(); + var node = export_statement(); + if (is("punc", ";")) semicolon(); + return node; + } + } + } + unexpected(); + }); + + function labeled_statement() { + var label = as_symbol(AST_Label); + if (label.name === "await" && is_in_async()) { + token_error(S.prev, "await cannot be used as label inside async function"); + } + if (S.labels.some((l) => l.name === label.name)) { + // ECMA-262, 12.12: An ECMAScript program is considered + // syntactically incorrect if it contains a + // LabelledStatement that is enclosed by a + // LabelledStatement with the same Identifier as label. + croak("Label " + label.name + " defined twice"); + } + expect(":"); + S.labels.push(label); + var stat = statement(); + S.labels.pop(); + if (!(stat instanceof AST_IterationStatement)) { + // check for `continue` that refers to this label. + // those should be reported as syntax errors. + // https://github.com/mishoo/UglifyJS2/issues/287 + label.references.forEach(function(ref) { + if (ref instanceof AST_Continue) { + ref = ref.label.start; + croak("Continue label `" + label.name + "` refers to non-IterationStatement.", + ref.line, ref.col, ref.pos); + } + }); + } + return new AST_LabeledStatement({ body: stat, label: label }); + } + + function simple_statement(tmp) { + return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); + } + + function break_cont(type) { + var label = null, ldef; + if (!can_insert_semicolon()) { + label = as_symbol(AST_LabelRef, true); + } + if (label != null) { + ldef = S.labels.find((l) => l.name === label.name); + if (!ldef) + croak("Undefined label " + label.name); + label.thedef = ldef; + } else if (S.in_loop == 0) + croak(type.TYPE + " not inside a loop or switch"); + semicolon(); + var stat = new type({ label: label }); + if (ldef) ldef.references.push(stat); + return stat; + } + + function for_() { + var for_await_error = "`for await` invalid in this context"; + var await_tok = S.token; + if (await_tok.type == "name" && await_tok.value == "await") { + if (!can_await()) { + token_error(await_tok, for_await_error); + } + next(); + } else { + await_tok = false; + } + expect("("); + var init = null; + if (!is("punc", ";")) { + init = + is("keyword", "var") ? (next(), var_(true)) : + is("keyword", "let") ? (next(), let_(true)) : + is("keyword", "const") ? (next(), const_(true)) : + expression(true, true); + var is_in = is("operator", "in"); + var is_of = is("name", "of"); + if (await_tok && !is_of) { + token_error(await_tok, for_await_error); + } + if (is_in || is_of) { + if (init instanceof AST_Definitions) { + if (init.definitions.length > 1) + token_error(init.start, "Only one variable declaration allowed in for..in loop"); + } else if (!(is_assignable(init) || (init = to_destructuring(init)) instanceof AST_Destructuring)) { + token_error(init.start, "Invalid left-hand side in for..in loop"); + } + next(); + if (is_in) { + return for_in(init); + } else { + return for_of(init, !!await_tok); + } + } + } else if (await_tok) { + token_error(await_tok, for_await_error); + } + return regular_for(init); + } + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(true); + expect(";"); + var step = is("punc", ")") ? null : expression(true); + expect(")"); + return new AST_For({ + init : init, + condition : test, + step : step, + body : in_loop(function() { return statement(false, true); }) + }); + } + + function for_of(init, is_await) { + var lhs = init instanceof AST_Definitions ? init.definitions[0].name : null; + var obj = expression(true); + expect(")"); + return new AST_ForOf({ + await : is_await, + init : init, + name : lhs, + object : obj, + body : in_loop(function() { return statement(false, true); }) + }); + } + + function for_in(init) { + var obj = expression(true); + expect(")"); + return new AST_ForIn({ + init : init, + object : obj, + body : in_loop(function() { return statement(false, true); }) + }); + } + + var arrow_function = function(start, argnames, is_async) { + if (has_newline_before(S.token)) { + croak("Unexpected newline before arrow (=>)"); + } + + expect_token("arrow", "=>"); + + var body = _function_body(is("punc", "{"), false, is_async); + + var end = + body instanceof Array && body.length ? body[body.length - 1].end : + body instanceof Array ? start : + body.end; + + return new AST_Arrow({ + start : start, + end : end, + async : is_async, + argnames : argnames, + body : body + }); + }; + + var function_ = function(ctor, is_generator_property, is_async, is_export_default) { + var in_statement = ctor === AST_Defun; + var is_generator = is("operator", "*"); + if (is_generator) { + next(); + } + + var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null; + if (in_statement && !name) { + if (is_export_default) { + ctor = AST_Function; + } else { + unexpected(); + } + } + + if (name && ctor !== AST_Accessor && !(name instanceof AST_SymbolDeclaration)) + unexpected(prev()); + + var args = []; + var body = _function_body(true, is_generator || is_generator_property, is_async, name, args); + return new ctor({ + start : args.start, + end : body.end, + is_generator: is_generator, + async : is_async, + name : name, + argnames: args, + body : body + }); + }; + + function track_used_binding_identifiers(is_parameter, strict) { + var parameters = new Set(); + var duplicate = false; + var default_assignment = false; + var spread = false; + var strict_mode = !!strict; + var tracker = { + add_parameter: function(token) { + if (parameters.has(token.value)) { + if (duplicate === false) { + duplicate = token; + } + tracker.check_strict(); + } else { + parameters.add(token.value); + if (is_parameter) { + switch (token.value) { + case "arguments": + case "eval": + case "yield": + if (strict_mode) { + token_error(token, "Unexpected " + token.value + " identifier as parameter inside strict mode"); + } + break; + default: + if (RESERVED_WORDS.has(token.value)) { + unexpected(); + } + } + } + } + }, + mark_default_assignment: function(token) { + if (default_assignment === false) { + default_assignment = token; + } + }, + mark_spread: function(token) { + if (spread === false) { + spread = token; + } + }, + mark_strict_mode: function() { + strict_mode = true; + }, + is_strict: function() { + return default_assignment !== false || spread !== false || strict_mode; + }, + check_strict: function() { + if (tracker.is_strict() && duplicate !== false) { + token_error(duplicate, "Parameter " + duplicate.value + " was used already"); + } + } + }; + + return tracker; + } + + function parameters(params) { + var used_parameters = track_used_binding_identifiers(true, S.input.has_directive("use strict")); + + expect("("); + + while (!is("punc", ")")) { + var param = parameter(used_parameters); + params.push(param); + + if (!is("punc", ")")) { + expect(","); + } + + if (param instanceof AST_Expansion) { + break; + } + } + + next(); + } + + function parameter(used_parameters, symbol_type) { + var param; + var expand = false; + if (used_parameters === undefined) { + used_parameters = track_used_binding_identifiers(true, S.input.has_directive("use strict")); + } + if (is("expand", "...")) { + expand = S.token; + used_parameters.mark_spread(S.token); + next(); + } + param = binding_element(used_parameters, symbol_type); + + if (is("operator", "=") && expand === false) { + used_parameters.mark_default_assignment(S.token); + next(); + param = new AST_DefaultAssign({ + start: param.start, + left: param, + operator: "=", + right: expression(false), + end: S.token + }); + } + + if (expand !== false) { + if (!is("punc", ")")) { + unexpected(); + } + param = new AST_Expansion({ + start: expand, + expression: param, + end: expand + }); + } + used_parameters.check_strict(); + + return param; + } + + function binding_element(used_parameters, symbol_type) { + var elements = []; + var first = true; + var is_expand = false; + var expand_token; + var first_token = S.token; + if (used_parameters === undefined) { + used_parameters = track_used_binding_identifiers(false, S.input.has_directive("use strict")); + } + symbol_type = symbol_type === undefined ? AST_SymbolFunarg : symbol_type; + if (is("punc", "[")) { + next(); + while (!is("punc", "]")) { + if (first) { + first = false; + } else { + expect(","); + } + + if (is("expand", "...")) { + is_expand = true; + expand_token = S.token; + used_parameters.mark_spread(S.token); + next(); + } + if (is("punc")) { + switch (S.token.value) { + case ",": + elements.push(new AST_Hole({ + start: S.token, + end: S.token + })); + continue; + case "]": // Trailing comma after last element + break; + case "[": + case "{": + elements.push(binding_element(used_parameters, symbol_type)); + break; + default: + unexpected(); + } + } else if (is("name")) { + used_parameters.add_parameter(S.token); + elements.push(as_symbol(symbol_type)); + } else { + croak("Invalid function parameter"); + } + if (is("operator", "=") && is_expand === false) { + used_parameters.mark_default_assignment(S.token); + next(); + elements[elements.length - 1] = new AST_DefaultAssign({ + start: elements[elements.length - 1].start, + left: elements[elements.length - 1], + operator: "=", + right: expression(false), + end: S.token + }); + } + if (is_expand) { + if (!is("punc", "]")) { + croak("Rest element must be last element"); + } + elements[elements.length - 1] = new AST_Expansion({ + start: expand_token, + expression: elements[elements.length - 1], + end: expand_token + }); + } + } + expect("]"); + used_parameters.check_strict(); + return new AST_Destructuring({ + start: first_token, + names: elements, + is_array: true, + end: prev() + }); + } else if (is("punc", "{")) { + next(); + while (!is("punc", "}")) { + if (first) { + first = false; + } else { + expect(","); + } + if (is("expand", "...")) { + is_expand = true; + expand_token = S.token; + used_parameters.mark_spread(S.token); + next(); + } + if (is("name") && (is_token(peek(), "punc") || is_token(peek(), "operator")) && [",", "}", "="].includes(peek().value)) { + used_parameters.add_parameter(S.token); + var start = prev(); + var value = as_symbol(symbol_type); + if (is_expand) { + elements.push(new AST_Expansion({ + start: expand_token, + expression: value, + end: value.end, + })); + } else { + elements.push(new AST_ObjectKeyVal({ + start: start, + key: value.name, + value: value, + end: value.end, + })); + } + } else if (is("punc", "}")) { + continue; // Allow trailing hole + } else { + var property_token = S.token; + var property = as_property_name(); + if (property === null) { + unexpected(prev()); + } else if (prev().type === "name" && !is("punc", ":")) { + elements.push(new AST_ObjectKeyVal({ + start: prev(), + key: property, + value: new symbol_type({ + start: prev(), + name: property, + end: prev() + }), + end: prev() + })); + } else { + expect(":"); + elements.push(new AST_ObjectKeyVal({ + start: property_token, + quote: property_token.quote, + key: property, + value: binding_element(used_parameters, symbol_type), + end: prev() + })); + } + } + if (is_expand) { + if (!is("punc", "}")) { + croak("Rest element must be last element"); + } + } else if (is("operator", "=")) { + used_parameters.mark_default_assignment(S.token); + next(); + elements[elements.length - 1].value = new AST_DefaultAssign({ + start: elements[elements.length - 1].value.start, + left: elements[elements.length - 1].value, + operator: "=", + right: expression(false), + end: S.token + }); + } + } + expect("}"); + used_parameters.check_strict(); + return new AST_Destructuring({ + start: first_token, + names: elements, + is_array: false, + end: prev() + }); + } else if (is("name")) { + used_parameters.add_parameter(S.token); + return as_symbol(symbol_type); + } else { + croak("Invalid function parameter"); + } + } + + function params_or_seq_(allow_arrows, maybe_sequence) { + var spread_token; + var invalid_sequence; + var trailing_comma; + var a = []; + expect("("); + while (!is("punc", ")")) { + if (spread_token) unexpected(spread_token); + if (is("expand", "...")) { + spread_token = S.token; + if (maybe_sequence) invalid_sequence = S.token; + next(); + a.push(new AST_Expansion({ + start: prev(), + expression: expression(), + end: S.token, + })); + } else { + a.push(expression()); + } + if (!is("punc", ")")) { + expect(","); + if (is("punc", ")")) { + trailing_comma = prev(); + if (maybe_sequence) invalid_sequence = trailing_comma; + } + } + } + expect(")"); + if (allow_arrows && is("arrow", "=>")) { + if (spread_token && trailing_comma) unexpected(trailing_comma); + } else if (invalid_sequence) { + unexpected(invalid_sequence); + } + return a; + } + + function _function_body(block, generator, is_async, name, args) { + var loop = S.in_loop; + var labels = S.labels; + var current_generator = S.in_generator; + var current_async = S.in_async; + ++S.in_function; + if (generator) + S.in_generator = S.in_function; + if (is_async) + S.in_async = S.in_function; + if (args) parameters(args); + if (block) + S.in_directives = true; + S.in_loop = 0; + S.labels = []; + if (block) { + S.input.push_directives_stack(); + var a = block_(); + if (name) _verify_symbol(name); + if (args) args.forEach(_verify_symbol); + S.input.pop_directives_stack(); + } else { + var a = [new AST_Return({ + start: S.token, + value: expression(false), + end: S.token + })]; + } + --S.in_function; + S.in_loop = loop; + S.labels = labels; + S.in_generator = current_generator; + S.in_async = current_async; + return a; + } + + function _await_expression() { + // Previous token must be "await" and not be interpreted as an identifier + if (!can_await()) { + croak("Unexpected await expression outside async function", + S.prev.line, S.prev.col, S.prev.pos); + } + // the await expression is parsed as a unary expression in Babel + return new AST_Await({ + start: prev(), + end: S.token, + expression : maybe_unary(true), + }); + } + + function _yield_expression() { + // Previous token must be keyword yield and not be interpret as an identifier + if (!is_in_generator()) { + croak("Unexpected yield expression outside generator function", + S.prev.line, S.prev.col, S.prev.pos); + } + var start = S.token; + var star = false; + var has_expression = true; + + // Attempt to get expression or star (and then the mandatory expression) + // behind yield on the same line. + // + // If nothing follows on the same line of the yieldExpression, + // it should default to the value `undefined` for yield to return. + // In that case, the `undefined` stored as `null` in ast. + // + // Note 1: It isn't allowed for yield* to close without an expression + // Note 2: If there is a nlb between yield and star, it is interpret as + // yield * + if (can_insert_semicolon() || + (is("punc") && PUNC_AFTER_EXPRESSION.has(S.token.value))) { + has_expression = false; + + } else if (is("operator", "*")) { + star = true; + next(); + } + + return new AST_Yield({ + start : start, + is_star : star, + expression : has_expression ? expression() : null, + end : prev() + }); + } + + function if_() { + var cond = parenthesised(), body = statement(false, false, true), belse = null; + if (is("keyword", "else")) { + next(); + belse = statement(false, false, true); + } + return new AST_If({ + condition : cond, + body : body, + alternative : belse + }); + } + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + a.push(statement()); + } + next(); + return a; + } + + function switch_body_() { + expect("{"); + var a = [], cur = null, branch = null, tmp; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + if (is("keyword", "case")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Case({ + start : (tmp = S.token, next(), tmp), + expression : expression(true), + body : cur + }); + a.push(branch); + expect(":"); + } else if (is("keyword", "default")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Default({ + start : (tmp = S.token, next(), expect(":"), tmp), + body : cur + }); + a.push(branch); + } else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + if (branch) branch.end = prev(); + next(); + return a; + } + + function try_() { + var body = block_(), bcatch = null, bfinally = null; + if (is("keyword", "catch")) { + var start = S.token; + next(); + if (is("punc", "{")) { + var name = null; + } else { + expect("("); + var name = parameter(undefined, AST_SymbolCatch); + expect(")"); + } + bcatch = new AST_Catch({ + start : start, + argname : name, + body : block_(), + end : prev() + }); + } + if (is("keyword", "finally")) { + var start = S.token; + next(); + bfinally = new AST_Finally({ + start : start, + body : block_(), + end : prev() + }); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return new AST_Try({ + body : body, + bcatch : bcatch, + bfinally : bfinally + }); + } + + function vardefs(no_in, kind) { + var a = []; + var def; + for (;;) { + var sym_type = + kind === "var" ? AST_SymbolVar : + kind === "const" ? AST_SymbolConst : + kind === "let" ? AST_SymbolLet : null; + if (is("punc", "{") || is("punc", "[")) { + def = new AST_VarDef({ + start: S.token, + name: binding_element(undefined ,sym_type), + value: is("operator", "=") ? (expect_token("operator", "="), expression(false, no_in)) : null, + end: prev() + }); + } else { + def = new AST_VarDef({ + start : S.token, + name : as_symbol(sym_type), + value : is("operator", "=") + ? (next(), expression(false, no_in)) + : !no_in && kind === "const" + ? croak("Missing initializer in const declaration") : null, + end : prev() + }); + if (def.name.name == "import") croak("Unexpected token: import"); + } + a.push(def); + if (!is("punc", ",")) + break; + next(); + } + return a; + } + + var var_ = function(no_in) { + return new AST_Var({ + start : prev(), + definitions : vardefs(no_in, "var"), + end : prev() + }); + }; + + var let_ = function(no_in) { + return new AST_Let({ + start : prev(), + definitions : vardefs(no_in, "let"), + end : prev() + }); + }; + + var const_ = function(no_in) { + return new AST_Const({ + start : prev(), + definitions : vardefs(no_in, "const"), + end : prev() + }); + }; + + var new_ = function(allow_calls) { + var start = S.token; + expect_token("operator", "new"); + if (is("punc", ".")) { + next(); + expect_token("name", "target"); + return subscripts(new AST_NewTarget({ + start : start, + end : prev() + }), allow_calls); + } + var newexp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")", true); + } else { + args = []; + } + var call = new AST_New({ + start : start, + expression : newexp, + args : args, + end : prev() + }); + annotate(call); + return subscripts(call, allow_calls); + }; + + function as_atom_node() { + var tok = S.token, ret; + switch (tok.type) { + case "name": + ret = _make_symbol(AST_SymbolRef); + break; + case "num": + ret = new AST_Number({ + start: tok, + end: tok, + value: tok.value, + raw: LATEST_RAW + }); + break; + case "big_int": + ret = new AST_BigInt({ start: tok, end: tok, value: tok.value }); + break; + case "string": + ret = new AST_String({ + start : tok, + end : tok, + value : tok.value, + quote : tok.quote + }); + break; + case "regexp": + const [_, source, flags] = tok.value.match(/^\/(.*)\/(\w*)$/); + + ret = new AST_RegExp({ start: tok, end: tok, value: { source, flags } }); + break; + case "atom": + switch (tok.value) { + case "false": + ret = new AST_False({ start: tok, end: tok }); + break; + case "true": + ret = new AST_True({ start: tok, end: tok }); + break; + case "null": + ret = new AST_Null({ start: tok, end: tok }); + break; + } + break; + } + next(); + return ret; + } + + function to_fun_args(ex, default_seen_above) { + var insert_default = function(ex, default_value) { + if (default_value) { + return new AST_DefaultAssign({ + start: ex.start, + left: ex, + operator: "=", + right: default_value, + end: default_value.end + }); + } + return ex; + }; + if (ex instanceof AST_Object) { + return insert_default(new AST_Destructuring({ + start: ex.start, + end: ex.end, + is_array: false, + names: ex.properties.map(prop => to_fun_args(prop)) + }), default_seen_above); + } else if (ex instanceof AST_ObjectKeyVal) { + ex.value = to_fun_args(ex.value); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_Hole) { + return ex; + } else if (ex instanceof AST_Destructuring) { + ex.names = ex.names.map(name => to_fun_args(name)); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_SymbolRef) { + return insert_default(new AST_SymbolFunarg({ + name: ex.name, + start: ex.start, + end: ex.end + }), default_seen_above); + } else if (ex instanceof AST_Expansion) { + ex.expression = to_fun_args(ex.expression); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_Array) { + return insert_default(new AST_Destructuring({ + start: ex.start, + end: ex.end, + is_array: true, + names: ex.elements.map(elm => to_fun_args(elm)) + }), default_seen_above); + } else if (ex instanceof AST_Assign) { + return insert_default(to_fun_args(ex.left, ex.right), default_seen_above); + } else if (ex instanceof AST_DefaultAssign) { + ex.left = to_fun_args(ex.left); + return ex; + } else { + croak("Invalid function parameter", ex.start.line, ex.start.col); + } + } + + var expr_atom = function(allow_calls, allow_arrows) { + if (is("operator", "new")) { + return new_(allow_calls); + } + if (is("operator", "import")) { + return import_meta(); + } + var start = S.token; + var peeked; + var async = is("name", "async") + && (peeked = peek()).value != "[" + && peeked.type != "arrow" + && as_atom_node(); + if (is("punc")) { + switch (S.token.value) { + case "(": + if (async && !allow_calls) break; + var exprs = params_or_seq_(allow_arrows, !async); + if (allow_arrows && is("arrow", "=>")) { + return arrow_function(start, exprs.map(e => to_fun_args(e)), !!async); + } + var ex = async ? new AST_Call({ + expression: async, + args: exprs + }) : exprs.length == 1 ? exprs[0] : new AST_Sequence({ + expressions: exprs + }); + if (ex.start) { + const outer_comments_before = start.comments_before.length; + outer_comments_before_counts.set(start, outer_comments_before); + ex.start.comments_before.unshift(...start.comments_before); + start.comments_before = ex.start.comments_before; + if (outer_comments_before == 0 && start.comments_before.length > 0) { + var comment = start.comments_before[0]; + if (!comment.nlb) { + comment.nlb = start.nlb; + start.nlb = false; + } + } + start.comments_after = ex.start.comments_after; + } + ex.start = start; + var end = prev(); + if (ex.end) { + end.comments_before = ex.end.comments_before; + ex.end.comments_after.push(...end.comments_after); + end.comments_after = ex.end.comments_after; + } + ex.end = end; + if (ex instanceof AST_Call) annotate(ex); + return subscripts(ex, allow_calls); + case "[": + return subscripts(array_(), allow_calls); + case "{": + return subscripts(object_or_destructuring_(), allow_calls); + } + if (!async) unexpected(); + } + if (allow_arrows && is("name") && is_token(peek(), "arrow")) { + var param = new AST_SymbolFunarg({ + name: S.token.value, + start: start, + end: start, + }); + next(); + return arrow_function(start, [param], !!async); + } + if (is("keyword", "function")) { + next(); + var func = function_(AST_Function, false, !!async); + func.start = start; + func.end = prev(); + return subscripts(func, allow_calls); + } + if (async) return subscripts(async, allow_calls); + if (is("keyword", "class")) { + next(); + var cls = class_(AST_ClassExpression); + cls.start = start; + cls.end = prev(); + return subscripts(cls, allow_calls); + } + if (is("template_head")) { + return subscripts(template_string(), allow_calls); + } + if (ATOMIC_START_TOKEN.has(S.token.type)) { + return subscripts(as_atom_node(), allow_calls); + } + unexpected(); + }; + + function template_string() { + var segments = [], start = S.token; + + segments.push(new AST_TemplateSegment({ + start: S.token, + raw: LATEST_RAW, + value: S.token.value, + end: S.token + })); + + while (!LATEST_TEMPLATE_END) { + next(); + handle_regexp(); + segments.push(expression(true)); + + segments.push(new AST_TemplateSegment({ + start: S.token, + raw: LATEST_RAW, + value: S.token.value, + end: S.token + })); + } + next(); + + return new AST_TemplateString({ + start: start, + segments: segments, + end: S.token + }); + } + + function expr_list(closing, allow_trailing_comma, allow_empty) { + var first = true, a = []; + while (!is("punc", closing)) { + if (first) first = false; else expect(","); + if (allow_trailing_comma && is("punc", closing)) break; + if (is("punc", ",") && allow_empty) { + a.push(new AST_Hole({ start: S.token, end: S.token })); + } else if (is("expand", "...")) { + next(); + a.push(new AST_Expansion({start: prev(), expression: expression(),end: S.token})); + } else { + a.push(expression(false)); + } + } + next(); + return a; + } + + var array_ = embed_tokens(function() { + expect("["); + return new AST_Array({ + elements: expr_list("]", !options.strict, true) + }); + }); + + var create_accessor = embed_tokens((is_generator, is_async) => { + return function_(AST_Accessor, is_generator, is_async); + }); + + var object_or_destructuring_ = embed_tokens(function object_or_destructuring_() { + var start = S.token, first = true, a = []; + expect("{"); + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + if (!options.strict && is("punc", "}")) + // allow trailing comma + break; + + start = S.token; + if (start.type == "expand") { + next(); + a.push(new AST_Expansion({ + start: start, + expression: expression(false), + end: prev(), + })); + continue; + } + + var name = as_property_name(); + var value; + + // Check property and fetch value + if (!is("punc", ":")) { + var concise = concise_method_or_getset(name, start); + if (concise) { + a.push(concise); + continue; + } + + value = new AST_SymbolRef({ + start: prev(), + name: name, + end: prev() + }); + } else if (name === null) { + unexpected(prev()); + } else { + next(); // `:` - see first condition + value = expression(false); + } + + // Check for default value and alter value accordingly if necessary + if (is("operator", "=")) { + next(); + value = new AST_Assign({ + start: start, + left: value, + operator: "=", + right: expression(false), + logical: false, + end: prev() + }); + } + + // Create property + a.push(new AST_ObjectKeyVal({ + start: start, + quote: start.quote, + key: name instanceof AST_Node ? name : "" + name, + value: value, + end: prev() + })); + } + next(); + return new AST_Object({ properties: a }); + }); + + function class_(KindOfClass, is_export_default) { + var start, method, class_name, extends_, a = []; + + S.input.push_directives_stack(); // Push directive stack, but not scope stack + S.input.add_directive("use strict"); + + if (S.token.type == "name" && S.token.value != "extends") { + class_name = as_symbol(KindOfClass === AST_DefClass ? AST_SymbolDefClass : AST_SymbolClass); + } + + if (KindOfClass === AST_DefClass && !class_name) { + if (is_export_default) { + KindOfClass = AST_ClassExpression; + } else { + unexpected(); + } + } + + if (S.token.value == "extends") { + next(); + extends_ = expression(true); + } + + expect("{"); + + while (is("punc", ";")) { next(); } // Leading semicolons are okay in class bodies. + while (!is("punc", "}")) { + start = S.token; + method = concise_method_or_getset(as_property_name(), start, true); + if (!method) { unexpected(); } + a.push(method); + while (is("punc", ";")) { next(); } + } + + S.input.pop_directives_stack(); + + next(); + + return new KindOfClass({ + start: start, + name: class_name, + extends: extends_, + properties: a, + end: prev(), + }); + } + + function concise_method_or_getset(name, start, is_class) { + const get_symbol_ast = (name, SymbolClass = AST_SymbolMethod) => { + if (typeof name === "string" || typeof name === "number") { + return new SymbolClass({ + start, + name: "" + name, + end: prev() + }); + } else if (name === null) { + unexpected(); + } + return name; + }; + + const is_not_method_start = () => + !is("punc", "(") && !is("punc", ",") && !is("punc", "}") && !is("punc", ";") && !is("operator", "="); + + var is_async = false; + var is_static = false; + var is_generator = false; + var is_private = false; + var accessor_type = null; + + if (is_class && name === "static" && is_not_method_start()) { + is_static = true; + name = as_property_name(); + } + if (name === "async" && is_not_method_start()) { + is_async = true; + name = as_property_name(); + } + if (prev().type === "operator" && prev().value === "*") { + is_generator = true; + name = as_property_name(); + } + if ((name === "get" || name === "set") && is_not_method_start()) { + accessor_type = name; + name = as_property_name(); + } + if (prev().type === "privatename") { + is_private = true; + } + + const property_token = prev(); + + if (accessor_type != null) { + if (!is_private) { + const AccessorClass = accessor_type === "get" + ? AST_ObjectGetter + : AST_ObjectSetter; + + name = get_symbol_ast(name); + return new AccessorClass({ + start, + static: is_static, + key: name, + quote: name instanceof AST_SymbolMethod ? property_token.quote : undefined, + value: create_accessor(), + end: prev() + }); + } else { + const AccessorClass = accessor_type === "get" + ? AST_PrivateGetter + : AST_PrivateSetter; + + return new AccessorClass({ + start, + static: is_static, + key: get_symbol_ast(name), + value: create_accessor(), + end: prev(), + }); + } + } + + if (is("punc", "(")) { + name = get_symbol_ast(name); + const AST_MethodVariant = is_private + ? AST_PrivateMethod + : AST_ConciseMethod; + var node = new AST_MethodVariant({ + start : start, + static : is_static, + is_generator: is_generator, + async : is_async, + key : name, + quote : name instanceof AST_SymbolMethod ? + property_token.quote : undefined, + value : create_accessor(is_generator, is_async), + end : prev() + }); + return node; + } + + if (is_class) { + const key = get_symbol_ast(name, AST_SymbolClassProperty); + const quote = key instanceof AST_SymbolClassProperty + ? property_token.quote + : undefined; + const AST_ClassPropertyVariant = is_private + ? AST_ClassPrivateProperty + : AST_ClassProperty; + if (is("operator", "=")) { + next(); + return new AST_ClassPropertyVariant({ + start, + static: is_static, + quote, + key, + value: expression(false), + end: prev() + }); + } else if ( + is("name") + || is("privatename") + || is("operator", "*") + || is("punc", ";") + || is("punc", "}") + ) { + return new AST_ClassPropertyVariant({ + start, + static: is_static, + quote, + key, + end: prev() + }); + } + } + } + + function maybe_import_assertion() { + if (is("name", "assert") && !has_newline_before(S.token)) { + next(); + return object_or_destructuring_(); + } + return null; + } + + function import_statement() { + var start = prev(); + + var imported_name; + var imported_names; + if (is("name")) { + imported_name = as_symbol(AST_SymbolImport); + } + + if (is("punc", ",")) { + next(); + } + + imported_names = map_names(true); + + if (imported_names || imported_name) { + expect_token("name", "from"); + } + var mod_str = S.token; + if (mod_str.type !== "string") { + unexpected(); + } + next(); + + const assert_clause = maybe_import_assertion(); + + return new AST_Import({ + start, + imported_name, + imported_names, + module_name: new AST_String({ + start: mod_str, + value: mod_str.value, + quote: mod_str.quote, + end: mod_str, + }), + assert_clause, + end: S.token, + }); + } + + function import_meta() { + var start = S.token; + expect_token("operator", "import"); + expect_token("punc", "."); + expect_token("name", "meta"); + return subscripts(new AST_ImportMeta({ + start: start, + end: prev() + }), false); + } + + function map_name(is_import) { + function make_symbol(type) { + return new type({ + name: as_property_name(), + start: prev(), + end: prev() + }); + } + + var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; + var type = is_import ? AST_SymbolImport : AST_SymbolExport; + var start = S.token; + var foreign_name; + var name; + + if (is_import) { + foreign_name = make_symbol(foreign_type); + } else { + name = make_symbol(type); + } + if (is("name", "as")) { + next(); // The "as" word + if (is_import) { + name = make_symbol(type); + } else { + foreign_name = make_symbol(foreign_type); + } + } else if (is_import) { + name = new type(foreign_name); + } else { + foreign_name = new foreign_type(name); + } + + return new AST_NameMapping({ + start: start, + foreign_name: foreign_name, + name: name, + end: prev(), + }); + } + + function map_nameAsterisk(is_import, name) { + var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; + var type = is_import ? AST_SymbolImport : AST_SymbolExport; + var start = S.token; + var foreign_name; + var end = prev(); + + name = name || new type({ + name: "*", + start: start, + end: end, + }); + + foreign_name = new foreign_type({ + name: "*", + start: start, + end: end, + }); + + return new AST_NameMapping({ + start: start, + foreign_name: foreign_name, + name: name, + end: end, + }); + } + + function map_names(is_import) { + var names; + if (is("punc", "{")) { + next(); + names = []; + while (!is("punc", "}")) { + names.push(map_name(is_import)); + if (is("punc", ",")) { + next(); + } + } + next(); + } else if (is("operator", "*")) { + var name; + next(); + if (is_import && is("name", "as")) { + next(); // The "as" word + name = as_symbol(is_import ? AST_SymbolImport : AST_SymbolExportForeign); + } + names = [map_nameAsterisk(is_import, name)]; + } + return names; + } + + function export_statement() { + var start = S.token; + var is_default; + var exported_names; + + if (is("keyword", "default")) { + is_default = true; + next(); + } else if (exported_names = map_names(false)) { + if (is("name", "from")) { + next(); + + var mod_str = S.token; + if (mod_str.type !== "string") { + unexpected(); + } + next(); + + const assert_clause = maybe_import_assertion(); + + return new AST_Export({ + start: start, + is_default: is_default, + exported_names: exported_names, + module_name: new AST_String({ + start: mod_str, + value: mod_str.value, + quote: mod_str.quote, + end: mod_str, + }), + end: prev(), + assert_clause + }); + } else { + return new AST_Export({ + start: start, + is_default: is_default, + exported_names: exported_names, + end: prev(), + }); + } + } + + var node; + var exported_value; + var exported_definition; + if (is("punc", "{") + || is_default + && (is("keyword", "class") || is("keyword", "function")) + && is_token(peek(), "punc")) { + exported_value = expression(false); + semicolon(); + } else if ((node = statement(is_default)) instanceof AST_Definitions && is_default) { + unexpected(node.start); + } else if ( + node instanceof AST_Definitions + || node instanceof AST_Defun + || node instanceof AST_DefClass + ) { + exported_definition = node; + } else if ( + node instanceof AST_ClassExpression + || node instanceof AST_Function + ) { + exported_value = node; + } else if (node instanceof AST_SimpleStatement) { + exported_value = node.body; + } else { + unexpected(node.start); + } + + return new AST_Export({ + start: start, + is_default: is_default, + exported_value: exported_value, + exported_definition: exported_definition, + end: prev(), + assert_clause: null + }); + } + + function as_property_name() { + var tmp = S.token; + switch (tmp.type) { + case "punc": + if (tmp.value === "[") { + next(); + var ex = expression(false); + expect("]"); + return ex; + } else unexpected(tmp); + case "operator": + if (tmp.value === "*") { + next(); + return null; + } + if (!["delete", "in", "instanceof", "new", "typeof", "void"].includes(tmp.value)) { + unexpected(tmp); + } + /* falls through */ + case "name": + case "privatename": + case "string": + case "num": + case "big_int": + case "keyword": + case "atom": + next(); + return tmp.value; + default: + unexpected(tmp); + } + } + + function as_name() { + var tmp = S.token; + if (tmp.type != "name" && tmp.type != "privatename") unexpected(); + next(); + return tmp.value; + } + + function _make_symbol(type) { + var name = S.token.value; + return new (name == "this" ? AST_This : + name == "super" ? AST_Super : + type)({ + name : String(name), + start : S.token, + end : S.token + }); + } + + function _verify_symbol(sym) { + var name = sym.name; + if (is_in_generator() && name == "yield") { + token_error(sym.start, "Yield cannot be used as identifier inside generators"); + } + if (S.input.has_directive("use strict")) { + if (name == "yield") { + token_error(sym.start, "Unexpected yield identifier inside strict mode"); + } + if (sym instanceof AST_SymbolDeclaration && (name == "arguments" || name == "eval")) { + token_error(sym.start, "Unexpected " + name + " in strict mode"); + } + } + } + + function as_symbol(type, noerror) { + if (!is("name")) { + if (!noerror) croak("Name expected"); + return null; + } + var sym = _make_symbol(type); + _verify_symbol(sym); + next(); + return sym; + } + + // Annotate AST_Call, AST_Lambda or AST_New with the special comments + function annotate(node) { + var start = node.start; + var comments = start.comments_before; + const comments_outside_parens = outer_comments_before_counts.get(start); + var i = comments_outside_parens != null ? comments_outside_parens : comments.length; + while (--i >= 0) { + var comment = comments[i]; + if (/[@#]__/.test(comment.value)) { + if (/[@#]__PURE__/.test(comment.value)) { + set_annotation(node, _PURE); + break; + } + if (/[@#]__INLINE__/.test(comment.value)) { + set_annotation(node, _INLINE); + break; + } + if (/[@#]__NOINLINE__/.test(comment.value)) { + set_annotation(node, _NOINLINE); + break; + } + } + } + } + + var subscripts = function(expr, allow_calls, is_chain) { + var start = expr.start; + if (is("punc", ".")) { + next(); + const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; + return subscripts(new AST_DotVariant({ + start : start, + expression : expr, + optional : false, + property : as_name(), + end : prev() + }), allow_calls, is_chain); + } + if (is("punc", "[")) { + next(); + var prop = expression(true); + expect("]"); + return subscripts(new AST_Sub({ + start : start, + expression : expr, + optional : false, + property : prop, + end : prev() + }), allow_calls, is_chain); + } + if (allow_calls && is("punc", "(")) { + next(); + var call = new AST_Call({ + start : start, + expression : expr, + optional : false, + args : call_args(), + end : prev() + }); + annotate(call); + return subscripts(call, true, is_chain); + } + + if (is("punc", "?.")) { + next(); + + let chain_contents; + + if (allow_calls && is("punc", "(")) { + next(); + + const call = new AST_Call({ + start, + optional: true, + expression: expr, + args: call_args(), + end: prev() + }); + annotate(call); + + chain_contents = subscripts(call, true, true); + } else if (is("name") || is("privatename")) { + const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; + chain_contents = subscripts(new AST_DotVariant({ + start, + expression: expr, + optional: true, + property: as_name(), + end: prev() + }), allow_calls, true); + } else if (is("punc", "[")) { + next(); + const property = expression(true); + expect("]"); + chain_contents = subscripts(new AST_Sub({ + start, + expression: expr, + optional: true, + property, + end: prev() + }), allow_calls, true); + } + + if (!chain_contents) unexpected(); + + if (chain_contents instanceof AST_Chain) return chain_contents; + + return new AST_Chain({ + start, + expression: chain_contents, + end: prev() + }); + } + + if (is("template_head")) { + if (is_chain) { + // a?.b`c` is a syntax error + unexpected(); + } + + return subscripts(new AST_PrefixedTemplateString({ + start: start, + prefix: expr, + template_string: template_string(), + end: prev() + }), allow_calls); + } + + return expr; + }; + + function call_args() { + var args = []; + while (!is("punc", ")")) { + if (is("expand", "...")) { + next(); + args.push(new AST_Expansion({ + start: prev(), + expression: expression(false), + end: prev() + })); + } else { + args.push(expression(false)); + } + if (!is("punc", ")")) { + expect(","); + } + } + next(); + return args; + } + + var maybe_unary = function(allow_calls, allow_arrows) { + var start = S.token; + if (start.type == "name" && start.value == "await" && can_await()) { + next(); + return _await_expression(); + } + if (is("operator") && UNARY_PREFIX.has(start.value)) { + next(); + handle_regexp(); + var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(allow_calls)); + ex.start = start; + ex.end = prev(); + return ex; + } + var val = expr_atom(allow_calls, allow_arrows); + while (is("operator") && UNARY_POSTFIX.has(S.token.value) && !has_newline_before(S.token)) { + if (val instanceof AST_Arrow) unexpected(); + val = make_unary(AST_UnaryPostfix, S.token, val); + val.start = start; + val.end = S.token; + next(); + } + return val; + }; + + function make_unary(ctor, token, expr) { + var op = token.value; + switch (op) { + case "++": + case "--": + if (!is_assignable(expr)) + croak("Invalid use of " + op + " operator", token.line, token.col, token.pos); + break; + case "delete": + if (expr instanceof AST_SymbolRef && S.input.has_directive("use strict")) + croak("Calling delete on expression not allowed in strict mode", expr.start.line, expr.start.col, expr.start.pos); + break; + } + return new ctor({ operator: op, expression: expr }); + } + + var expr_op = function(left, min_prec, no_in) { + var op = is("operator") ? S.token.value : null; + if (op == "in" && no_in) op = null; + if (op == "**" && left instanceof AST_UnaryPrefix + /* unary token in front not allowed - parenthesis required */ + && !is_token(left.start, "punc", "(") + && left.operator !== "--" && left.operator !== "++") + unexpected(left.start); + var prec = op != null ? PRECEDENCE[op] : null; + if (prec != null && (prec > min_prec || (op === "**" && min_prec === prec))) { + next(); + var right = expr_op(maybe_unary(true), prec, no_in); + return expr_op(new AST_Binary({ + start : left.start, + left : left, + operator : op, + right : right, + end : right.end + }), min_prec, no_in); + } + return left; + }; + + function expr_ops(no_in) { + return expr_op(maybe_unary(true, true), 0, no_in); + } + + var maybe_conditional = function(no_in) { + var start = S.token; + var expr = expr_ops(no_in); + if (is("operator", "?")) { + next(); + var yes = expression(false); + expect(":"); + return new AST_Conditional({ + start : start, + condition : expr, + consequent : yes, + alternative : expression(false, no_in), + end : prev() + }); + } + return expr; + }; + + function is_assignable(expr) { + return expr instanceof AST_PropAccess || expr instanceof AST_SymbolRef; + } + + function to_destructuring(node) { + if (node instanceof AST_Object) { + node = new AST_Destructuring({ + start: node.start, + names: node.properties.map(to_destructuring), + is_array: false, + end: node.end + }); + } else if (node instanceof AST_Array) { + var names = []; + + for (var i = 0; i < node.elements.length; i++) { + // Only allow expansion as last element + if (node.elements[i] instanceof AST_Expansion) { + if (i + 1 !== node.elements.length) { + token_error(node.elements[i].start, "Spread must the be last element in destructuring array"); + } + node.elements[i].expression = to_destructuring(node.elements[i].expression); + } + + names.push(to_destructuring(node.elements[i])); + } + + node = new AST_Destructuring({ + start: node.start, + names: names, + is_array: true, + end: node.end + }); + } else if (node instanceof AST_ObjectProperty) { + node.value = to_destructuring(node.value); + } else if (node instanceof AST_Assign) { + node = new AST_DefaultAssign({ + start: node.start, + left: node.left, + operator: "=", + right: node.right, + end: node.end + }); + } + return node; + } + + // In ES6, AssignmentExpression can also be an ArrowFunction + var maybe_assign = function(no_in) { + handle_regexp(); + var start = S.token; + + if (start.type == "name" && start.value == "yield") { + if (is_in_generator()) { + next(); + return _yield_expression(); + } else if (S.input.has_directive("use strict")) { + token_error(S.token, "Unexpected yield identifier inside strict mode"); + } + } + + var left = maybe_conditional(no_in); + var val = S.token.value; + + if (is("operator") && ASSIGNMENT.has(val)) { + if (is_assignable(left) || (left = to_destructuring(left)) instanceof AST_Destructuring) { + next(); + + return new AST_Assign({ + start : start, + left : left, + operator : val, + right : maybe_assign(no_in), + logical : LOGICAL_ASSIGNMENT.has(val), + end : prev() + }); + } + croak("Invalid assignment"); + } + return left; + }; + + var expression = function(commas, no_in) { + var start = S.token; + var exprs = []; + while (true) { + exprs.push(maybe_assign(no_in)); + if (!commas || !is("punc", ",")) break; + next(); + commas = true; + } + return exprs.length == 1 ? exprs[0] : new AST_Sequence({ + start : start, + expressions : exprs, + end : peek() + }); + }; + + function in_loop(cont) { + ++S.in_loop; + var ret = cont(); + --S.in_loop; + return ret; + } + + if (options.expression) { + return expression(true); + } + + return (function parse_toplevel() { + var start = S.token; + var body = []; + S.input.push_directives_stack(); + if (options.module) S.input.add_directive("use strict"); + while (!is("eof")) { + body.push(statement()); + } + S.input.pop_directives_stack(); + var end = prev(); + var toplevel = options.toplevel; + if (toplevel) { + toplevel.body = toplevel.body.concat(body); + toplevel.end = end; + } else { + toplevel = new AST_Toplevel({ start: start, body: body, end: end }); + } + return toplevel; + })(); + +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +function DEFNODE(type, props, methods, base = AST_Node) { + if (!props) props = []; + else props = props.split(/\s+/); + var self_props = props; + if (base && base.PROPS) + props = props.concat(base.PROPS); + var code = "return function AST_" + type + "(props){ if (props) { "; + for (var i = props.length; --i >= 0;) { + code += "this." + props[i] + " = props." + props[i] + ";"; + } + const proto = base && Object.create(base.prototype); + if (proto && proto.initialize || (methods && methods.initialize)) + code += "this.initialize();"; + code += "}"; + code += "this.flags = 0;"; + code += "}"; + var ctor = new Function(code)(); + if (proto) { + ctor.prototype = proto; + ctor.BASE = base; + } + if (base) base.SUBCLASSES.push(ctor); + ctor.prototype.CTOR = ctor; + ctor.prototype.constructor = ctor; + ctor.PROPS = props || null; + ctor.SELF_PROPS = self_props; + ctor.SUBCLASSES = []; + if (type) { + ctor.prototype.TYPE = ctor.TYPE = type; + } + if (methods) for (i in methods) if (HOP(methods, i)) { + if (i[0] === "$") { + ctor[i.substr(1)] = methods[i]; + } else { + ctor.prototype[i] = methods[i]; + } + } + ctor.DEFMETHOD = function(name, method) { + this.prototype[name] = method; + }; + return ctor; +} + +const has_tok_flag = (tok, flag) => Boolean(tok.flags & flag); +const set_tok_flag = (tok, flag, truth) => { + if (truth) { + tok.flags |= flag; + } else { + tok.flags &= ~flag; + } +}; + +const TOK_FLAG_NLB = 0b0001; +const TOK_FLAG_QUOTE_SINGLE = 0b0010; +const TOK_FLAG_QUOTE_EXISTS = 0b0100; + +class AST_Token { + constructor(type, value, line, col, pos, nlb, comments_before, comments_after, file) { + this.flags = (nlb ? 1 : 0); + + this.type = type; + this.value = value; + this.line = line; + this.col = col; + this.pos = pos; + this.comments_before = comments_before; + this.comments_after = comments_after; + this.file = file; + + Object.seal(this); + } + + get nlb() { + return has_tok_flag(this, TOK_FLAG_NLB); + } + + set nlb(new_nlb) { + set_tok_flag(this, TOK_FLAG_NLB, new_nlb); + } + + get quote() { + return !has_tok_flag(this, TOK_FLAG_QUOTE_EXISTS) + ? "" + : (has_tok_flag(this, TOK_FLAG_QUOTE_SINGLE) ? "'" : '"'); + } + + set quote(quote_type) { + set_tok_flag(this, TOK_FLAG_QUOTE_SINGLE, quote_type === "'"); + set_tok_flag(this, TOK_FLAG_QUOTE_EXISTS, !!quote_type); + } +} + +var AST_Node = DEFNODE("Node", "start end", { + _clone: function(deep) { + if (deep) { + var self = this.clone(); + return self.transform(new TreeTransformer(function(node) { + if (node !== self) { + return node.clone(true); + } + })); + } + return new this.CTOR(this); + }, + clone: function(deep) { + return this._clone(deep); + }, + $documentation: "Base class of all AST nodes", + $propdoc: { + start: "[AST_Token] The first token of this node", + end: "[AST_Token] The last token of this node" + }, + _walk: function(visitor) { + return visitor._visit(this); + }, + walk: function(visitor) { + return this._walk(visitor); // not sure the indirection will be any help + }, + _children_backwards: () => {} +}, null); + +/* -----[ statements ]----- */ + +var AST_Statement = DEFNODE("Statement", null, { + $documentation: "Base class of all statements", +}); + +var AST_Debugger = DEFNODE("Debugger", null, { + $documentation: "Represents a debugger statement", +}, AST_Statement); + +var AST_Directive = DEFNODE("Directive", "value quote", { + $documentation: "Represents a directive, like \"use strict\";", + $propdoc: { + value: "[string] The value of this directive as a plain string (it's not an AST_String!)", + quote: "[string] the original quote character" + }, +}, AST_Statement); + +var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", { + $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", + $propdoc: { + body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + } +}, AST_Statement); + +function walk_body(node, visitor) { + const body = node.body; + for (var i = 0, len = body.length; i < len; i++) { + body[i]._walk(visitor); + } +} + +function clone_block_scope(deep) { + var clone = this._clone(deep); + if (this.block_scope) { + clone.block_scope = this.block_scope.clone(); + } + return clone; +} + +var AST_Block = DEFNODE("Block", "body block_scope", { + $documentation: "A body of statements (usually braced)", + $propdoc: { + body: "[AST_Statement*] an array of statements", + block_scope: "[AST_Scope] the block scope" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + }, + clone: clone_block_scope +}, AST_Statement); + +var AST_BlockStatement = DEFNODE("BlockStatement", null, { + $documentation: "A block statement", +}, AST_Block); + +var AST_EmptyStatement = DEFNODE("EmptyStatement", null, { + $documentation: "The empty statement (empty block or simply a semicolon)" +}, AST_Statement); + +var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { + $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", + $propdoc: { + body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" + } +}, AST_Statement); + +var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { + $documentation: "Statement with a label", + $propdoc: { + label: "[AST_Label] a label definition" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.label._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.label); + }, + clone: function(deep) { + var node = this._clone(deep); + if (deep) { + var label = node.label; + var def = this.label; + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_LoopControl + && node.label && node.label.thedef === def) { + node.label.thedef = label; + label.references.push(node); + } + })); + } + return node; + } +}, AST_StatementWithBody); + +var AST_IterationStatement = DEFNODE("IterationStatement", "block_scope", { + $documentation: "Internal class. All loops inherit from it.", + $propdoc: { + block_scope: "[AST_Scope] the block scope for this iteration statement." + }, + clone: clone_block_scope +}, AST_StatementWithBody); + +var AST_DWLoop = DEFNODE("DWLoop", "condition", { + $documentation: "Base class for do/while statements", + $propdoc: { + condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" + } +}, AST_IterationStatement); + +var AST_Do = DEFNODE("Do", null, { + $documentation: "A `do` statement", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.body._walk(visitor); + this.condition._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.condition); + push(this.body); + } +}, AST_DWLoop); + +var AST_While = DEFNODE("While", null, { + $documentation: "A `while` statement", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.condition); + }, +}, AST_DWLoop); + +var AST_For = DEFNODE("For", "init condition step", { + $documentation: "A `for` statement", + $propdoc: { + init: "[AST_Node?] the `for` initialization code, or null if empty", + condition: "[AST_Node?] the `for` termination clause, or null if empty", + step: "[AST_Node?] the `for` update clause, or null if empty" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.init) this.init._walk(visitor); + if (this.condition) this.condition._walk(visitor); + if (this.step) this.step._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + if (this.step) push(this.step); + if (this.condition) push(this.condition); + if (this.init) push(this.init); + }, +}, AST_IterationStatement); + +var AST_ForIn = DEFNODE("ForIn", "init object", { + $documentation: "A `for ... in` statement", + $propdoc: { + init: "[AST_Node] the `for/in` initialization code", + object: "[AST_Node] the object that we're looping through" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.init._walk(visitor); + this.object._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + if (this.object) push(this.object); + if (this.init) push(this.init); + }, +}, AST_IterationStatement); + +var AST_ForOf = DEFNODE("ForOf", "await", { + $documentation: "A `for ... of` statement", +}, AST_ForIn); + +var AST_With = DEFNODE("With", "expression", { + $documentation: "A `with` statement", + $propdoc: { + expression: "[AST_Node] the `with` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.expression); + }, +}, AST_StatementWithBody); + +/* -----[ scope and functions ]----- */ + +var AST_Scope = DEFNODE("Scope", "variables functions uses_with uses_eval parent_scope enclosed cname", { + $documentation: "Base class for all statements introducing a lexical scope", + $propdoc: { + variables: "[Map/S] a map of name -> SymbolDef for all variables/functions defined in this scope", + uses_with: "[boolean/S] tells whether this scope uses the `with` statement", + uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", + parent_scope: "[AST_Scope?/S] link to the parent scope", + enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", + cname: "[integer/S] current index for mangling variables (used internally by the mangler)", + }, + get_defun_scope: function() { + var self = this; + while (self.is_block_scope()) { + self = self.parent_scope; + } + return self; + }, + clone: function(deep, toplevel) { + var node = this._clone(deep); + if (deep && this.variables && toplevel && !this._block_scope) { + node.figure_out_scope({}, { + toplevel: toplevel, + parent_scope: this.parent_scope + }); + } else { + if (this.variables) node.variables = new Map(this.variables); + if (this.enclosed) node.enclosed = this.enclosed.slice(); + if (this._block_scope) node._block_scope = this._block_scope; + } + return node; + }, + pinned: function() { + return this.uses_eval || this.uses_with; + } +}, AST_Block); + +var AST_Toplevel = DEFNODE("Toplevel", "globals", { + $documentation: "The toplevel scope", + $propdoc: { + globals: "[Map/S] a map of name -> SymbolDef for all undeclared names", + }, + wrap_commonjs: function(name) { + var body = this.body; + var wrapped_tl = "(function(exports){'$ORIG';})(typeof " + name + "=='undefined'?(" + name + "={}):" + name + ");"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function(node) { + if (node instanceof AST_Directive && node.value == "$ORIG") { + return MAP.splice(body); + } + })); + return wrapped_tl; + }, + wrap_enclose: function(args_values) { + if (typeof args_values != "string") args_values = ""; + var index = args_values.indexOf(":"); + if (index < 0) index = args_values.length; + var body = this.body; + return parse([ + "(function(", + args_values.slice(0, index), + '){"$ORIG"})(', + args_values.slice(index + 1), + ")" + ].join("")).transform(new TreeTransformer(function(node) { + if (node instanceof AST_Directive && node.value == "$ORIG") { + return MAP.splice(body); + } + })); + } +}, AST_Scope); + +var AST_Expansion = DEFNODE("Expansion", "expression", { + $documentation: "An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list", + $propdoc: { + expression: "[AST_Node] the thing to be expanded" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression.walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments is_generator async", { + $documentation: "Base class for functions", + $propdoc: { + name: "[AST_SymbolDeclaration?] the name of this function", + argnames: "[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments", + uses_arguments: "[boolean/S] tells whether this function accesses the arguments array", + is_generator: "[boolean] is this a generator method", + async: "[boolean] is this method async", + }, + args_as_names: function () { + var out = []; + for (var i = 0; i < this.argnames.length; i++) { + if (this.argnames[i] instanceof AST_Destructuring) { + out.push(...this.argnames[i].all_symbols()); + } else { + out.push(this.argnames[i]); + } + } + return out; + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.name) this.name._walk(visitor); + var argnames = this.argnames; + for (var i = 0, len = argnames.length; i < len; i++) { + argnames[i]._walk(visitor); + } + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + + i = this.argnames.length; + while (i--) push(this.argnames[i]); + + if (this.name) push(this.name); + }, + is_braceless() { + return this.body[0] instanceof AST_Return && this.body[0].value; + }, + // Default args and expansion don't count, so .argnames.length doesn't cut it + length_property() { + let length = 0; + + for (const arg of this.argnames) { + if (arg instanceof AST_SymbolFunarg || arg instanceof AST_Destructuring) { + length++; + } + } + + return length; + } +}, AST_Scope); + +var AST_Accessor = DEFNODE("Accessor", null, { + $documentation: "A setter/getter function. The `name` property is always null." +}, AST_Lambda); + +var AST_Function = DEFNODE("Function", null, { + $documentation: "A function expression" +}, AST_Lambda); + +var AST_Arrow = DEFNODE("Arrow", null, { + $documentation: "An ES6 Arrow function ((a) => b)" +}, AST_Lambda); + +var AST_Defun = DEFNODE("Defun", null, { + $documentation: "A function definition" +}, AST_Lambda); + +/* -----[ DESTRUCTURING ]----- */ +var AST_Destructuring = DEFNODE("Destructuring", "names is_array", { + $documentation: "A destructuring of several names. Used in destructuring assignment and with destructuring function argument names", + $propdoc: { + "names": "[AST_Node*] Array of properties or elements", + "is_array": "[Boolean] Whether the destructuring represents an object or array" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.names.forEach(function(name) { + name._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.names.length; + while (i--) push(this.names[i]); + }, + all_symbols: function() { + var out = []; + this.walk(new TreeWalker(function (node) { + if (node instanceof AST_Symbol) { + out.push(node); + } + })); + return out; + } +}); + +var AST_PrefixedTemplateString = DEFNODE("PrefixedTemplateString", "template_string prefix", { + $documentation: "A templatestring with a prefix, such as String.raw`foobarbaz`", + $propdoc: { + template_string: "[AST_TemplateString] The template string", + prefix: "[AST_Node] The prefix, which will get called." + }, + _walk: function(visitor) { + return visitor._visit(this, function () { + this.prefix._walk(visitor); + this.template_string._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.template_string); + push(this.prefix); + }, +}); + +var AST_TemplateString = DEFNODE("TemplateString", "segments", { + $documentation: "A template string literal", + $propdoc: { + segments: "[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment." + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.segments.forEach(function(seg) { + seg._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.segments.length; + while (i--) push(this.segments[i]); + } +}); + +var AST_TemplateSegment = DEFNODE("TemplateSegment", "value raw", { + $documentation: "A segment of a template string literal", + $propdoc: { + value: "Content of the segment", + raw: "Raw source of the segment", + } +}); + +/* -----[ JUMPS ]----- */ + +var AST_Jump = DEFNODE("Jump", null, { + $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)" +}, AST_Statement); + +var AST_Exit = DEFNODE("Exit", "value", { + $documentation: "Base class for “exits” (`return` and `throw`)", + $propdoc: { + value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" + }, + _walk: function(visitor) { + return visitor._visit(this, this.value && function() { + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value) push(this.value); + }, +}, AST_Jump); + +var AST_Return = DEFNODE("Return", null, { + $documentation: "A `return` statement" +}, AST_Exit); + +var AST_Throw = DEFNODE("Throw", null, { + $documentation: "A `throw` statement" +}, AST_Exit); + +var AST_LoopControl = DEFNODE("LoopControl", "label", { + $documentation: "Base class for loop control statements (`break` and `continue`)", + $propdoc: { + label: "[AST_LabelRef?] the label, or null if none", + }, + _walk: function(visitor) { + return visitor._visit(this, this.label && function() { + this.label._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.label) push(this.label); + }, +}, AST_Jump); + +var AST_Break = DEFNODE("Break", null, { + $documentation: "A `break` statement" +}, AST_LoopControl); + +var AST_Continue = DEFNODE("Continue", null, { + $documentation: "A `continue` statement" +}, AST_LoopControl); + +var AST_Await = DEFNODE("Await", "expression", { + $documentation: "An `await` statement", + $propdoc: { + expression: "[AST_Node] the mandatory expression being awaited", + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Yield = DEFNODE("Yield", "expression is_star", { + $documentation: "A `yield` statement", + $propdoc: { + expression: "[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false", + is_star: "[Boolean] Whether this is a yield or yield* statement" + }, + _walk: function(visitor) { + return visitor._visit(this, this.expression && function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.expression) push(this.expression); + } +}); + +/* -----[ IF ]----- */ + +var AST_If = DEFNODE("If", "condition alternative", { + $documentation: "A `if` statement", + $propdoc: { + condition: "[AST_Node] the `if` condition", + alternative: "[AST_Statement?] the `else` part, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.body._walk(visitor); + if (this.alternative) this.alternative._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.alternative) { + push(this.alternative); + } + push(this.body); + push(this.condition); + } +}, AST_StatementWithBody); + +/* -----[ SWITCH ]----- */ + +var AST_Switch = DEFNODE("Switch", "expression", { + $documentation: "A `switch` statement", + $propdoc: { + expression: "[AST_Node] the `switch` “discriminant”" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + push(this.expression); + } +}, AST_Block); + +var AST_SwitchBranch = DEFNODE("SwitchBranch", null, { + $documentation: "Base class for `switch` branches", +}, AST_Block); + +var AST_Default = DEFNODE("Default", null, { + $documentation: "A `default` switch branch", +}, AST_SwitchBranch); + +var AST_Case = DEFNODE("Case", "expression", { + $documentation: "A `case` switch branch", + $propdoc: { + expression: "[AST_Node] the `case` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + push(this.expression); + }, +}, AST_SwitchBranch); + +/* -----[ EXCEPTIONS ]----- */ + +var AST_Try = DEFNODE("Try", "bcatch bfinally", { + $documentation: "A `try` statement", + $propdoc: { + bcatch: "[AST_Catch?] the catch block, or null if not present", + bfinally: "[AST_Finally?] the finally block, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + walk_body(this, visitor); + if (this.bcatch) this.bcatch._walk(visitor); + if (this.bfinally) this.bfinally._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.bfinally) push(this.bfinally); + if (this.bcatch) push(this.bcatch); + let i = this.body.length; + while (i--) push(this.body[i]); + }, +}, AST_Block); + +var AST_Catch = DEFNODE("Catch", "argname", { + $documentation: "A `catch` node; only makes sense as part of a `try` statement", + $propdoc: { + argname: "[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.argname) this.argname._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + if (this.argname) push(this.argname); + }, +}, AST_Block); + +var AST_Finally = DEFNODE("Finally", null, { + $documentation: "A `finally` node; only makes sense as part of a `try` statement" +}, AST_Block); + +/* -----[ VAR/CONST ]----- */ + +var AST_Definitions = DEFNODE("Definitions", "definitions", { + $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", + $propdoc: { + definitions: "[AST_VarDef*] array of variable definitions" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var definitions = this.definitions; + for (var i = 0, len = definitions.length; i < len; i++) { + definitions[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.definitions.length; + while (i--) push(this.definitions[i]); + }, +}, AST_Statement); + +var AST_Var = DEFNODE("Var", null, { + $documentation: "A `var` statement" +}, AST_Definitions); + +var AST_Let = DEFNODE("Let", null, { + $documentation: "A `let` statement" +}, AST_Definitions); + +var AST_Const = DEFNODE("Const", null, { + $documentation: "A `const` statement" +}, AST_Definitions); + +var AST_VarDef = DEFNODE("VarDef", "name value", { + $documentation: "A variable declaration; only appears in a AST_Definitions node", + $propdoc: { + name: "[AST_Destructuring|AST_SymbolConst|AST_SymbolLet|AST_SymbolVar] name of the variable", + value: "[AST_Node?] initializer, or null of there's no initializer" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.name._walk(visitor); + if (this.value) this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value) push(this.value); + push(this.name); + }, +}); + +var AST_NameMapping = DEFNODE("NameMapping", "foreign_name name", { + $documentation: "The part of the export/import statement that declare names from a module.", + $propdoc: { + foreign_name: "[AST_SymbolExportForeign|AST_SymbolImportForeign] The name being exported/imported (as specified in the module)", + name: "[AST_SymbolExport|AST_SymbolImport] The name as it is visible to this module." + }, + _walk: function (visitor) { + return visitor._visit(this, function() { + this.foreign_name._walk(visitor); + this.name._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.name); + push(this.foreign_name); + }, +}); + +var AST_Import = DEFNODE("Import", "imported_name imported_names module_name assert_clause", { + $documentation: "An `import` statement", + $propdoc: { + imported_name: "[AST_SymbolImport] The name of the variable holding the module's default export.", + imported_names: "[AST_NameMapping*] The names of non-default imported variables", + module_name: "[AST_String] String literal describing where this module came from", + assert_clause: "[AST_Object?] The import assertion" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.imported_name) { + this.imported_name._walk(visitor); + } + if (this.imported_names) { + this.imported_names.forEach(function(name_import) { + name_import._walk(visitor); + }); + } + this.module_name._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.module_name); + if (this.imported_names) { + let i = this.imported_names.length; + while (i--) push(this.imported_names[i]); + } + if (this.imported_name) push(this.imported_name); + }, +}); + +var AST_ImportMeta = DEFNODE("ImportMeta", null, { + $documentation: "A reference to import.meta", +}); + +var AST_Export = DEFNODE("Export", "exported_definition exported_value is_default exported_names module_name assert_clause", { + $documentation: "An `export` statement", + $propdoc: { + exported_definition: "[AST_Defun|AST_Definitions|AST_DefClass?] An exported definition", + exported_value: "[AST_Node?] An exported value", + exported_names: "[AST_NameMapping*?] List of exported names", + module_name: "[AST_String?] Name of the file to load exports from", + is_default: "[Boolean] Whether this is the default exported value of this module", + assert_clause: "[AST_Object?] The import assertion" + }, + _walk: function (visitor) { + return visitor._visit(this, function () { + if (this.exported_definition) { + this.exported_definition._walk(visitor); + } + if (this.exported_value) { + this.exported_value._walk(visitor); + } + if (this.exported_names) { + this.exported_names.forEach(function(name_export) { + name_export._walk(visitor); + }); + } + if (this.module_name) { + this.module_name._walk(visitor); + } + }); + }, + _children_backwards(push) { + if (this.module_name) push(this.module_name); + if (this.exported_names) { + let i = this.exported_names.length; + while (i--) push(this.exported_names[i]); + } + if (this.exported_value) push(this.exported_value); + if (this.exported_definition) push(this.exported_definition); + } +}, AST_Statement); + +/* -----[ OTHER ]----- */ + +var AST_Call = DEFNODE("Call", "expression args optional _annotations", { + $documentation: "A function call expression", + $propdoc: { + expression: "[AST_Node] expression to invoke as function", + args: "[AST_Node*] array of arguments", + optional: "[boolean] whether this is an optional call (IE ?.() )", + _annotations: "[number] bitfield containing information about the call" + }, + initialize() { + if (this._annotations == null) this._annotations = 0; + }, + _walk(visitor) { + return visitor._visit(this, function() { + var args = this.args; + for (var i = 0, len = args.length; i < len; i++) { + args[i]._walk(visitor); + } + this.expression._walk(visitor); // TODO why do we need to crawl this last? + }); + }, + _children_backwards(push) { + let i = this.args.length; + while (i--) push(this.args[i]); + push(this.expression); + }, +}); + +var AST_New = DEFNODE("New", null, { + $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" +}, AST_Call); + +var AST_Sequence = DEFNODE("Sequence", "expressions", { + $documentation: "A sequence expression (comma-separated expressions)", + $propdoc: { + expressions: "[AST_Node*] array of expressions (at least two)" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expressions.forEach(function(node) { + node._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.expressions.length; + while (i--) push(this.expressions[i]); + }, +}); + +var AST_PropAccess = DEFNODE("PropAccess", "expression property optional", { + $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", + $propdoc: { + expression: "[AST_Node] the “container” expression", + property: "[AST_Node|string] the property to access. For AST_Dot & AST_DotHash this is always a plain string, while for AST_Sub it's an arbitrary AST_Node", + + optional: "[boolean] whether this is an optional property access (IE ?.)" + } +}); + +var AST_Dot = DEFNODE("Dot", "quote", { + $documentation: "A dotted property access expression", + $propdoc: { + quote: "[string] the original quote character when transformed from AST_Sub", + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}, AST_PropAccess); + +var AST_DotHash = DEFNODE("DotHash", "", { + $documentation: "A dotted property access to a private property", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}, AST_PropAccess); + +var AST_Sub = DEFNODE("Sub", null, { + $documentation: "Index-style property access, i.e. `a[\"foo\"]`", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + this.property._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.property); + push(this.expression); + }, +}, AST_PropAccess); + +var AST_Chain = DEFNODE("Chain", "expression", { + $documentation: "A chain expression like a?.b?.(c)?.[d]", + $propdoc: { + expression: "[AST_Call|AST_Dot|AST_DotHash|AST_Sub] chain element." + }, + _walk: function (visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Unary = DEFNODE("Unary", "operator expression", { + $documentation: "Base class for unary expressions", + $propdoc: { + operator: "[string] the operator", + expression: "[AST_Node] expression that this unary operator applies to" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, { + $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" +}, AST_Unary); + +var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, { + $documentation: "Unary postfix expression, i.e. `i++`" +}, AST_Unary); + +var AST_Binary = DEFNODE("Binary", "operator left right", { + $documentation: "Binary expression, i.e. `a + b`", + $propdoc: { + left: "[AST_Node] left-hand side expression", + operator: "[string] the operator", + right: "[AST_Node] right-hand side expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.left._walk(visitor); + this.right._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.right); + push(this.left); + }, +}); + +var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", { + $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", + $propdoc: { + condition: "[AST_Node]", + consequent: "[AST_Node]", + alternative: "[AST_Node]" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.consequent._walk(visitor); + this.alternative._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.alternative); + push(this.consequent); + push(this.condition); + }, +}); + +var AST_Assign = DEFNODE("Assign", "logical", { + $documentation: "An assignment expression — `a = b + 5`", + $propdoc: { + logical: "Whether it's a logical assignment" + } +}, AST_Binary); + +var AST_DefaultAssign = DEFNODE("DefaultAssign", null, { + $documentation: "A default assignment expression like in `(a = 3) => a`" +}, AST_Binary); + +/* -----[ LITERALS ]----- */ + +var AST_Array = DEFNODE("Array", "elements", { + $documentation: "An array literal", + $propdoc: { + elements: "[AST_Node*] array of elements" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var elements = this.elements; + for (var i = 0, len = elements.length; i < len; i++) { + elements[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.elements.length; + while (i--) push(this.elements[i]); + }, +}); + +var AST_Object = DEFNODE("Object", "properties", { + $documentation: "An object literal", + $propdoc: { + properties: "[AST_ObjectProperty*] array of properties" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var properties = this.properties; + for (var i = 0, len = properties.length; i < len; i++) { + properties[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.properties.length; + while (i--) push(this.properties[i]); + }, +}); + +var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { + $documentation: "Base class for literal object properties", + $propdoc: { + key: "[string|AST_Node] property name. For ObjectKeyVal this is a string. For getters, setters and computed property this is an AST_Node.", + value: "[AST_Node] property value. For getters and setters this is an AST_Accessor." + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.key instanceof AST_Node) + this.key._walk(visitor); + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.value); + if (this.key instanceof AST_Node) push(this.key); + } +}); + +var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", { + $documentation: "A key: value object property", + $propdoc: { + quote: "[string] the original quote character" + }, + computed_key() { + return this.key instanceof AST_Node; + } +}, AST_ObjectProperty); + +var AST_PrivateSetter = DEFNODE("PrivateSetter", "static", { + $propdoc: { + static: "[boolean] whether this is a static private setter" + }, + $documentation: "A private setter property", + computed_key() { + return false; + } +}, AST_ObjectProperty); + +var AST_PrivateGetter = DEFNODE("PrivateGetter", "static", { + $propdoc: { + static: "[boolean] whether this is a static private getter" + }, + $documentation: "A private getter property", + computed_key() { + return false; + } +}, AST_ObjectProperty); + +var AST_ObjectSetter = DEFNODE("ObjectSetter", "quote static", { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] whether this is a static setter (classes only)" + }, + $documentation: "An object setter property", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } +}, AST_ObjectProperty); + +var AST_ObjectGetter = DEFNODE("ObjectGetter", "quote static", { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] whether this is a static getter (classes only)" + }, + $documentation: "An object getter property", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } +}, AST_ObjectProperty); + +var AST_ConciseMethod = DEFNODE("ConciseMethod", "quote static is_generator async", { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] is this method static (classes only)", + is_generator: "[boolean] is this a generator method", + async: "[boolean] is this method async", + }, + $documentation: "An ES6 concise method inside an object or class", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } +}, AST_ObjectProperty); + +var AST_PrivateMethod = DEFNODE("PrivateMethod", "", { + $documentation: "A private class method inside a class", +}, AST_ConciseMethod); + +var AST_Class = DEFNODE("Class", "name extends properties", { + $propdoc: { + name: "[AST_SymbolClass|AST_SymbolDefClass?] optional class name.", + extends: "[AST_Node]? optional parent class", + properties: "[AST_ObjectProperty*] array of properties" + }, + $documentation: "An ES6 class", + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.name) { + this.name._walk(visitor); + } + if (this.extends) { + this.extends._walk(visitor); + } + this.properties.forEach((prop) => prop._walk(visitor)); + }); + }, + _children_backwards(push) { + let i = this.properties.length; + while (i--) push(this.properties[i]); + if (this.extends) push(this.extends); + if (this.name) push(this.name); + }, +}, AST_Scope /* TODO a class might have a scope but it's not a scope */); + +var AST_ClassProperty = DEFNODE("ClassProperty", "static quote", { + $documentation: "A class property", + $propdoc: { + static: "[boolean] whether this is a static key", + quote: "[string] which quote is being used" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.key instanceof AST_Node) + this.key._walk(visitor); + if (this.value instanceof AST_Node) + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value instanceof AST_Node) push(this.value); + if (this.key instanceof AST_Node) push(this.key); + }, + computed_key() { + return !(this.key instanceof AST_SymbolClassProperty); + } +}, AST_ObjectProperty); + +var AST_ClassPrivateProperty = DEFNODE("ClassPrivateProperty", "", { + $documentation: "A class property for a private property", +}, AST_ClassProperty); + +var AST_DefClass = DEFNODE("DefClass", null, { + $documentation: "A class definition", +}, AST_Class); + +var AST_ClassExpression = DEFNODE("ClassExpression", null, { + $documentation: "A class expression." +}, AST_Class); + +var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { + $propdoc: { + name: "[string] name of this symbol", + scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", + thedef: "[SymbolDef/S] the definition of this symbol" + }, + $documentation: "Base class for all symbols" +}); + +var AST_NewTarget = DEFNODE("NewTarget", null, { + $documentation: "A reference to new.target" +}); + +var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { + $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", +}, AST_Symbol); + +var AST_SymbolVar = DEFNODE("SymbolVar", null, { + $documentation: "Symbol defining a variable", +}, AST_SymbolDeclaration); + +var AST_SymbolBlockDeclaration = DEFNODE("SymbolBlockDeclaration", null, { + $documentation: "Base class for block-scoped declaration symbols" +}, AST_SymbolDeclaration); + +var AST_SymbolConst = DEFNODE("SymbolConst", null, { + $documentation: "A constant declaration" +}, AST_SymbolBlockDeclaration); + +var AST_SymbolLet = DEFNODE("SymbolLet", null, { + $documentation: "A block-scoped `let` declaration" +}, AST_SymbolBlockDeclaration); + +var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, { + $documentation: "Symbol naming a function argument", +}, AST_SymbolVar); + +var AST_SymbolDefun = DEFNODE("SymbolDefun", null, { + $documentation: "Symbol defining a function", +}, AST_SymbolDeclaration); + +var AST_SymbolMethod = DEFNODE("SymbolMethod", null, { + $documentation: "Symbol in an object defining a method", +}, AST_Symbol); + +var AST_SymbolClassProperty = DEFNODE("SymbolClassProperty", null, { + $documentation: "Symbol for a class property", +}, AST_Symbol); + +var AST_SymbolLambda = DEFNODE("SymbolLambda", null, { + $documentation: "Symbol naming a function expression", +}, AST_SymbolDeclaration); + +var AST_SymbolDefClass = DEFNODE("SymbolDefClass", null, { + $documentation: "Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class." +}, AST_SymbolBlockDeclaration); + +var AST_SymbolClass = DEFNODE("SymbolClass", null, { + $documentation: "Symbol naming a class's name. Lexically scoped to the class." +}, AST_SymbolDeclaration); + +var AST_SymbolCatch = DEFNODE("SymbolCatch", null, { + $documentation: "Symbol naming the exception in catch", +}, AST_SymbolBlockDeclaration); + +var AST_SymbolImport = DEFNODE("SymbolImport", null, { + $documentation: "Symbol referring to an imported name", +}, AST_SymbolBlockDeclaration); + +var AST_SymbolImportForeign = DEFNODE("SymbolImportForeign", null, { + $documentation: "A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes", +}, AST_Symbol); + +var AST_Label = DEFNODE("Label", "references", { + $documentation: "Symbol naming a label (declaration)", + $propdoc: { + references: "[AST_LoopControl*] a list of nodes referring to this label" + }, + initialize: function() { + this.references = []; + this.thedef = this; + } +}, AST_Symbol); + +var AST_SymbolRef = DEFNODE("SymbolRef", null, { + $documentation: "Reference to some symbol (not definition/declaration)", +}, AST_Symbol); + +var AST_SymbolExport = DEFNODE("SymbolExport", null, { + $documentation: "Symbol referring to a name to export", +}, AST_SymbolRef); + +var AST_SymbolExportForeign = DEFNODE("SymbolExportForeign", null, { + $documentation: "A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes", +}, AST_Symbol); + +var AST_LabelRef = DEFNODE("LabelRef", null, { + $documentation: "Reference to a label symbol", +}, AST_Symbol); + +var AST_This = DEFNODE("This", null, { + $documentation: "The `this` symbol", +}, AST_Symbol); + +var AST_Super = DEFNODE("Super", null, { + $documentation: "The `super` symbol", +}, AST_This); + +var AST_Constant = DEFNODE("Constant", null, { + $documentation: "Base class for all constants", + getValue: function() { + return this.value; + } +}); + +var AST_String = DEFNODE("String", "value quote", { + $documentation: "A string literal", + $propdoc: { + value: "[string] the contents of this string", + quote: "[string] the original quote character" + } +}, AST_Constant); + +var AST_Number = DEFNODE("Number", "value raw", { + $documentation: "A number literal", + $propdoc: { + value: "[number] the numeric value", + raw: "[string] numeric value as string" + } +}, AST_Constant); + +var AST_BigInt = DEFNODE("BigInt", "value", { + $documentation: "A big int literal", + $propdoc: { + value: "[string] big int value" + } +}, AST_Constant); + +var AST_RegExp = DEFNODE("RegExp", "value", { + $documentation: "A regexp literal", + $propdoc: { + value: "[RegExp] the actual regexp", + } +}, AST_Constant); + +var AST_Atom = DEFNODE("Atom", null, { + $documentation: "Base class for atoms", +}, AST_Constant); + +var AST_Null = DEFNODE("Null", null, { + $documentation: "The `null` atom", + value: null +}, AST_Atom); + +var AST_NaN = DEFNODE("NaN", null, { + $documentation: "The impossible value", + value: 0/0 +}, AST_Atom); + +var AST_Undefined = DEFNODE("Undefined", null, { + $documentation: "The `undefined` value", + value: (function() {}()) +}, AST_Atom); + +var AST_Hole = DEFNODE("Hole", null, { + $documentation: "A hole in an array", + value: (function() {}()) +}, AST_Atom); + +var AST_Infinity = DEFNODE("Infinity", null, { + $documentation: "The `Infinity` value", + value: 1/0 +}, AST_Atom); + +var AST_Boolean = DEFNODE("Boolean", null, { + $documentation: "Base class for booleans", +}, AST_Atom); + +var AST_False = DEFNODE("False", null, { + $documentation: "The `false` atom", + value: false +}, AST_Boolean); + +var AST_True = DEFNODE("True", null, { + $documentation: "The `true` atom", + value: true +}, AST_Boolean); + +/* -----[ Walk function ]---- */ + +/** + * Walk nodes in depth-first search fashion. + * Callback can return `walk_abort` symbol to stop iteration. + * It can also return `true` to stop iteration just for child nodes. + * Iteration can be stopped and continued by passing the `to_visit` argument, + * which is given to the callback in the second argument. + **/ +function walk(node, cb, to_visit = [node]) { + const push = to_visit.push.bind(to_visit); + while (to_visit.length) { + const node = to_visit.pop(); + const ret = cb(node, to_visit); + + if (ret) { + if (ret === walk_abort) return true; + continue; + } + + node._children_backwards(push); + } + return false; +} + +function walk_parent(node, cb, initial_stack) { + const to_visit = [node]; + const push = to_visit.push.bind(to_visit); + const stack = initial_stack ? initial_stack.slice() : []; + const parent_pop_indices = []; + + let current; + + const info = { + parent: (n = 0) => { + if (n === -1) { + return current; + } + + // [ p1 p0 ] [ 1 0 ] + if (initial_stack && n >= stack.length) { + n -= stack.length; + return initial_stack[ + initial_stack.length - (n + 1) + ]; + } + + return stack[stack.length - (1 + n)]; + }, + }; + + while (to_visit.length) { + current = to_visit.pop(); + + while ( + parent_pop_indices.length && + to_visit.length == parent_pop_indices[parent_pop_indices.length - 1] + ) { + stack.pop(); + parent_pop_indices.pop(); + } + + const ret = cb(current, info); + + if (ret) { + if (ret === walk_abort) return true; + continue; + } + + const visit_length = to_visit.length; + + current._children_backwards(push); + + // Push only if we're going to traverse the children + if (to_visit.length > visit_length) { + stack.push(current); + parent_pop_indices.push(visit_length - 1); + } + } + + return false; +} + +const walk_abort = Symbol("abort walk"); + +/* -----[ TreeWalker ]----- */ + +class TreeWalker { + constructor(callback) { + this.visit = callback; + this.stack = []; + this.directives = Object.create(null); + } + + _visit(node, descend) { + this.push(node); + var ret = this.visit(node, descend ? function() { + descend.call(node); + } : noop); + if (!ret && descend) { + descend.call(node); + } + this.pop(); + return ret; + } + + parent(n) { + return this.stack[this.stack.length - 2 - (n || 0)]; + } + + push(node) { + if (node instanceof AST_Lambda) { + this.directives = Object.create(this.directives); + } else if (node instanceof AST_Directive && !this.directives[node.value]) { + this.directives[node.value] = node; + } else if (node instanceof AST_Class) { + this.directives = Object.create(this.directives); + if (!this.directives["use strict"]) { + this.directives["use strict"] = node; + } + } + this.stack.push(node); + } + + pop() { + var node = this.stack.pop(); + if (node instanceof AST_Lambda || node instanceof AST_Class) { + this.directives = Object.getPrototypeOf(this.directives); + } + } + + self() { + return this.stack[this.stack.length - 1]; + } + + find_parent(type) { + var stack = this.stack; + for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof type) return x; + } + } + + has_directive(type) { + var dir = this.directives[type]; + if (dir) return dir; + var node = this.stack[this.stack.length - 1]; + if (node instanceof AST_Scope && node.body) { + for (var i = 0; i < node.body.length; ++i) { + var st = node.body[i]; + if (!(st instanceof AST_Directive)) break; + if (st.value == type) return st; + } + } + } + + loopcontrol_target(node) { + var stack = this.stack; + if (node.label) for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_LabeledStatement && x.label.name == node.label.name) + return x.body; + } else for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_IterationStatement + || node instanceof AST_Break && x instanceof AST_Switch) + return x; + } + } +} + +// Tree transformer helpers. +class TreeTransformer extends TreeWalker { + constructor(before, after) { + super(); + this.before = before; + this.after = after; + } +} + +const _PURE = 0b00000001; +const _INLINE = 0b00000010; +const _NOINLINE = 0b00000100; + +var ast = /*#__PURE__*/Object.freeze({ +__proto__: null, +AST_Accessor: AST_Accessor, +AST_Array: AST_Array, +AST_Arrow: AST_Arrow, +AST_Assign: AST_Assign, +AST_Atom: AST_Atom, +AST_Await: AST_Await, +AST_BigInt: AST_BigInt, +AST_Binary: AST_Binary, +AST_Block: AST_Block, +AST_BlockStatement: AST_BlockStatement, +AST_Boolean: AST_Boolean, +AST_Break: AST_Break, +AST_Call: AST_Call, +AST_Case: AST_Case, +AST_Catch: AST_Catch, +AST_Chain: AST_Chain, +AST_Class: AST_Class, +AST_ClassExpression: AST_ClassExpression, +AST_ClassPrivateProperty: AST_ClassPrivateProperty, +AST_ClassProperty: AST_ClassProperty, +AST_ConciseMethod: AST_ConciseMethod, +AST_Conditional: AST_Conditional, +AST_Const: AST_Const, +AST_Constant: AST_Constant, +AST_Continue: AST_Continue, +AST_Debugger: AST_Debugger, +AST_Default: AST_Default, +AST_DefaultAssign: AST_DefaultAssign, +AST_DefClass: AST_DefClass, +AST_Definitions: AST_Definitions, +AST_Defun: AST_Defun, +AST_Destructuring: AST_Destructuring, +AST_Directive: AST_Directive, +AST_Do: AST_Do, +AST_Dot: AST_Dot, +AST_DotHash: AST_DotHash, +AST_DWLoop: AST_DWLoop, +AST_EmptyStatement: AST_EmptyStatement, +AST_Exit: AST_Exit, +AST_Expansion: AST_Expansion, +AST_Export: AST_Export, +AST_False: AST_False, +AST_Finally: AST_Finally, +AST_For: AST_For, +AST_ForIn: AST_ForIn, +AST_ForOf: AST_ForOf, +AST_Function: AST_Function, +AST_Hole: AST_Hole, +AST_If: AST_If, +AST_Import: AST_Import, +AST_ImportMeta: AST_ImportMeta, +AST_Infinity: AST_Infinity, +AST_IterationStatement: AST_IterationStatement, +AST_Jump: AST_Jump, +AST_Label: AST_Label, +AST_LabeledStatement: AST_LabeledStatement, +AST_LabelRef: AST_LabelRef, +AST_Lambda: AST_Lambda, +AST_Let: AST_Let, +AST_LoopControl: AST_LoopControl, +AST_NameMapping: AST_NameMapping, +AST_NaN: AST_NaN, +AST_New: AST_New, +AST_NewTarget: AST_NewTarget, +AST_Node: AST_Node, +AST_Null: AST_Null, +AST_Number: AST_Number, +AST_Object: AST_Object, +AST_ObjectGetter: AST_ObjectGetter, +AST_ObjectKeyVal: AST_ObjectKeyVal, +AST_ObjectProperty: AST_ObjectProperty, +AST_ObjectSetter: AST_ObjectSetter, +AST_PrefixedTemplateString: AST_PrefixedTemplateString, +AST_PrivateGetter: AST_PrivateGetter, +AST_PrivateMethod: AST_PrivateMethod, +AST_PrivateSetter: AST_PrivateSetter, +AST_PropAccess: AST_PropAccess, +AST_RegExp: AST_RegExp, +AST_Return: AST_Return, +AST_Scope: AST_Scope, +AST_Sequence: AST_Sequence, +AST_SimpleStatement: AST_SimpleStatement, +AST_Statement: AST_Statement, +AST_StatementWithBody: AST_StatementWithBody, +AST_String: AST_String, +AST_Sub: AST_Sub, +AST_Super: AST_Super, +AST_Switch: AST_Switch, +AST_SwitchBranch: AST_SwitchBranch, +AST_Symbol: AST_Symbol, +AST_SymbolBlockDeclaration: AST_SymbolBlockDeclaration, +AST_SymbolCatch: AST_SymbolCatch, +AST_SymbolClass: AST_SymbolClass, +AST_SymbolClassProperty: AST_SymbolClassProperty, +AST_SymbolConst: AST_SymbolConst, +AST_SymbolDeclaration: AST_SymbolDeclaration, +AST_SymbolDefClass: AST_SymbolDefClass, +AST_SymbolDefun: AST_SymbolDefun, +AST_SymbolExport: AST_SymbolExport, +AST_SymbolExportForeign: AST_SymbolExportForeign, +AST_SymbolFunarg: AST_SymbolFunarg, +AST_SymbolImport: AST_SymbolImport, +AST_SymbolImportForeign: AST_SymbolImportForeign, +AST_SymbolLambda: AST_SymbolLambda, +AST_SymbolLet: AST_SymbolLet, +AST_SymbolMethod: AST_SymbolMethod, +AST_SymbolRef: AST_SymbolRef, +AST_SymbolVar: AST_SymbolVar, +AST_TemplateSegment: AST_TemplateSegment, +AST_TemplateString: AST_TemplateString, +AST_This: AST_This, +AST_Throw: AST_Throw, +AST_Token: AST_Token, +AST_Toplevel: AST_Toplevel, +AST_True: AST_True, +AST_Try: AST_Try, +AST_Unary: AST_Unary, +AST_UnaryPostfix: AST_UnaryPostfix, +AST_UnaryPrefix: AST_UnaryPrefix, +AST_Undefined: AST_Undefined, +AST_Var: AST_Var, +AST_VarDef: AST_VarDef, +AST_While: AST_While, +AST_With: AST_With, +AST_Yield: AST_Yield, +TreeTransformer: TreeTransformer, +TreeWalker: TreeWalker, +walk: walk, +walk_abort: walk_abort, +walk_body: walk_body, +walk_parent: walk_parent, +_INLINE: _INLINE, +_NOINLINE: _NOINLINE, +_PURE: _PURE +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +function def_transform(node, descend) { + node.DEFMETHOD("transform", function(tw, in_list) { + let transformed = undefined; + tw.push(this); + if (tw.before) transformed = tw.before(this, descend, in_list); + if (transformed === undefined) { + transformed = this; + descend(transformed, tw); + if (tw.after) { + const after_ret = tw.after(transformed, in_list); + if (after_ret !== undefined) transformed = after_ret; + } + } + tw.pop(); + return transformed; + }); +} + +function do_list(list, tw) { + return MAP(list, function(node) { + return node.transform(tw, true); + }); +} + +def_transform(AST_Node, noop); + +def_transform(AST_LabeledStatement, function(self, tw) { + self.label = self.label.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_SimpleStatement, function(self, tw) { + self.body = self.body.transform(tw); +}); + +def_transform(AST_Block, function(self, tw) { + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Do, function(self, tw) { + self.body = self.body.transform(tw); + self.condition = self.condition.transform(tw); +}); + +def_transform(AST_While, function(self, tw) { + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_For, function(self, tw) { + if (self.init) self.init = self.init.transform(tw); + if (self.condition) self.condition = self.condition.transform(tw); + if (self.step) self.step = self.step.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_ForIn, function(self, tw) { + self.init = self.init.transform(tw); + self.object = self.object.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_With, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_Exit, function(self, tw) { + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_LoopControl, function(self, tw) { + if (self.label) self.label = self.label.transform(tw); +}); + +def_transform(AST_If, function(self, tw) { + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + if (self.alternative) self.alternative = self.alternative.transform(tw); +}); + +def_transform(AST_Switch, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Case, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Try, function(self, tw) { + self.body = do_list(self.body, tw); + if (self.bcatch) self.bcatch = self.bcatch.transform(tw); + if (self.bfinally) self.bfinally = self.bfinally.transform(tw); +}); + +def_transform(AST_Catch, function(self, tw) { + if (self.argname) self.argname = self.argname.transform(tw); + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Definitions, function(self, tw) { + self.definitions = do_list(self.definitions, tw); +}); + +def_transform(AST_VarDef, function(self, tw) { + self.name = self.name.transform(tw); + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_Destructuring, function(self, tw) { + self.names = do_list(self.names, tw); +}); + +def_transform(AST_Lambda, function(self, tw) { + if (self.name) self.name = self.name.transform(tw); + self.argnames = do_list(self.argnames, tw); + if (self.body instanceof AST_Node) { + self.body = self.body.transform(tw); + } else { + self.body = do_list(self.body, tw); + } +}); + +def_transform(AST_Call, function(self, tw) { + self.expression = self.expression.transform(tw); + self.args = do_list(self.args, tw); +}); + +def_transform(AST_Sequence, function(self, tw) { + const result = do_list(self.expressions, tw); + self.expressions = result.length + ? result + : [new AST_Number({ value: 0 })]; +}); + +def_transform(AST_PropAccess, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Sub, function(self, tw) { + self.expression = self.expression.transform(tw); + self.property = self.property.transform(tw); +}); + +def_transform(AST_Chain, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Yield, function(self, tw) { + if (self.expression) self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Await, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Unary, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Binary, function(self, tw) { + self.left = self.left.transform(tw); + self.right = self.right.transform(tw); +}); + +def_transform(AST_Conditional, function(self, tw) { + self.condition = self.condition.transform(tw); + self.consequent = self.consequent.transform(tw); + self.alternative = self.alternative.transform(tw); +}); + +def_transform(AST_Array, function(self, tw) { + self.elements = do_list(self.elements, tw); +}); + +def_transform(AST_Object, function(self, tw) { + self.properties = do_list(self.properties, tw); +}); + +def_transform(AST_ObjectProperty, function(self, tw) { + if (self.key instanceof AST_Node) { + self.key = self.key.transform(tw); + } + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_Class, function(self, tw) { + if (self.name) self.name = self.name.transform(tw); + if (self.extends) self.extends = self.extends.transform(tw); + self.properties = do_list(self.properties, tw); +}); + +def_transform(AST_Expansion, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_NameMapping, function(self, tw) { + self.foreign_name = self.foreign_name.transform(tw); + self.name = self.name.transform(tw); +}); + +def_transform(AST_Import, function(self, tw) { + if (self.imported_name) self.imported_name = self.imported_name.transform(tw); + if (self.imported_names) do_list(self.imported_names, tw); + self.module_name = self.module_name.transform(tw); +}); + +def_transform(AST_Export, function(self, tw) { + if (self.exported_definition) self.exported_definition = self.exported_definition.transform(tw); + if (self.exported_value) self.exported_value = self.exported_value.transform(tw); + if (self.exported_names) do_list(self.exported_names, tw); + if (self.module_name) self.module_name = self.module_name.transform(tw); +}); + +def_transform(AST_TemplateString, function(self, tw) { + self.segments = do_list(self.segments, tw); +}); + +def_transform(AST_PrefixedTemplateString, function(self, tw) { + self.prefix = self.prefix.transform(tw); + self.template_string = self.template_string.transform(tw); +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +(function() { + + var normalize_directives = function(body) { + var in_directive = true; + + for (var i = 0; i < body.length; i++) { + if (in_directive && body[i] instanceof AST_Statement && body[i].body instanceof AST_String) { + body[i] = new AST_Directive({ + start: body[i].start, + end: body[i].end, + value: body[i].body.value + }); + } else if (in_directive && !(body[i] instanceof AST_Statement && body[i].body instanceof AST_String)) { + in_directive = false; + } + } + + return body; + }; + + const assert_clause_from_moz = (assertions) => { + if (assertions && assertions.length > 0) { + return new AST_Object({ + start: my_start_token(assertions), + end: my_end_token(assertions), + properties: assertions.map((assertion_kv) => + new AST_ObjectKeyVal({ + start: my_start_token(assertion_kv), + end: my_end_token(assertion_kv), + key: assertion_kv.key.name || assertion_kv.key.value, + value: from_moz(assertion_kv.value) + }) + ) + }); + } + return null; + }; + + var MOZ_TO_ME = { + Program: function(M) { + return new AST_Toplevel({ + start: my_start_token(M), + end: my_end_token(M), + body: normalize_directives(M.body.map(from_moz)) + }); + }, + ArrayPattern: function(M) { + return new AST_Destructuring({ + start: my_start_token(M), + end: my_end_token(M), + names: M.elements.map(function(elm) { + if (elm === null) { + return new AST_Hole(); + } + return from_moz(elm); + }), + is_array: true + }); + }, + ObjectPattern: function(M) { + return new AST_Destructuring({ + start: my_start_token(M), + end: my_end_token(M), + names: M.properties.map(from_moz), + is_array: false + }); + }, + AssignmentPattern: function(M) { + return new AST_DefaultAssign({ + start: my_start_token(M), + end: my_end_token(M), + left: from_moz(M.left), + operator: "=", + right: from_moz(M.right) + }); + }, + SpreadElement: function(M) { + return new AST_Expansion({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument) + }); + }, + RestElement: function(M) { + return new AST_Expansion({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument) + }); + }, + TemplateElement: function(M) { + return new AST_TemplateSegment({ + start: my_start_token(M), + end: my_end_token(M), + value: M.value.cooked, + raw: M.value.raw + }); + }, + TemplateLiteral: function(M) { + var segments = []; + for (var i = 0; i < M.quasis.length; i++) { + segments.push(from_moz(M.quasis[i])); + if (M.expressions[i]) { + segments.push(from_moz(M.expressions[i])); + } + } + return new AST_TemplateString({ + start: my_start_token(M), + end: my_end_token(M), + segments: segments + }); + }, + TaggedTemplateExpression: function(M) { + return new AST_PrefixedTemplateString({ + start: my_start_token(M), + end: my_end_token(M), + template_string: from_moz(M.quasi), + prefix: from_moz(M.tag) + }); + }, + FunctionDeclaration: function(M) { + return new AST_Defun({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + is_generator: M.generator, + async: M.async, + body: normalize_directives(from_moz(M.body).body) + }); + }, + FunctionExpression: function(M) { + return new AST_Function({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + is_generator: M.generator, + async: M.async, + body: normalize_directives(from_moz(M.body).body) + }); + }, + ArrowFunctionExpression: function(M) { + const body = M.body.type === "BlockStatement" + ? from_moz(M.body).body + : [make_node(AST_Return, {}, { value: from_moz(M.body) })]; + return new AST_Arrow({ + start: my_start_token(M), + end: my_end_token(M), + argnames: M.params.map(from_moz), + body, + async: M.async, + }); + }, + ExpressionStatement: function(M) { + return new AST_SimpleStatement({ + start: my_start_token(M), + end: my_end_token(M), + body: from_moz(M.expression) + }); + }, + TryStatement: function(M) { + var handlers = M.handlers || [M.handler]; + if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) { + throw new Error("Multiple catch clauses are not supported."); + } + return new AST_Try({ + start : my_start_token(M), + end : my_end_token(M), + body : from_moz(M.block).body, + bcatch : from_moz(handlers[0]), + bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null + }); + }, + Property: function(M) { + var key = M.key; + var args = { + start : my_start_token(key || M.value), + end : my_end_token(M.value), + key : key.type == "Identifier" ? key.name : key.value, + value : from_moz(M.value) + }; + if (M.computed) { + args.key = from_moz(M.key); + } + if (M.method) { + args.is_generator = M.value.generator; + args.async = M.value.async; + if (!M.computed) { + args.key = new AST_SymbolMethod({ name: args.key }); + } else { + args.key = from_moz(M.key); + } + return new AST_ConciseMethod(args); + } + if (M.kind == "init") { + if (key.type != "Identifier" && key.type != "Literal") { + args.key = from_moz(key); + } + return new AST_ObjectKeyVal(args); + } + if (typeof args.key === "string" || typeof args.key === "number") { + args.key = new AST_SymbolMethod({ + name: args.key + }); + } + args.value = new AST_Accessor(args.value); + if (M.kind == "get") return new AST_ObjectGetter(args); + if (M.kind == "set") return new AST_ObjectSetter(args); + if (M.kind == "method") { + args.async = M.value.async; + args.is_generator = M.value.generator; + args.quote = M.computed ? "\"" : null; + return new AST_ConciseMethod(args); + } + }, + MethodDefinition: function(M) { + var args = { + start : my_start_token(M), + end : my_end_token(M), + key : M.computed ? from_moz(M.key) : new AST_SymbolMethod({ name: M.key.name || M.key.value }), + value : from_moz(M.value), + static : M.static, + }; + if (M.kind == "get") { + return new AST_ObjectGetter(args); + } + if (M.kind == "set") { + return new AST_ObjectSetter(args); + } + args.is_generator = M.value.generator; + args.async = M.value.async; + return new AST_ConciseMethod(args); + }, + FieldDefinition: function(M) { + let key; + if (M.computed) { + key = from_moz(M.key); + } else { + if (M.key.type !== "Identifier") throw new Error("Non-Identifier key in FieldDefinition"); + key = from_moz(M.key); + } + return new AST_ClassProperty({ + start : my_start_token(M), + end : my_end_token(M), + key, + value : from_moz(M.value), + static : M.static, + }); + }, + PropertyDefinition: function(M) { + let key; + if (M.computed) { + key = from_moz(M.key); + } else { + if (M.key.type !== "Identifier") throw new Error("Non-Identifier key in PropertyDefinition"); + key = from_moz(M.key); + } + + return new AST_ClassProperty({ + start : my_start_token(M), + end : my_end_token(M), + key, + value : from_moz(M.value), + static : M.static, + }); + }, + ArrayExpression: function(M) { + return new AST_Array({ + start : my_start_token(M), + end : my_end_token(M), + elements : M.elements.map(function(elem) { + return elem === null ? new AST_Hole() : from_moz(elem); + }) + }); + }, + ObjectExpression: function(M) { + return new AST_Object({ + start : my_start_token(M), + end : my_end_token(M), + properties : M.properties.map(function(prop) { + if (prop.type === "SpreadElement") { + return from_moz(prop); + } + prop.type = "Property"; + return from_moz(prop); + }) + }); + }, + SequenceExpression: function(M) { + return new AST_Sequence({ + start : my_start_token(M), + end : my_end_token(M), + expressions: M.expressions.map(from_moz) + }); + }, + MemberExpression: function(M) { + return new (M.computed ? AST_Sub : AST_Dot)({ + start : my_start_token(M), + end : my_end_token(M), + property : M.computed ? from_moz(M.property) : M.property.name, + expression : from_moz(M.object), + optional : M.optional || false + }); + }, + ChainExpression: function(M) { + return new AST_Chain({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.expression) + }); + }, + SwitchCase: function(M) { + return new (M.test ? AST_Case : AST_Default)({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.test), + body : M.consequent.map(from_moz) + }); + }, + VariableDeclaration: function(M) { + return new (M.kind === "const" ? AST_Const : + M.kind === "let" ? AST_Let : AST_Var)({ + start : my_start_token(M), + end : my_end_token(M), + definitions : M.declarations.map(from_moz) + }); + }, + + ImportDeclaration: function(M) { + var imported_name = null; + var imported_names = null; + M.specifiers.forEach(function (specifier) { + if (specifier.type === "ImportSpecifier") { + if (!imported_names) { imported_names = []; } + imported_names.push(new AST_NameMapping({ + start: my_start_token(specifier), + end: my_end_token(specifier), + foreign_name: from_moz(specifier.imported), + name: from_moz(specifier.local) + })); + } else if (specifier.type === "ImportDefaultSpecifier") { + imported_name = from_moz(specifier.local); + } else if (specifier.type === "ImportNamespaceSpecifier") { + if (!imported_names) { imported_names = []; } + imported_names.push(new AST_NameMapping({ + start: my_start_token(specifier), + end: my_end_token(specifier), + foreign_name: new AST_SymbolImportForeign({ name: "*" }), + name: from_moz(specifier.local) + })); + } + }); + return new AST_Import({ + start : my_start_token(M), + end : my_end_token(M), + imported_name: imported_name, + imported_names : imported_names, + module_name : from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + ExportAllDeclaration: function(M) { + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_names: [ + new AST_NameMapping({ + name: new AST_SymbolExportForeign({ name: "*" }), + foreign_name: new AST_SymbolExportForeign({ name: "*" }) + }) + ], + module_name: from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + ExportNamedDeclaration: function(M) { + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_definition: from_moz(M.declaration), + exported_names: M.specifiers && M.specifiers.length ? M.specifiers.map(function (specifier) { + return new AST_NameMapping({ + foreign_name: from_moz(specifier.exported), + name: from_moz(specifier.local) + }); + }) : null, + module_name: from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + ExportDefaultDeclaration: function(M) { + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_value: from_moz(M.declaration), + is_default: true + }); + }, + Literal: function(M) { + var val = M.value, args = { + start : my_start_token(M), + end : my_end_token(M) + }; + var rx = M.regex; + if (rx && rx.pattern) { + // RegExpLiteral as per ESTree AST spec + args.value = { + source: rx.pattern, + flags: rx.flags + }; + return new AST_RegExp(args); + } else if (rx) { + // support legacy RegExp + const rx_source = M.raw || val; + const match = rx_source.match(/^\/(.*)\/(\w*)$/); + if (!match) throw new Error("Invalid regex source " + rx_source); + const [_, source, flags] = match; + args.value = { source, flags }; + return new AST_RegExp(args); + } + if (val === null) return new AST_Null(args); + switch (typeof val) { + case "string": + args.value = val; + return new AST_String(args); + case "number": + args.value = val; + args.raw = M.raw || val.toString(); + return new AST_Number(args); + case "boolean": + return new (val ? AST_True : AST_False)(args); + } + }, + MetaProperty: function(M) { + if (M.meta.name === "new" && M.property.name === "target") { + return new AST_NewTarget({ + start: my_start_token(M), + end: my_end_token(M) + }); + } else if (M.meta.name === "import" && M.property.name === "meta") { + return new AST_ImportMeta({ + start: my_start_token(M), + end: my_end_token(M) + }); + } + }, + Identifier: function(M) { + var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; + return new ( p.type == "LabeledStatement" ? AST_Label + : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : p.kind == "let" ? AST_SymbolLet : AST_SymbolVar) + : /Import.*Specifier/.test(p.type) ? (p.local === M ? AST_SymbolImport : AST_SymbolImportForeign) + : p.type == "ExportSpecifier" ? (p.local === M ? AST_SymbolExport : AST_SymbolExportForeign) + : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) + : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) + : p.type == "ArrowFunctionExpression" ? (p.params.includes(M)) ? AST_SymbolFunarg : AST_SymbolRef + : p.type == "ClassExpression" ? (p.id === M ? AST_SymbolClass : AST_SymbolRef) + : p.type == "Property" ? (p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolMethod) + : p.type == "PropertyDefinition" || p.type === "FieldDefinition" ? (p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolClassProperty) + : p.type == "ClassDeclaration" ? (p.id === M ? AST_SymbolDefClass : AST_SymbolRef) + : p.type == "MethodDefinition" ? (p.computed ? AST_SymbolRef : AST_SymbolMethod) + : p.type == "CatchClause" ? AST_SymbolCatch + : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef + : AST_SymbolRef)({ + start : my_start_token(M), + end : my_end_token(M), + name : M.name + }); + }, + BigIntLiteral(M) { + return new AST_BigInt({ + start : my_start_token(M), + end : my_end_token(M), + value : M.value + }); + } + }; + + MOZ_TO_ME.UpdateExpression = + MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) { + var prefix = "prefix" in M ? M.prefix + : M.type == "UnaryExpression" ? true : false; + return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ + start : my_start_token(M), + end : my_end_token(M), + operator : M.operator, + expression : from_moz(M.argument) + }); + }; + + MOZ_TO_ME.ClassDeclaration = + MOZ_TO_ME.ClassExpression = function From_Moz_Class(M) { + return new (M.type === "ClassDeclaration" ? AST_DefClass : AST_ClassExpression)({ + start : my_start_token(M), + end : my_end_token(M), + name : from_moz(M.id), + extends : from_moz(M.superClass), + properties: M.body.body.map(from_moz) + }); + }; + + map("EmptyStatement", AST_EmptyStatement); + map("BlockStatement", AST_BlockStatement, "body@body"); + map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"); + map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"); + map("BreakStatement", AST_Break, "label>label"); + map("ContinueStatement", AST_Continue, "label>label"); + map("WithStatement", AST_With, "object>expression, body>body"); + map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"); + map("ReturnStatement", AST_Return, "argument>value"); + map("ThrowStatement", AST_Throw, "argument>value"); + map("WhileStatement", AST_While, "test>condition, body>body"); + map("DoWhileStatement", AST_Do, "test>condition, body>body"); + map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"); + map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"); + map("ForOfStatement", AST_ForOf, "left>init, right>object, body>body, await=await"); + map("AwaitExpression", AST_Await, "argument>expression"); + map("YieldExpression", AST_Yield, "argument>expression, delegate=is_star"); + map("DebuggerStatement", AST_Debugger); + map("VariableDeclarator", AST_VarDef, "id>name, init>value"); + map("CatchClause", AST_Catch, "param>argname, body%body"); + + map("ThisExpression", AST_This); + map("Super", AST_Super); + map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"); + map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"); + map("NewExpression", AST_New, "callee>expression, arguments@args"); + map("CallExpression", AST_Call, "callee>expression, optional=optional, arguments@args"); + + def_to_moz(AST_Toplevel, function To_Moz_Program(M) { + return to_moz_scope("Program", M); + }); + + def_to_moz(AST_Expansion, function To_Moz_Spread(M) { + return { + type: to_moz_in_destructuring() ? "RestElement" : "SpreadElement", + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_PrefixedTemplateString, function To_Moz_TaggedTemplateExpression(M) { + return { + type: "TaggedTemplateExpression", + tag: to_moz(M.prefix), + quasi: to_moz(M.template_string) + }; + }); + + def_to_moz(AST_TemplateString, function To_Moz_TemplateLiteral(M) { + var quasis = []; + var expressions = []; + for (var i = 0; i < M.segments.length; i++) { + if (i % 2 !== 0) { + expressions.push(to_moz(M.segments[i])); + } else { + quasis.push({ + type: "TemplateElement", + value: { + raw: M.segments[i].raw, + cooked: M.segments[i].value + }, + tail: i === M.segments.length - 1 + }); + } + } + return { + type: "TemplateLiteral", + quasis: quasis, + expressions: expressions + }; + }); + + def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) { + return { + type: "FunctionDeclaration", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + generator: M.is_generator, + async: M.async, + body: to_moz_scope("BlockStatement", M) + }; + }); + + def_to_moz(AST_Function, function To_Moz_FunctionExpression(M, parent) { + var is_generator = parent.is_generator !== undefined ? + parent.is_generator : M.is_generator; + return { + type: "FunctionExpression", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + generator: is_generator, + async: M.async, + body: to_moz_scope("BlockStatement", M) + }; + }); + + def_to_moz(AST_Arrow, function To_Moz_ArrowFunctionExpression(M) { + var body = { + type: "BlockStatement", + body: M.body.map(to_moz) + }; + return { + type: "ArrowFunctionExpression", + params: M.argnames.map(to_moz), + async: M.async, + body: body + }; + }); + + def_to_moz(AST_Destructuring, function To_Moz_ObjectPattern(M) { + if (M.is_array) { + return { + type: "ArrayPattern", + elements: M.names.map(to_moz) + }; + } + return { + type: "ObjectPattern", + properties: M.names.map(to_moz) + }; + }); + + def_to_moz(AST_Directive, function To_Moz_Directive(M) { + return { + type: "ExpressionStatement", + expression: { + type: "Literal", + value: M.value, + raw: M.print_to_string() + }, + directive: M.value + }; + }); + + def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) { + return { + type: "ExpressionStatement", + expression: to_moz(M.body) + }; + }); + + def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) { + return { + type: "SwitchCase", + test: to_moz(M.expression), + consequent: M.body.map(to_moz) + }; + }); + + def_to_moz(AST_Try, function To_Moz_TryStatement(M) { + return { + type: "TryStatement", + block: to_moz_block(M), + handler: to_moz(M.bcatch), + guardedHandlers: [], + finalizer: to_moz(M.bfinally) + }; + }); + + def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { + return { + type: "CatchClause", + param: to_moz(M.argname), + guard: null, + body: to_moz_block(M) + }; + }); + + def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) { + return { + type: "VariableDeclaration", + kind: + M instanceof AST_Const ? "const" : + M instanceof AST_Let ? "let" : "var", + declarations: M.definitions.map(to_moz) + }; + }); + + const assert_clause_to_moz = assert_clause => { + const assertions = []; + if (assert_clause) { + for (const { key, value } of assert_clause.properties) { + const key_moz = is_basic_identifier_string(key) + ? { type: "Identifier", name: key } + : { type: "Literal", value: key, raw: JSON.stringify(key) }; + assertions.push({ + type: "ImportAttribute", + key: key_moz, + value: to_moz(value) + }); + } + } + return assertions; + }; + + def_to_moz(AST_Export, function To_Moz_ExportDeclaration(M) { + if (M.exported_names) { + if (M.exported_names[0].name.name === "*") { + return { + type: "ExportAllDeclaration", + source: to_moz(M.module_name), + assertions: assert_clause_to_moz(M.assert_clause) + }; + } + return { + type: "ExportNamedDeclaration", + specifiers: M.exported_names.map(function (name_mapping) { + return { + type: "ExportSpecifier", + exported: to_moz(name_mapping.foreign_name), + local: to_moz(name_mapping.name) + }; + }), + declaration: to_moz(M.exported_definition), + source: to_moz(M.module_name), + assertions: assert_clause_to_moz(M.assert_clause) + }; + } + return { + type: M.is_default ? "ExportDefaultDeclaration" : "ExportNamedDeclaration", + declaration: to_moz(M.exported_value || M.exported_definition) + }; + }); + + def_to_moz(AST_Import, function To_Moz_ImportDeclaration(M) { + var specifiers = []; + if (M.imported_name) { + specifiers.push({ + type: "ImportDefaultSpecifier", + local: to_moz(M.imported_name) + }); + } + if (M.imported_names && M.imported_names[0].foreign_name.name === "*") { + specifiers.push({ + type: "ImportNamespaceSpecifier", + local: to_moz(M.imported_names[0].name) + }); + } else if (M.imported_names) { + M.imported_names.forEach(function(name_mapping) { + specifiers.push({ + type: "ImportSpecifier", + local: to_moz(name_mapping.name), + imported: to_moz(name_mapping.foreign_name) + }); + }); + } + return { + type: "ImportDeclaration", + specifiers: specifiers, + source: to_moz(M.module_name), + assertions: assert_clause_to_moz(M.assert_clause) + }; + }); + + def_to_moz(AST_ImportMeta, function To_Moz_MetaProperty() { + return { + type: "MetaProperty", + meta: { + type: "Identifier", + name: "import" + }, + property: { + type: "Identifier", + name: "meta" + } + }; + }); + + def_to_moz(AST_Sequence, function To_Moz_SequenceExpression(M) { + return { + type: "SequenceExpression", + expressions: M.expressions.map(to_moz) + }; + }); + + def_to_moz(AST_DotHash, function To_Moz_PrivateMemberExpression(M) { + return { + type: "MemberExpression", + object: to_moz(M.expression), + computed: false, + property: { + type: "PrivateIdentifier", + name: M.property + }, + optional: M.optional + }; + }); + + def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) { + var isComputed = M instanceof AST_Sub; + return { + type: "MemberExpression", + object: to_moz(M.expression), + computed: isComputed, + property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}, + optional: M.optional + }; + }); + + def_to_moz(AST_Chain, function To_Moz_ChainExpression(M) { + return { + type: "ChainExpression", + expression: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Unary, function To_Moz_Unary(M) { + return { + type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression", + operator: M.operator, + prefix: M instanceof AST_UnaryPrefix, + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { + if (M.operator == "=" && to_moz_in_destructuring()) { + return { + type: "AssignmentPattern", + left: to_moz(M.left), + right: to_moz(M.right) + }; + } + + const type = M.operator == "&&" || M.operator == "||" || M.operator === "??" + ? "LogicalExpression" + : "BinaryExpression"; + + return { + type, + left: to_moz(M.left), + operator: M.operator, + right: to_moz(M.right) + }; + }); + + def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) { + return { + type: "ArrayExpression", + elements: M.elements.map(to_moz) + }; + }); + + def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) { + return { + type: "ObjectExpression", + properties: M.properties.map(to_moz) + }; + }); + + def_to_moz(AST_ObjectProperty, function To_Moz_Property(M, parent) { + var key = M.key instanceof AST_Node ? to_moz(M.key) : { + type: "Identifier", + value: M.key + }; + if (typeof M.key === "number") { + key = { + type: "Literal", + value: Number(M.key) + }; + } + if (typeof M.key === "string") { + key = { + type: "Identifier", + name: M.key + }; + } + var kind; + var string_or_num = typeof M.key === "string" || typeof M.key === "number"; + var computed = string_or_num ? false : !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef; + if (M instanceof AST_ObjectKeyVal) { + kind = "init"; + computed = !string_or_num; + } else + if (M instanceof AST_ObjectGetter) { + kind = "get"; + } else + if (M instanceof AST_ObjectSetter) { + kind = "set"; + } + if (M instanceof AST_PrivateGetter || M instanceof AST_PrivateSetter) { + const kind = M instanceof AST_PrivateGetter ? "get" : "set"; + return { + type: "MethodDefinition", + computed: false, + kind: kind, + static: M.static, + key: { + type: "PrivateIdentifier", + name: M.key.name + }, + value: to_moz(M.value) + }; + } + if (M instanceof AST_ClassPrivateProperty) { + return { + type: "PropertyDefinition", + key: { + type: "PrivateIdentifier", + name: M.key.name + }, + value: to_moz(M.value), + computed: false, + static: M.static + }; + } + if (M instanceof AST_ClassProperty) { + return { + type: "PropertyDefinition", + key, + value: to_moz(M.value), + computed, + static: M.static + }; + } + if (parent instanceof AST_Class) { + return { + type: "MethodDefinition", + computed: computed, + kind: kind, + static: M.static, + key: to_moz(M.key), + value: to_moz(M.value) + }; + } + return { + type: "Property", + computed: computed, + kind: kind, + key: key, + value: to_moz(M.value) + }; + }); + + def_to_moz(AST_ConciseMethod, function To_Moz_MethodDefinition(M, parent) { + if (parent instanceof AST_Object) { + return { + type: "Property", + computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef, + kind: "init", + method: true, + shorthand: false, + key: to_moz(M.key), + value: to_moz(M.value) + }; + } + + const key = M instanceof AST_PrivateMethod + ? { + type: "PrivateIdentifier", + name: M.key.name + } + : to_moz(M.key); + + return { + type: "MethodDefinition", + kind: M.key === "constructor" ? "constructor" : "method", + key, + value: to_moz(M.value), + computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef, + static: M.static, + }; + }); + + def_to_moz(AST_Class, function To_Moz_Class(M) { + var type = M instanceof AST_ClassExpression ? "ClassExpression" : "ClassDeclaration"; + return { + type: type, + superClass: to_moz(M.extends), + id: M.name ? to_moz(M.name) : null, + body: { + type: "ClassBody", + body: M.properties.map(to_moz) + } + }; + }); + + def_to_moz(AST_NewTarget, function To_Moz_MetaProperty() { + return { + type: "MetaProperty", + meta: { + type: "Identifier", + name: "new" + }, + property: { + type: "Identifier", + name: "target" + } + }; + }); + + def_to_moz(AST_Symbol, function To_Moz_Identifier(M, parent) { + if (M instanceof AST_SymbolMethod && parent.quote) { + return { + type: "Literal", + value: M.name + }; + } + var def = M.definition(); + return { + type: "Identifier", + name: def ? def.mangled_name || def.name : M.name + }; + }); + + def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) { + const pattern = M.value.source; + const flags = M.value.flags; + return { + type: "Literal", + value: null, + raw: M.print_to_string(), + regex: { pattern, flags } + }; + }); + + def_to_moz(AST_Constant, function To_Moz_Literal(M) { + var value = M.value; + return { + type: "Literal", + value: value, + raw: M.raw || M.print_to_string() + }; + }); + + def_to_moz(AST_Atom, function To_Moz_Atom(M) { + return { + type: "Identifier", + name: String(M.value) + }; + }); + + def_to_moz(AST_BigInt, M => ({ + type: "BigIntLiteral", + value: M.value + })); + + AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null; }); + + AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast); + AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast); + + /* -----[ tools ]----- */ + + function my_start_token(moznode) { + var loc = moznode.loc, start = loc && loc.start; + var range = moznode.range; + return new AST_Token( + "", + "", + start && start.line || 0, + start && start.column || 0, + range ? range [0] : moznode.start, + false, + [], + [], + loc && loc.source, + ); + } + + function my_end_token(moznode) { + var loc = moznode.loc, end = loc && loc.end; + var range = moznode.range; + return new AST_Token( + "", + "", + end && end.line || 0, + end && end.column || 0, + range ? range [0] : moznode.end, + false, + [], + [], + loc && loc.source, + ); + } + + function map(moztype, mytype, propmap) { + var moz_to_me = "function From_Moz_" + moztype + "(M){\n"; + moz_to_me += "return new U2." + mytype.name + "({\n" + + "start: my_start_token(M),\n" + + "end: my_end_token(M)"; + + var me_to_moz = "function To_Moz_" + moztype + "(M){\n"; + me_to_moz += "return {\n" + + "type: " + JSON.stringify(moztype); + + if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop) { + var m = /([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(prop); + if (!m) throw new Error("Can't understand property map: " + prop); + var moz = m[1], how = m[2], my = m[3]; + moz_to_me += ",\n" + my + ": "; + me_to_moz += ",\n" + moz + ": "; + switch (how) { + case "@": + moz_to_me += "M." + moz + ".map(from_moz)"; + me_to_moz += "M." + my + ".map(to_moz)"; + break; + case ">": + moz_to_me += "from_moz(M." + moz + ")"; + me_to_moz += "to_moz(M." + my + ")"; + break; + case "=": + moz_to_me += "M." + moz; + me_to_moz += "M." + my; + break; + case "%": + moz_to_me += "from_moz(M." + moz + ").body"; + me_to_moz += "to_moz_block(M)"; + break; + default: + throw new Error("Can't understand operator in propmap: " + prop); + } + }); + + moz_to_me += "\n})\n}"; + me_to_moz += "\n}\n}"; + + moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")( + ast, my_start_token, my_end_token, from_moz + ); + me_to_moz = new Function("to_moz", "to_moz_block", "to_moz_scope", "return(" + me_to_moz + ")")( + to_moz, to_moz_block, to_moz_scope + ); + MOZ_TO_ME[moztype] = moz_to_me; + def_to_moz(mytype, me_to_moz); + } + + var FROM_MOZ_STACK = null; + + function from_moz(node) { + FROM_MOZ_STACK.push(node); + var ret = node != null ? MOZ_TO_ME[node.type](node) : null; + FROM_MOZ_STACK.pop(); + return ret; + } + + AST_Node.from_mozilla_ast = function(node) { + var save_stack = FROM_MOZ_STACK; + FROM_MOZ_STACK = []; + var ast = from_moz(node); + FROM_MOZ_STACK = save_stack; + return ast; + }; + + function set_moz_loc(mynode, moznode) { + var start = mynode.start; + var end = mynode.end; + if (!(start && end)) { + return moznode; + } + if (start.pos != null && end.endpos != null) { + moznode.range = [start.pos, end.endpos]; + } + if (start.line) { + moznode.loc = { + start: {line: start.line, column: start.col}, + end: end.endline ? {line: end.endline, column: end.endcol} : null + }; + if (start.file) { + moznode.loc.source = start.file; + } + } + return moznode; + } + + function def_to_moz(mytype, handler) { + mytype.DEFMETHOD("to_mozilla_ast", function(parent) { + return set_moz_loc(this, handler(this, parent)); + }); + } + + var TO_MOZ_STACK = null; + + function to_moz(node) { + if (TO_MOZ_STACK === null) { TO_MOZ_STACK = []; } + TO_MOZ_STACK.push(node); + var ast = node != null ? node.to_mozilla_ast(TO_MOZ_STACK[TO_MOZ_STACK.length - 2]) : null; + TO_MOZ_STACK.pop(); + if (TO_MOZ_STACK.length === 0) { TO_MOZ_STACK = null; } + return ast; + } + + function to_moz_in_destructuring() { + var i = TO_MOZ_STACK.length; + while (i--) { + if (TO_MOZ_STACK[i] instanceof AST_Destructuring) { + return true; + } + } + return false; + } + + function to_moz_block(node) { + return { + type: "BlockStatement", + body: node.body.map(to_moz) + }; + } + + function to_moz_scope(type, node) { + var body = node.body.map(to_moz); + if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) { + body.unshift(to_moz(new AST_EmptyStatement(node.body[0]))); + } + return { + type: type, + body: body + }; + } +})(); + +// return true if the node at the top of the stack (that means the +// innermost node in the current output) is lexically the first in +// a statement. +function first_in_statement(stack) { + let node = stack.parent(-1); + for (let i = 0, p; p = stack.parent(i); i++) { + if (p instanceof AST_Statement && p.body === node) + return true; + if ((p instanceof AST_Sequence && p.expressions[0] === node) || + (p.TYPE === "Call" && p.expression === node) || + (p instanceof AST_PrefixedTemplateString && p.prefix === node) || + (p instanceof AST_Dot && p.expression === node) || + (p instanceof AST_Sub && p.expression === node) || + (p instanceof AST_Conditional && p.condition === node) || + (p instanceof AST_Binary && p.left === node) || + (p instanceof AST_UnaryPostfix && p.expression === node) + ) { + node = p; + } else { + return false; + } + } +} + +// Returns whether the leftmost item in the expression is an object +function left_is_object(node) { + if (node instanceof AST_Object) return true; + if (node instanceof AST_Sequence) return left_is_object(node.expressions[0]); + if (node.TYPE === "Call") return left_is_object(node.expression); + if (node instanceof AST_PrefixedTemplateString) return left_is_object(node.prefix); + if (node instanceof AST_Dot || node instanceof AST_Sub) return left_is_object(node.expression); + if (node instanceof AST_Conditional) return left_is_object(node.condition); + if (node instanceof AST_Binary) return left_is_object(node.left); + if (node instanceof AST_UnaryPostfix) return left_is_object(node.expression); + return false; +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +const EXPECT_DIRECTIVE = /^$|[;{][\s\n]*$/; +const CODE_LINE_BREAK = 10; +const CODE_SPACE = 32; + +const r_annotation = /[@#]__(PURE|INLINE|NOINLINE)__/g; + +function is_some_comments(comment) { + // multiline comment + return ( + (comment.type === "comment2" || comment.type === "comment1") + && /@preserve|@copyright|@lic|@cc_on|^\**!/i.test(comment.value) + ); +} + +class Rope { + constructor() { + this.committed = ""; + this.current = ""; + } + + append(str) { + this.current += str; + } + + insertAt(char, index) { + const { committed, current } = this; + if (index < committed.length) { + this.committed = committed.slice(0, index) + char + committed.slice(index); + } else if (index === committed.length) { + this.committed += char; + } else { + index -= committed.length; + this.committed += current.slice(0, index) + char; + this.current = current.slice(index); + } + } + + charAt(index) { + const { committed } = this; + if (index < committed.length) return committed[index]; + return this.current[index - committed.length]; + } + + curLength() { + return this.current.length; + } + + length() { + return this.committed.length + this.current.length; + } + + toString() { + return this.committed + this.current; + } +} + +function OutputStream(options) { + + var readonly = !options; + options = defaults(options, { + ascii_only : false, + beautify : false, + braces : false, + comments : "some", + ecma : 5, + ie8 : false, + indent_level : 4, + indent_start : 0, + inline_script : true, + keep_numbers : false, + keep_quoted_props : false, + max_line_len : false, + preamble : null, + preserve_annotations : false, + quote_keys : false, + quote_style : 0, + safari10 : false, + semicolons : true, + shebang : true, + shorthand : undefined, + source_map : null, + webkit : false, + width : 80, + wrap_iife : false, + wrap_func_args : true, + }, true); + + if (options.shorthand === undefined) + options.shorthand = options.ecma > 5; + + // Convert comment option to RegExp if neccessary and set up comments filter + var comment_filter = return_false; // Default case, throw all comments away + if (options.comments) { + let comments = options.comments; + if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) { + var regex_pos = options.comments.lastIndexOf("/"); + comments = new RegExp( + options.comments.substr(1, regex_pos - 1), + options.comments.substr(regex_pos + 1) + ); + } + if (comments instanceof RegExp) { + comment_filter = function(comment) { + return comment.type != "comment5" && comments.test(comment.value); + }; + } else if (typeof comments === "function") { + comment_filter = function(comment) { + return comment.type != "comment5" && comments(this, comment); + }; + } else if (comments === "some") { + comment_filter = is_some_comments; + } else { // NOTE includes "all" option + comment_filter = return_true; + } + } + + var indentation = 0; + var current_col = 0; + var current_line = 1; + var current_pos = 0; + var OUTPUT = new Rope(); + let printed_comments = new Set(); + + var to_utf8 = options.ascii_only ? function(str, identifier = false, regexp = false) { + if (options.ecma >= 2015 && !options.safari10 && !regexp) { + str = str.replace(/[\ud800-\udbff][\udc00-\udfff]/g, function(ch) { + var code = get_full_char_code(ch, 0).toString(16); + return "\\u{" + code + "}"; + }); + } + return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) { + var code = ch.charCodeAt(0).toString(16); + if (code.length <= 2 && !identifier) { + while (code.length < 2) code = "0" + code; + return "\\x" + code; + } else { + while (code.length < 4) code = "0" + code; + return "\\u" + code; + } + }); + } : function(str) { + return str.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g, function(match, lone) { + if (lone) { + return "\\u" + lone.charCodeAt(0).toString(16); + } + return match; + }); + }; + + function make_string(str, quote) { + var dq = 0, sq = 0; + str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, + function(s, i) { + switch (s) { + case '"': ++dq; return '"'; + case "'": ++sq; return "'"; + case "\\": return "\\\\"; + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\t": return "\\t"; + case "\b": return "\\b"; + case "\f": return "\\f"; + case "\x0B": return options.ie8 ? "\\x0B" : "\\v"; + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + case "\ufeff": return "\\ufeff"; + case "\0": + return /[0-9]/.test(get_full_char(str, i+1)) ? "\\x00" : "\\0"; + } + return s; + }); + function quote_single() { + return "'" + str.replace(/\x27/g, "\\'") + "'"; + } + function quote_double() { + return '"' + str.replace(/\x22/g, '\\"') + '"'; + } + function quote_template() { + return "`" + str.replace(/`/g, "\\`") + "`"; + } + str = to_utf8(str); + if (quote === "`") return quote_template(); + switch (options.quote_style) { + case 1: + return quote_single(); + case 2: + return quote_double(); + case 3: + return quote == "'" ? quote_single() : quote_double(); + default: + return dq > sq ? quote_single() : quote_double(); + } + } + + function encode_string(str, quote) { + var ret = make_string(str, quote); + if (options.inline_script) { + ret = ret.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2"); + ret = ret.replace(/\x3c!--/g, "\\x3c!--"); + ret = ret.replace(/--\x3e/g, "--\\x3e"); + } + return ret; + } + + function make_name(name) { + name = name.toString(); + name = to_utf8(name, true); + return name; + } + + function make_indent(back) { + return " ".repeat(options.indent_start + indentation - back * options.indent_level); + } + + /* -----[ beautification/minification ]----- */ + + var has_parens = false; + var might_need_space = false; + var might_need_semicolon = false; + var might_add_newline = 0; + var need_newline_indented = false; + var need_space = false; + var newline_insert = -1; + var last = ""; + var mapping_token, mapping_name, mappings = options.source_map && []; + + var do_add_mapping = mappings ? function() { + mappings.forEach(function(mapping) { + try { + let { name, token } = mapping; + if (token.type == "name" || token.type === "privatename") { + name = token.value; + } else if (name instanceof AST_Symbol) { + name = token.type === "string" ? token.value : name.name; + } + options.source_map.add( + mapping.token.file, + mapping.line, mapping.col, + mapping.token.line, mapping.token.col, + is_basic_identifier_string(name) ? name : undefined + ); + } catch(ex) { + // Ignore bad mapping + } + }); + mappings = []; + } : noop; + + var ensure_line_len = options.max_line_len ? function() { + if (current_col > options.max_line_len) { + if (might_add_newline) { + OUTPUT.insertAt("\n", might_add_newline); + const curLength = OUTPUT.curLength(); + if (mappings) { + var delta = curLength - current_col; + mappings.forEach(function(mapping) { + mapping.line++; + mapping.col += delta; + }); + } + current_line++; + current_pos++; + current_col = curLength; + } + } + if (might_add_newline) { + might_add_newline = 0; + do_add_mapping(); + } + } : noop; + + var requireSemicolonChars = makePredicate("( [ + * / - , . `"); + + function print(str) { + str = String(str); + var ch = get_full_char(str, 0); + if (need_newline_indented && ch) { + need_newline_indented = false; + if (ch !== "\n") { + print("\n"); + indent(); + } + } + if (need_space && ch) { + need_space = false; + if (!/[\s;})]/.test(ch)) { + space(); + } + } + newline_insert = -1; + var prev = last.charAt(last.length - 1); + if (might_need_semicolon) { + might_need_semicolon = false; + + if (prev === ":" && ch === "}" || (!ch || !";}".includes(ch)) && prev !== ";") { + if (options.semicolons || requireSemicolonChars.has(ch)) { + OUTPUT.append(";"); + current_col++; + current_pos++; + } else { + ensure_line_len(); + if (current_col > 0) { + OUTPUT.append("\n"); + current_pos++; + current_line++; + current_col = 0; + } + + if (/^\s+$/.test(str)) { + // reset the semicolon flag, since we didn't print one + // now and might still have to later + might_need_semicolon = true; + } + } + + if (!options.beautify) + might_need_space = false; + } + } + + if (might_need_space) { + if ((is_identifier_char(prev) + && (is_identifier_char(ch) || ch == "\\")) + || (ch == "/" && ch == prev) + || ((ch == "+" || ch == "-") && ch == last) + ) { + OUTPUT.append(" "); + current_col++; + current_pos++; + } + might_need_space = false; + } + + if (mapping_token) { + mappings.push({ + token: mapping_token, + name: mapping_name, + line: current_line, + col: current_col + }); + mapping_token = false; + if (!might_add_newline) do_add_mapping(); + } + + OUTPUT.append(str); + has_parens = str[str.length - 1] == "("; + current_pos += str.length; + var a = str.split(/\r?\n/), n = a.length - 1; + current_line += n; + current_col += a[0].length; + if (n > 0) { + ensure_line_len(); + current_col = a[n].length; + } + last = str; + } + + var star = function() { + print("*"); + }; + + var space = options.beautify ? function() { + print(" "); + } : function() { + might_need_space = true; + }; + + var indent = options.beautify ? function(half) { + if (options.beautify) { + print(make_indent(half ? 0.5 : 0)); + } + } : noop; + + var with_indent = options.beautify ? function(col, cont) { + if (col === true) col = next_indent(); + var save_indentation = indentation; + indentation = col; + var ret = cont(); + indentation = save_indentation; + return ret; + } : function(col, cont) { return cont(); }; + + var newline = options.beautify ? function() { + if (newline_insert < 0) return print("\n"); + if (OUTPUT.charAt(newline_insert) != "\n") { + OUTPUT.insertAt("\n", newline_insert); + current_pos++; + current_line++; + } + newline_insert++; + } : options.max_line_len ? function() { + ensure_line_len(); + might_add_newline = OUTPUT.length(); + } : noop; + + var semicolon = options.beautify ? function() { + print(";"); + } : function() { + might_need_semicolon = true; + }; + + function force_semicolon() { + might_need_semicolon = false; + print(";"); + } + + function next_indent() { + return indentation + options.indent_level; + } + + function with_block(cont) { + var ret; + print("{"); + newline(); + with_indent(next_indent(), function() { + ret = cont(); + }); + indent(); + print("}"); + return ret; + } + + function with_parens(cont) { + print("("); + //XXX: still nice to have that for argument lists + //var ret = with_indent(current_col, cont); + var ret = cont(); + print(")"); + return ret; + } + + function with_square(cont) { + print("["); + //var ret = with_indent(current_col, cont); + var ret = cont(); + print("]"); + return ret; + } + + function comma() { + print(","); + space(); + } + + function colon() { + print(":"); + space(); + } + + var add_mapping = mappings ? function(token, name) { + mapping_token = token; + mapping_name = name; + } : noop; + + function get() { + if (might_add_newline) { + ensure_line_len(); + } + return OUTPUT.toString(); + } + + function has_nlb() { + const output = OUTPUT.toString(); + let n = output.length - 1; + while (n >= 0) { + const code = output.charCodeAt(n); + if (code === CODE_LINE_BREAK) { + return true; + } + + if (code !== CODE_SPACE) { + return false; + } + n--; + } + return true; + } + + function filter_comment(comment) { + if (!options.preserve_annotations) { + comment = comment.replace(r_annotation, " "); + } + if (/^\s*$/.test(comment)) { + return ""; + } + return comment.replace(/(<\s*\/\s*)(script)/i, "<\\/$2"); + } + + function prepend_comments(node) { + var self = this; + var start = node.start; + if (!start) return; + var printed_comments = self.printed_comments; + + // There cannot be a newline between return and its value. + const return_with_value = node instanceof AST_Exit && node.value; + + if ( + start.comments_before + && printed_comments.has(start.comments_before) + ) { + if (return_with_value) { + start.comments_before = []; + } else { + return; + } + } + + var comments = start.comments_before; + if (!comments) { + comments = start.comments_before = []; + } + printed_comments.add(comments); + + if (return_with_value) { + var tw = new TreeWalker(function(node) { + var parent = tw.parent(); + if (parent instanceof AST_Exit + || parent instanceof AST_Binary && parent.left === node + || parent.TYPE == "Call" && parent.expression === node + || parent instanceof AST_Conditional && parent.condition === node + || parent instanceof AST_Dot && parent.expression === node + || parent instanceof AST_Sequence && parent.expressions[0] === node + || parent instanceof AST_Sub && parent.expression === node + || parent instanceof AST_UnaryPostfix) { + if (!node.start) return; + var text = node.start.comments_before; + if (text && !printed_comments.has(text)) { + printed_comments.add(text); + comments = comments.concat(text); + } + } else { + return true; + } + }); + tw.push(node); + node.value.walk(tw); + } + + if (current_pos == 0) { + if (comments.length > 0 && options.shebang && comments[0].type === "comment5" + && !printed_comments.has(comments[0])) { + print("#!" + comments.shift().value + "\n"); + indent(); + } + var preamble = options.preamble; + if (preamble) { + print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n")); + } + } + + comments = comments.filter(comment_filter, node).filter(c => !printed_comments.has(c)); + if (comments.length == 0) return; + var last_nlb = has_nlb(); + comments.forEach(function(c, i) { + printed_comments.add(c); + if (!last_nlb) { + if (c.nlb) { + print("\n"); + indent(); + last_nlb = true; + } else if (i > 0) { + space(); + } + } + + if (/comment[134]/.test(c.type)) { + var value = filter_comment(c.value); + if (value) { + print("//" + value + "\n"); + indent(); + } + last_nlb = true; + } else if (c.type == "comment2") { + var value = filter_comment(c.value); + if (value) { + print("/*" + value + "*/"); + } + last_nlb = false; + } + }); + if (!last_nlb) { + if (start.nlb) { + print("\n"); + indent(); + } else { + space(); + } + } + } + + function append_comments(node, tail) { + var self = this; + var token = node.end; + if (!token) return; + var printed_comments = self.printed_comments; + var comments = token[tail ? "comments_before" : "comments_after"]; + if (!comments || printed_comments.has(comments)) return; + if (!(node instanceof AST_Statement || comments.every((c) => + !/comment[134]/.test(c.type) + ))) return; + printed_comments.add(comments); + var insert = OUTPUT.length(); + comments.filter(comment_filter, node).forEach(function(c, i) { + if (printed_comments.has(c)) return; + printed_comments.add(c); + need_space = false; + if (need_newline_indented) { + print("\n"); + indent(); + need_newline_indented = false; + } else if (c.nlb && (i > 0 || !has_nlb())) { + print("\n"); + indent(); + } else if (i > 0 || !tail) { + space(); + } + if (/comment[134]/.test(c.type)) { + const value = filter_comment(c.value); + if (value) { + print("//" + value); + } + need_newline_indented = true; + } else if (c.type == "comment2") { + const value = filter_comment(c.value); + if (value) { + print("/*" + value + "*/"); + } + need_space = true; + } + }); + if (OUTPUT.length() > insert) newline_insert = insert; + } + + var stack = []; + return { + get : get, + toString : get, + indent : indent, + in_directive : false, + use_asm : null, + active_scope : null, + indentation : function() { return indentation; }, + current_width : function() { return current_col - indentation; }, + should_break : function() { return options.width && this.current_width() >= options.width; }, + has_parens : function() { return has_parens; }, + newline : newline, + print : print, + star : star, + space : space, + comma : comma, + colon : colon, + last : function() { return last; }, + semicolon : semicolon, + force_semicolon : force_semicolon, + to_utf8 : to_utf8, + print_name : function(name) { print(make_name(name)); }, + print_string : function(str, quote, escape_directive) { + var encoded = encode_string(str, quote); + if (escape_directive === true && !encoded.includes("\\")) { + // Insert semicolons to break directive prologue + if (!EXPECT_DIRECTIVE.test(OUTPUT.toString())) { + force_semicolon(); + } + force_semicolon(); + } + print(encoded); + }, + print_template_string_chars: function(str) { + var encoded = encode_string(str, "`").replace(/\${/g, "\\${"); + return print(encoded.substr(1, encoded.length - 2)); + }, + encode_string : encode_string, + next_indent : next_indent, + with_indent : with_indent, + with_block : with_block, + with_parens : with_parens, + with_square : with_square, + add_mapping : add_mapping, + option : function(opt) { return options[opt]; }, + printed_comments: printed_comments, + prepend_comments: readonly ? noop : prepend_comments, + append_comments : readonly || comment_filter === return_false ? noop : append_comments, + line : function() { return current_line; }, + col : function() { return current_col; }, + pos : function() { return current_pos; }, + push_node : function(node) { stack.push(node); }, + pop_node : function() { return stack.pop(); }, + parent : function(n) { + return stack[stack.length - 2 - (n || 0)]; + } + }; + +} + +/* -----[ code generators ]----- */ + +(function() { + + /* -----[ utils ]----- */ + + function DEFPRINT(nodetype, generator) { + nodetype.DEFMETHOD("_codegen", generator); + } + + AST_Node.DEFMETHOD("print", function(output, force_parens) { + var self = this, generator = self._codegen; + if (self instanceof AST_Scope) { + output.active_scope = self; + } else if (!output.use_asm && self instanceof AST_Directive && self.value == "use asm") { + output.use_asm = output.active_scope; + } + function doit() { + output.prepend_comments(self); + self.add_source_map(output); + generator(self, output); + output.append_comments(self); + } + output.push_node(self); + if (force_parens || self.needs_parens(output)) { + output.with_parens(doit); + } else { + doit(); + } + output.pop_node(); + if (self === output.use_asm) { + output.use_asm = null; + } + }); + AST_Node.DEFMETHOD("_print", AST_Node.prototype.print); + + AST_Node.DEFMETHOD("print_to_string", function(options) { + var output = OutputStream(options); + this.print(output); + return output.get(); + }); + + /* -----[ PARENTHESES ]----- */ + + function PARENS(nodetype, func) { + if (Array.isArray(nodetype)) { + nodetype.forEach(function(nodetype) { + PARENS(nodetype, func); + }); + } else { + nodetype.DEFMETHOD("needs_parens", func); + } + } + + PARENS(AST_Node, return_false); + + // a function expression needs parens around it when it's provably + // the first token to appear in a statement. + PARENS(AST_Function, function(output) { + if (!output.has_parens() && first_in_statement(output)) { + return true; + } + + if (output.option("webkit")) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + return true; + } + } + + if (output.option("wrap_iife")) { + var p = output.parent(); + if (p instanceof AST_Call && p.expression === this) { + return true; + } + } + + if (output.option("wrap_func_args")) { + var p = output.parent(); + if (p instanceof AST_Call && p.args.includes(this)) { + return true; + } + } + + return false; + }); + + PARENS(AST_Arrow, function(output) { + var p = output.parent(); + + if ( + output.option("wrap_func_args") + && p instanceof AST_Call + && p.args.includes(this) + ) { + return true; + } + return p instanceof AST_PropAccess && p.expression === this; + }); + + // same goes for an object literal (as in AST_Function), because + // otherwise {...} would be interpreted as a block of code. + PARENS(AST_Object, function(output) { + return !output.has_parens() && first_in_statement(output); + }); + + PARENS(AST_ClassExpression, first_in_statement); + + PARENS(AST_Unary, function(output) { + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this + || p instanceof AST_Binary + && p.operator === "**" + && this instanceof AST_UnaryPrefix + && p.left === this + && this.operator !== "++" + && this.operator !== "--"; + }); + + PARENS(AST_Await, function(output) { + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this + || p instanceof AST_Binary && p.operator === "**" && p.left === this + || output.option("safari10") && p instanceof AST_UnaryPrefix; + }); + + PARENS(AST_Sequence, function(output) { + var p = output.parent(); + return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) + || p instanceof AST_Unary // !(foo, bar, baz) + || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 + || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 + || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 + || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] + || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 + || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) + * ==> 20 (side effect, set a := 10 and b := 20) */ + || p instanceof AST_Arrow // x => (x, x) + || p instanceof AST_DefaultAssign // x => (x = (0, function(){})) + || p instanceof AST_Expansion // [...(a, b)] + || p instanceof AST_ForOf && this === p.object // for (e of (foo, bar)) {} + || p instanceof AST_Yield // yield (foo, bar) + || p instanceof AST_Export // export default (foo, bar) + ; + }); + + PARENS(AST_Binary, function(output) { + var p = output.parent(); + // (foo && bar)() + if (p instanceof AST_Call && p.expression === this) + return true; + // typeof (foo && bar) + if (p instanceof AST_Unary) + return true; + // (foo && bar)["prop"], (foo && bar).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // this deals with precedence: 3 * (2 + 1) + if (p instanceof AST_Binary) { + const po = p.operator; + const so = this.operator; + + if (so === "??" && (po === "||" || po === "&&")) { + return true; + } + + if (po === "??" && (so === "||" || so === "&&")) { + return true; + } + + const pp = PRECEDENCE[po]; + const sp = PRECEDENCE[so]; + if (pp > sp + || (pp == sp + && (this === p.right || po == "**"))) { + return true; + } + } + }); + + PARENS(AST_Yield, function(output) { + var p = output.parent(); + // (yield 1) + (yield 2) + // a = yield 3 + if (p instanceof AST_Binary && p.operator !== "=") + return true; + // (yield 1)() + // new (yield 1)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (yield 1) ? yield 2 : yield 3 + if (p instanceof AST_Conditional && p.condition === this) + return true; + // -(yield 4) + if (p instanceof AST_Unary) + return true; + // (yield x).foo + // (yield x)['foo'] + if (p instanceof AST_PropAccess && p.expression === this) + return true; + }); + + PARENS(AST_PropAccess, function(output) { + var p = output.parent(); + if (p instanceof AST_New && p.expression === this) { + // i.e. new (foo.bar().baz) + // + // if there's one call into this subtree, then we need + // parens around it too, otherwise the call will be + // interpreted as passing the arguments to the upper New + // expression. + return walk(this, node => { + if (node instanceof AST_Scope) return true; + if (node instanceof AST_Call) { + return walk_abort; // makes walk() return true. + } + }); + } + }); + + PARENS(AST_Call, function(output) { + var p = output.parent(), p1; + if (p instanceof AST_New && p.expression === this + || p instanceof AST_Export && p.is_default && this.expression instanceof AST_Function) + return true; + + // workaround for Safari bug. + // https://bugs.webkit.org/show_bug.cgi?id=123506 + return this.expression instanceof AST_Function + && p instanceof AST_PropAccess + && p.expression === this + && (p1 = output.parent(1)) instanceof AST_Assign + && p1.left === p; + }); + + PARENS(AST_New, function(output) { + var p = output.parent(); + if (this.args.length === 0 + && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() + || p instanceof AST_Call && p.expression === this + || p instanceof AST_PrefixedTemplateString && p.prefix === this)) // (new foo)(bar) + return true; + }); + + PARENS(AST_Number, function(output) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + var value = this.getValue(); + if (value < 0 || /^0/.test(make_num(value))) { + return true; + } + } + }); + + PARENS(AST_BigInt, function(output) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + var value = this.getValue(); + if (value.startsWith("-")) { + return true; + } + } + }); + + PARENS([ AST_Assign, AST_Conditional ], function(output) { + var p = output.parent(); + // !(a = false) → true + if (p instanceof AST_Unary) + return true; + // 1 + (a = 2) + 3 → 6, side effect setting a = 2 + if (p instanceof AST_Binary && !(p instanceof AST_Assign)) + return true; + // (a = func)() —or— new (a = Object)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (a = foo) ? bar : baz + if (p instanceof AST_Conditional && p.condition === this) + return true; + // (a = foo)["prop"] —or— (a = foo).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // ({a, b} = {a: 1, b: 2}), a destructuring assignment + if (this instanceof AST_Assign && this.left instanceof AST_Destructuring && this.left.is_array === false) + return true; + }); + + /* -----[ PRINTERS ]----- */ + + DEFPRINT(AST_Directive, function(self, output) { + output.print_string(self.value, self.quote); + output.semicolon(); + }); + + DEFPRINT(AST_Expansion, function (self, output) { + output.print("..."); + self.expression.print(output); + }); + + DEFPRINT(AST_Destructuring, function (self, output) { + output.print(self.is_array ? "[" : "{"); + var len = self.names.length; + self.names.forEach(function (name, i) { + if (i > 0) output.comma(); + name.print(output); + // If the final element is a hole, we need to make sure it + // doesn't look like a trailing comma, by inserting an actual + // trailing comma. + if (i == len - 1 && name instanceof AST_Hole) output.comma(); + }); + output.print(self.is_array ? "]" : "}"); + }); + + DEFPRINT(AST_Debugger, function(self, output) { + output.print("debugger"); + output.semicolon(); + }); + + /* -----[ statements ]----- */ + + function display_body(body, is_toplevel, output, allow_directives) { + var last = body.length - 1; + output.in_directive = allow_directives; + body.forEach(function(stmt, i) { + if (output.in_directive === true && !(stmt instanceof AST_Directive || + stmt instanceof AST_EmptyStatement || + (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String) + )) { + output.in_directive = false; + } + if (!(stmt instanceof AST_EmptyStatement)) { + output.indent(); + stmt.print(output); + if (!(i == last && is_toplevel)) { + output.newline(); + if (is_toplevel) output.newline(); + } + } + if (output.in_directive === true && + stmt instanceof AST_SimpleStatement && + stmt.body instanceof AST_String + ) { + output.in_directive = false; + } + }); + output.in_directive = false; + } + + AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output) { + force_statement(this.body, output); + }); + + DEFPRINT(AST_Statement, function(self, output) { + self.body.print(output); + output.semicolon(); + }); + DEFPRINT(AST_Toplevel, function(self, output) { + display_body(self.body, true, output, true); + output.print(""); + }); + DEFPRINT(AST_LabeledStatement, function(self, output) { + self.label.print(output); + output.colon(); + self.body.print(output); + }); + DEFPRINT(AST_SimpleStatement, function(self, output) { + self.body.print(output); + output.semicolon(); + }); + function print_braced_empty(self, output) { + output.print("{"); + output.with_indent(output.next_indent(), function() { + output.append_comments(self, true); + }); + output.print("}"); + } + function print_braced(self, output, allow_directives) { + if (self.body.length > 0) { + output.with_block(function() { + display_body(self.body, false, output, allow_directives); + }); + } else print_braced_empty(self, output); + } + DEFPRINT(AST_BlockStatement, function(self, output) { + print_braced(self, output); + }); + DEFPRINT(AST_EmptyStatement, function(self, output) { + output.semicolon(); + }); + DEFPRINT(AST_Do, function(self, output) { + output.print("do"); + output.space(); + make_block(self.body, output); + output.space(); + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.semicolon(); + }); + DEFPRINT(AST_While, function(self, output) { + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_For, function(self, output) { + output.print("for"); + output.space(); + output.with_parens(function() { + if (self.init) { + if (self.init instanceof AST_Definitions) { + self.init.print(output); + } else { + parenthesize_for_noin(self.init, output, true); + } + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.condition) { + self.condition.print(output); + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.step) { + self.step.print(output); + } + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_ForIn, function(self, output) { + output.print("for"); + if (self.await) { + output.space(); + output.print("await"); + } + output.space(); + output.with_parens(function() { + self.init.print(output); + output.space(); + output.print(self instanceof AST_ForOf ? "of" : "in"); + output.space(); + self.object.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_With, function(self, output) { + output.print("with"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + output.space(); + self._do_print_body(output); + }); + + /* -----[ functions ]----- */ + AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword) { + var self = this; + if (!nokeyword) { + if (self.async) { + output.print("async"); + output.space(); + } + output.print("function"); + if (self.is_generator) { + output.star(); + } + if (self.name) { + output.space(); + } + } + if (self.name instanceof AST_Symbol) { + self.name.print(output); + } else if (nokeyword && self.name instanceof AST_Node) { + output.with_square(function() { + self.name.print(output); // Computed method name + }); + } + output.with_parens(function() { + self.argnames.forEach(function(arg, i) { + if (i) output.comma(); + arg.print(output); + }); + }); + output.space(); + print_braced(self, output, true); + }); + DEFPRINT(AST_Lambda, function(self, output) { + self._do_print(output); + }); + + DEFPRINT(AST_PrefixedTemplateString, function(self, output) { + var tag = self.prefix; + var parenthesize_tag = tag instanceof AST_Lambda + || tag instanceof AST_Binary + || tag instanceof AST_Conditional + || tag instanceof AST_Sequence + || tag instanceof AST_Unary + || tag instanceof AST_Dot && tag.expression instanceof AST_Object; + if (parenthesize_tag) output.print("("); + self.prefix.print(output); + if (parenthesize_tag) output.print(")"); + self.template_string.print(output); + }); + DEFPRINT(AST_TemplateString, function(self, output) { + var is_tagged = output.parent() instanceof AST_PrefixedTemplateString; + + output.print("`"); + for (var i = 0; i < self.segments.length; i++) { + if (!(self.segments[i] instanceof AST_TemplateSegment)) { + output.print("${"); + self.segments[i].print(output); + output.print("}"); + } else if (is_tagged) { + output.print(self.segments[i].raw); + } else { + output.print_template_string_chars(self.segments[i].value); + } + } + output.print("`"); + }); + DEFPRINT(AST_TemplateSegment, function(self, output) { + output.print_template_string_chars(self.value); + }); + + AST_Arrow.DEFMETHOD("_do_print", function(output) { + var self = this; + var parent = output.parent(); + var needs_parens = (parent instanceof AST_Binary && !(parent instanceof AST_Assign)) || + parent instanceof AST_Unary || + (parent instanceof AST_Call && self === parent.expression); + if (needs_parens) { output.print("("); } + if (self.async) { + output.print("async"); + output.space(); + } + if (self.argnames.length === 1 && self.argnames[0] instanceof AST_Symbol) { + self.argnames[0].print(output); + } else { + output.with_parens(function() { + self.argnames.forEach(function(arg, i) { + if (i) output.comma(); + arg.print(output); + }); + }); + } + output.space(); + output.print("=>"); + output.space(); + const first_statement = self.body[0]; + if ( + self.body.length === 1 + && first_statement instanceof AST_Return + ) { + const returned = first_statement.value; + if (!returned) { + output.print("{}"); + } else if (left_is_object(returned)) { + output.print("("); + returned.print(output); + output.print(")"); + } else { + returned.print(output); + } + } else { + print_braced(self, output); + } + if (needs_parens) { output.print(")"); } + }); + + /* -----[ exits ]----- */ + AST_Exit.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + if (this.value) { + output.space(); + const comments = this.value.start.comments_before; + if (comments && comments.length && !output.printed_comments.has(comments)) { + output.print("("); + this.value.print(output); + output.print(")"); + } else { + this.value.print(output); + } + } + output.semicolon(); + }); + DEFPRINT(AST_Return, function(self, output) { + self._do_print(output, "return"); + }); + DEFPRINT(AST_Throw, function(self, output) { + self._do_print(output, "throw"); + }); + + /* -----[ yield ]----- */ + + DEFPRINT(AST_Yield, function(self, output) { + var star = self.is_star ? "*" : ""; + output.print("yield" + star); + if (self.expression) { + output.space(); + self.expression.print(output); + } + }); + + DEFPRINT(AST_Await, function(self, output) { + output.print("await"); + output.space(); + var e = self.expression; + var parens = !( + e instanceof AST_Call + || e instanceof AST_SymbolRef + || e instanceof AST_PropAccess + || e instanceof AST_Unary + || e instanceof AST_Constant + || e instanceof AST_Await + || e instanceof AST_Object + ); + if (parens) output.print("("); + self.expression.print(output); + if (parens) output.print(")"); + }); + + /* -----[ loop control ]----- */ + AST_LoopControl.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + if (this.label) { + output.space(); + this.label.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Break, function(self, output) { + self._do_print(output, "break"); + }); + DEFPRINT(AST_Continue, function(self, output) { + self._do_print(output, "continue"); + }); + + /* -----[ if ]----- */ + function make_then(self, output) { + var b = self.body; + if (output.option("braces") + || output.option("ie8") && b instanceof AST_Do) + return make_block(b, output); + // The squeezer replaces "block"-s that contain only a single + // statement with the statement itself; technically, the AST + // is correct, but this can create problems when we output an + // IF having an ELSE clause where the THEN clause ends in an + // IF *without* an ELSE block (then the outer ELSE would refer + // to the inner IF). This function checks for this case and + // adds the block braces if needed. + if (!b) return output.force_semicolon(); + while (true) { + if (b instanceof AST_If) { + if (!b.alternative) { + make_block(self.body, output); + return; + } + b = b.alternative; + } else if (b instanceof AST_StatementWithBody) { + b = b.body; + } else break; + } + force_statement(self.body, output); + } + DEFPRINT(AST_If, function(self, output) { + output.print("if"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.space(); + if (self.alternative) { + make_then(self, output); + output.space(); + output.print("else"); + output.space(); + if (self.alternative instanceof AST_If) + self.alternative.print(output); + else + force_statement(self.alternative, output); + } else { + self._do_print_body(output); + } + }); + + /* -----[ switch ]----- */ + DEFPRINT(AST_Switch, function(self, output) { + output.print("switch"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + output.space(); + var last = self.body.length - 1; + if (last < 0) print_braced_empty(self, output); + else output.with_block(function() { + self.body.forEach(function(branch, i) { + output.indent(true); + branch.print(output); + if (i < last && branch.body.length > 0) + output.newline(); + }); + }); + }); + AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output) { + output.newline(); + this.body.forEach(function(stmt) { + output.indent(); + stmt.print(output); + output.newline(); + }); + }); + DEFPRINT(AST_Default, function(self, output) { + output.print("default:"); + self._do_print_body(output); + }); + DEFPRINT(AST_Case, function(self, output) { + output.print("case"); + output.space(); + self.expression.print(output); + output.print(":"); + self._do_print_body(output); + }); + + /* -----[ exceptions ]----- */ + DEFPRINT(AST_Try, function(self, output) { + output.print("try"); + output.space(); + print_braced(self, output); + if (self.bcatch) { + output.space(); + self.bcatch.print(output); + } + if (self.bfinally) { + output.space(); + self.bfinally.print(output); + } + }); + DEFPRINT(AST_Catch, function(self, output) { + output.print("catch"); + if (self.argname) { + output.space(); + output.with_parens(function() { + self.argname.print(output); + }); + } + output.space(); + print_braced(self, output); + }); + DEFPRINT(AST_Finally, function(self, output) { + output.print("finally"); + output.space(); + print_braced(self, output); + }); + + /* -----[ var/const ]----- */ + AST_Definitions.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + output.space(); + this.definitions.forEach(function(def, i) { + if (i) output.comma(); + def.print(output); + }); + var p = output.parent(); + var in_for = p instanceof AST_For || p instanceof AST_ForIn; + var output_semicolon = !in_for || p && p.init !== this; + if (output_semicolon) + output.semicolon(); + }); + DEFPRINT(AST_Let, function(self, output) { + self._do_print(output, "let"); + }); + DEFPRINT(AST_Var, function(self, output) { + self._do_print(output, "var"); + }); + DEFPRINT(AST_Const, function(self, output) { + self._do_print(output, "const"); + }); + DEFPRINT(AST_Import, function(self, output) { + output.print("import"); + output.space(); + if (self.imported_name) { + self.imported_name.print(output); + } + if (self.imported_name && self.imported_names) { + output.print(","); + output.space(); + } + if (self.imported_names) { + if (self.imported_names.length === 1 && self.imported_names[0].foreign_name.name === "*") { + self.imported_names[0].print(output); + } else { + output.print("{"); + self.imported_names.forEach(function (name_import, i) { + output.space(); + name_import.print(output); + if (i < self.imported_names.length - 1) { + output.print(","); + } + }); + output.space(); + output.print("}"); + } + } + if (self.imported_name || self.imported_names) { + output.space(); + output.print("from"); + output.space(); + } + self.module_name.print(output); + if (self.assert_clause) { + output.print("assert"); + self.assert_clause.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_ImportMeta, function(self, output) { + output.print("import.meta"); + }); + + DEFPRINT(AST_NameMapping, function(self, output) { + var is_import = output.parent() instanceof AST_Import; + var definition = self.name.definition(); + var names_are_different = + (definition && definition.mangled_name || self.name.name) !== + self.foreign_name.name; + if (names_are_different) { + if (is_import) { + output.print(self.foreign_name.name); + } else { + self.name.print(output); + } + output.space(); + output.print("as"); + output.space(); + if (is_import) { + self.name.print(output); + } else { + output.print(self.foreign_name.name); + } + } else { + self.name.print(output); + } + }); + + DEFPRINT(AST_Export, function(self, output) { + output.print("export"); + output.space(); + if (self.is_default) { + output.print("default"); + output.space(); + } + if (self.exported_names) { + if (self.exported_names.length === 1 && self.exported_names[0].name.name === "*") { + self.exported_names[0].print(output); + } else { + output.print("{"); + self.exported_names.forEach(function(name_export, i) { + output.space(); + name_export.print(output); + if (i < self.exported_names.length - 1) { + output.print(","); + } + }); + output.space(); + output.print("}"); + } + } else if (self.exported_value) { + self.exported_value.print(output); + } else if (self.exported_definition) { + self.exported_definition.print(output); + if (self.exported_definition instanceof AST_Definitions) return; + } + if (self.module_name) { + output.space(); + output.print("from"); + output.space(); + self.module_name.print(output); + } + if (self.assert_clause) { + output.print("assert"); + self.assert_clause.print(output); + } + if (self.exported_value + && !(self.exported_value instanceof AST_Defun || + self.exported_value instanceof AST_Function || + self.exported_value instanceof AST_Class) + || self.module_name + || self.exported_names + ) { + output.semicolon(); + } + }); + + function parenthesize_for_noin(node, output, noin) { + var parens = false; + // need to take some precautions here: + // https://github.com/mishoo/UglifyJS2/issues/60 + if (noin) { + parens = walk(node, node => { + // Don't go into scopes -- except arrow functions: + // https://github.com/terser/terser/issues/1019#issuecomment-877642607 + if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) { + return true; + } + if (node instanceof AST_Binary && node.operator == "in") { + return walk_abort; // makes walk() return true + } + }); + } + node.print(output, parens); + } + + DEFPRINT(AST_VarDef, function(self, output) { + self.name.print(output); + if (self.value) { + output.space(); + output.print("="); + output.space(); + var p = output.parent(1); + var noin = p instanceof AST_For || p instanceof AST_ForIn; + parenthesize_for_noin(self.value, output, noin); + } + }); + + /* -----[ other expressions ]----- */ + DEFPRINT(AST_Call, function(self, output) { + self.expression.print(output); + if (self instanceof AST_New && self.args.length === 0) + return; + if (self.expression instanceof AST_Call || self.expression instanceof AST_Lambda) { + output.add_mapping(self.start); + } + if (self.optional) output.print("?."); + output.with_parens(function() { + self.args.forEach(function(expr, i) { + if (i) output.comma(); + expr.print(output); + }); + }); + }); + DEFPRINT(AST_New, function(self, output) { + output.print("new"); + output.space(); + AST_Call.prototype._codegen(self, output); + }); + + AST_Sequence.DEFMETHOD("_do_print", function(output) { + this.expressions.forEach(function(node, index) { + if (index > 0) { + output.comma(); + if (output.should_break()) { + output.newline(); + output.indent(); + } + } + node.print(output); + }); + }); + DEFPRINT(AST_Sequence, function(self, output) { + self._do_print(output); + // var p = output.parent(); + // if (p instanceof AST_Statement) { + // output.with_indent(output.next_indent(), function(){ + // self._do_print(output); + // }); + // } else { + // self._do_print(output); + // } + }); + DEFPRINT(AST_Dot, function(self, output) { + var expr = self.expression; + expr.print(output); + var prop = self.property; + var print_computed = ALL_RESERVED_WORDS.has(prop) + ? output.option("ie8") + : !is_identifier_string( + prop, + output.option("ecma") >= 2015 || output.option("safari10") + ); + + if (self.optional) output.print("?."); + + if (print_computed) { + output.print("["); + output.add_mapping(self.end); + output.print_string(prop); + output.print("]"); + } else { + if (expr instanceof AST_Number && expr.getValue() >= 0) { + if (!/[xa-f.)]/i.test(output.last())) { + output.print("."); + } + } + if (!self.optional) output.print("."); + // the name after dot would be mapped about here. + output.add_mapping(self.end); + output.print_name(prop); + } + }); + DEFPRINT(AST_DotHash, function(self, output) { + var expr = self.expression; + expr.print(output); + var prop = self.property; + + if (self.optional) output.print("?"); + output.print(".#"); + output.add_mapping(self.end); + output.print_name(prop); + }); + DEFPRINT(AST_Sub, function(self, output) { + self.expression.print(output); + if (self.optional) output.print("?."); + output.print("["); + self.property.print(output); + output.print("]"); + }); + DEFPRINT(AST_Chain, function(self, output) { + self.expression.print(output); + }); + DEFPRINT(AST_UnaryPrefix, function(self, output) { + var op = self.operator; + output.print(op); + if (/^[a-z]/i.test(op) + || (/[+-]$/.test(op) + && self.expression instanceof AST_UnaryPrefix + && /^[+-]/.test(self.expression.operator))) { + output.space(); + } + self.expression.print(output); + }); + DEFPRINT(AST_UnaryPostfix, function(self, output) { + self.expression.print(output); + output.print(self.operator); + }); + DEFPRINT(AST_Binary, function(self, output) { + var op = self.operator; + self.left.print(output); + if (op[0] == ">" /* ">>" ">>>" ">" ">=" */ + && self.left instanceof AST_UnaryPostfix + && self.left.operator == "--") { + // space is mandatory to avoid outputting --> + output.print(" "); + } else { + // the space is optional depending on "beautify" + output.space(); + } + output.print(op); + if ((op == "<" || op == "<<") + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "!" + && self.right.expression instanceof AST_UnaryPrefix + && self.right.expression.operator == "--") { + // space is mandatory to avoid outputting x ? y : false + if (self.left.operator == "||") { + var lr = self.left.right.evaluate(compressor); + if (!lr) return make_node(AST_Conditional, self, { + condition: self.left.left, + consequent: self.right, + alternative: self.left.right + }).optimize(compressor); + } + break; + case "||": + var ll = has_flag(self.left, TRUTHY) + ? true + : has_flag(self.left, FALSY) + ? false + : self.left.evaluate(compressor); + if (!ll) { + return make_sequence(self, [ self.left, self.right ]).optimize(compressor); + } else if (!(ll instanceof AST_Node)) { + return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor); + } + var rr = self.right.evaluate(compressor); + if (!rr) { + var parent = compressor.parent(); + if (parent.operator == "||" && parent.left === compressor.self() || compressor.in_boolean_context()) { + return self.left.optimize(compressor); + } + } else if (!(rr instanceof AST_Node)) { + if (compressor.in_boolean_context()) { + return make_sequence(self, [ + self.left, + make_node(AST_True, self) + ]).optimize(compressor); + } else { + set_flag(self, TRUTHY); + } + } + if (self.left.operator == "&&") { + var lr = self.left.right.evaluate(compressor); + if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self, { + condition: self.left.left, + consequent: self.left.right, + alternative: self.right + }).optimize(compressor); + } + break; + case "??": + if (is_nullish(self.left, compressor)) { + return self.right; + } + + var ll = self.left.evaluate(compressor); + if (!(ll instanceof AST_Node)) { + // if we know the value for sure we can simply compute right away. + return ll == null ? self.right : self.left; + } + + if (compressor.in_boolean_context()) { + const rr = self.right.evaluate(compressor); + if (!(rr instanceof AST_Node) && !rr) { + return self.left; + } + } + } + var associative = true; + switch (self.operator) { + case "+": + // (x + "foo") + "bar" => x + "foobar" + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.is_string(compressor)) { + var binary = make_node(AST_Binary, self, { + operator: "+", + left: self.left.right, + right: self.right, + }); + var r = binary.optimize(compressor); + if (binary !== r) { + self = make_node(AST_Binary, self, { + operator: "+", + left: self.left.left, + right: r + }); + } + } + // (x + "foo") + ("bar" + y) => (x + "foobar") + y + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.is_string(compressor) + && self.right instanceof AST_Binary + && self.right.operator == "+" + && self.right.is_string(compressor)) { + var binary = make_node(AST_Binary, self, { + operator: "+", + left: self.left.right, + right: self.right.left, + }); + var m = binary.optimize(compressor); + if (binary !== m) { + self = make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_Binary, self.left, { + operator: "+", + left: self.left.left, + right: m + }), + right: self.right.right + }); + } + } + // a + -b => a - b + if (self.right instanceof AST_UnaryPrefix + && self.right.operator == "-" + && self.left.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.left, + right: self.right.expression + }); + break; + } + // -a + b => b - a + if (self.left instanceof AST_UnaryPrefix + && self.left.operator == "-" + && reversible() + && self.right.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.right, + right: self.left.expression + }); + break; + } + // `foo${bar}baz` + 1 => `foo${bar}baz1` + if (self.left instanceof AST_TemplateString) { + var l = self.left; + var r = self.right.evaluate(compressor); + if (r != self.right) { + l.segments[l.segments.length - 1].value += String(r); + return l; + } + } + // 1 + `foo${bar}baz` => `1foo${bar}baz` + if (self.right instanceof AST_TemplateString) { + var r = self.right; + var l = self.left.evaluate(compressor); + if (l != self.left) { + r.segments[0].value = String(l) + r.segments[0].value; + return r; + } + } + // `1${bar}2` + `foo${bar}baz` => `1${bar}2foo${bar}baz` + if (self.left instanceof AST_TemplateString + && self.right instanceof AST_TemplateString) { + var l = self.left; + var segments = l.segments; + var r = self.right; + segments[segments.length - 1].value += r.segments[0].value; + for (var i = 1; i < r.segments.length; i++) { + segments.push(r.segments[i]); + } + return l; + } + case "*": + associative = compressor.option("unsafe_math"); + case "&": + case "|": + case "^": + // a + +b => +b + a + if (self.left.is_number(compressor) + && self.right.is_number(compressor) + && reversible() + && !(self.left instanceof AST_Binary + && self.left.operator != self.operator + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + var reversed = make_node(AST_Binary, self, { + operator: self.operator, + left: self.right, + right: self.left + }); + if (self.right instanceof AST_Constant + && !(self.left instanceof AST_Constant)) { + self = best_of(compressor, reversed, self); + } else { + self = best_of(compressor, self, reversed); + } + } + if (associative && self.is_number(compressor)) { + // a + (b + c) => (a + b) + c + if (self.right instanceof AST_Binary + && self.right.operator == self.operator) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left, + right: self.right.left, + start: self.left.start, + end: self.right.left.end + }), + right: self.right.right + }); + } + // (n + 2) + 3 => 5 + n + // (2 * n) * 3 => 6 + n + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == self.operator) { + if (self.left.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.left, + right: self.right, + start: self.left.left.start, + end: self.right.end + }), + right: self.left.right + }); + } else if (self.left.right instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.right, + right: self.right, + start: self.left.right.start, + end: self.right.end + }), + right: self.left.left + }); + } + } + // (a | 1) | (2 | d) => (3 | a) | b + if (self.left instanceof AST_Binary + && self.left.operator == self.operator + && self.left.right instanceof AST_Constant + && self.right instanceof AST_Binary + && self.right.operator == self.operator + && self.right.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: make_node(AST_Binary, self.left.left, { + operator: self.operator, + left: self.left.right, + right: self.right.left, + start: self.left.right.start, + end: self.right.left.end + }), + right: self.left.left + }), + right: self.right.right + }); + } + } + } + } + // x && (y && z) ==> x && y && z + // x || (y || z) ==> x || y || z + // x + ("y" + z) ==> x + "y" + z + // "x" + (y + "z")==> "x" + y + "z" + if (self.right instanceof AST_Binary + && self.right.operator == self.operator + && (lazy_op.has(self.operator) + || (self.operator == "+" + && (self.right.left.is_string(compressor) + || (self.left.is_string(compressor) + && self.right.right.is_string(compressor))))) + ) { + self.left = make_node(AST_Binary, self.left, { + operator : self.operator, + left : self.left.transform(compressor), + right : self.right.left.transform(compressor) + }); + self.right = self.right.right.transform(compressor); + return self.transform(compressor); + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +def_optimize(AST_SymbolExport, function(self) { + return self; +}); + +function within_array_or_object_literal(compressor) { + var node, level = 0; + while (node = compressor.parent(level++)) { + if (node instanceof AST_Statement) return false; + if (node instanceof AST_Array + || node instanceof AST_ObjectKeyVal + || node instanceof AST_Object) { + return true; + } + } + return false; +} + +def_optimize(AST_SymbolRef, function(self, compressor) { + if ( + !compressor.option("ie8") + && is_undeclared_ref(self) + && !compressor.find_parent(AST_With) + ) { + switch (self.name) { + case "undefined": + return make_node(AST_Undefined, self).optimize(compressor); + case "NaN": + return make_node(AST_NaN, self).optimize(compressor); + case "Infinity": + return make_node(AST_Infinity, self).optimize(compressor); + } + } + + const parent = compressor.parent(); + if (compressor.option("reduce_vars") && is_lhs(self, parent) !== self) { + const def = self.definition(); + const nearest_scope = find_scope(compressor); + if (compressor.top_retain && def.global && compressor.top_retain(def)) { + def.fixed = false; + def.single_use = false; + return self; + } + + let fixed = self.fixed_value(); + let single_use = def.single_use + && !(parent instanceof AST_Call + && (parent.is_callee_pure(compressor)) + || has_annotation(parent, _NOINLINE)) + && !(parent instanceof AST_Export + && fixed instanceof AST_Lambda + && fixed.name); + + if (single_use && fixed instanceof AST_Node) { + single_use = + !fixed.has_side_effects(compressor) + && !fixed.may_throw(compressor); + } + + if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) { + if (retain_top_func(fixed, compressor)) { + single_use = false; + } else if (def.scope !== self.scope + && (def.escaped == 1 + || has_flag(fixed, INLINED) + || within_array_or_object_literal(compressor) + || !compressor.option("reduce_funcs"))) { + single_use = false; + } else if (is_recursive_ref(compressor, def)) { + single_use = false; + } else if (def.scope !== self.scope || def.orig[0] instanceof AST_SymbolFunarg) { + single_use = fixed.is_constant_expression(self.scope); + if (single_use == "f") { + var scope = self.scope; + do { + if (scope instanceof AST_Defun || is_func_expr(scope)) { + set_flag(scope, INLINED); + } + } while (scope = scope.parent_scope); + } + } + } + + if (single_use && fixed instanceof AST_Lambda) { + single_use = + def.scope === self.scope + && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) + || parent instanceof AST_Call + && parent.expression === self + && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) + && !(fixed.name && fixed.name.definition().recursive_refs > 0); + } + + if (single_use && fixed) { + if (fixed instanceof AST_DefClass) { + set_flag(fixed, SQUEEZED); + fixed = make_node(AST_ClassExpression, fixed, fixed); + } + if (fixed instanceof AST_Defun) { + set_flag(fixed, SQUEEZED); + fixed = make_node(AST_Function, fixed, fixed); + } + if (def.recursive_refs > 0 && fixed.name instanceof AST_SymbolDefun) { + const defun_def = fixed.name.definition(); + let lambda_def = fixed.variables.get(fixed.name.name); + let name = lambda_def && lambda_def.orig[0]; + if (!(name instanceof AST_SymbolLambda)) { + name = make_node(AST_SymbolLambda, fixed.name, fixed.name); + name.scope = fixed; + fixed.name = name; + lambda_def = fixed.def_function(name); + } + walk(fixed, node => { + if (node instanceof AST_SymbolRef && node.definition() === defun_def) { + node.thedef = lambda_def; + lambda_def.references.push(node); + } + }); + } + if ( + (fixed instanceof AST_Lambda || fixed instanceof AST_Class) + && fixed.parent_scope !== nearest_scope + ) { + fixed = fixed.clone(true, compressor.get_toplevel()); + + nearest_scope.add_child_scope(fixed); + } + return fixed.optimize(compressor); + } + + // multiple uses + if (fixed) { + let replace; + + if (fixed instanceof AST_This) { + if (!(def.orig[0] instanceof AST_SymbolFunarg) + && def.references.every((ref) => + def.scope === ref.scope + )) { + replace = fixed; + } + } else { + var ev = fixed.evaluate(compressor); + if ( + ev !== fixed + && (compressor.option("unsafe_regexp") || !(ev instanceof RegExp)) + ) { + replace = make_node_from_constant(ev, fixed); + } + } + + if (replace) { + const name_length = self.size(compressor); + const replace_size = replace.size(compressor); + + let overhead = 0; + if (compressor.option("unused") && !compressor.exposed(def)) { + overhead = + (name_length + 2 + replace_size) / + (def.references.length - def.assignments); + } + + if (replace_size <= name_length + overhead) { + return replace; + } + } + } + } + + return self; +}); + +function scope_encloses_variables_in_this_scope(scope, pulled_scope) { + for (const enclosed of pulled_scope.enclosed) { + if (pulled_scope.variables.has(enclosed.name)) { + continue; + } + const looked_up = scope.find_variable(enclosed.name); + if (looked_up) { + if (looked_up === enclosed) continue; + return true; + } + } + return false; +} + +function is_atomic(lhs, self) { + return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE; +} + +def_optimize(AST_Undefined, function(self, compressor) { + if (compressor.option("unsafe_undefined")) { + var undef = find_variable(compressor, "undefined"); + if (undef) { + var ref = make_node(AST_SymbolRef, self, { + name : "undefined", + scope : undef.scope, + thedef : undef + }); + set_flag(ref, UNDEFINED); + return ref; + } + } + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && is_atomic(lhs, self)) return self; + return make_node(AST_UnaryPrefix, self, { + operator: "void", + expression: make_node(AST_Number, self, { + value: 0 + }) + }); +}); + +def_optimize(AST_Infinity, function(self, compressor) { + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && is_atomic(lhs, self)) return self; + if ( + compressor.option("keep_infinity") + && !(lhs && !is_atomic(lhs, self)) + && !find_variable(compressor, "Infinity") + ) { + return self; + } + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 1 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); +}); + +def_optimize(AST_NaN, function(self, compressor) { + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && !is_atomic(lhs, self) + || find_variable(compressor, "NaN")) { + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 0 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); + } + return self; +}); + +function is_reachable(self, defs) { + const find_ref = node => { + if (node instanceof AST_SymbolRef && member(node.definition(), defs)) { + return walk_abort; + } + }; + + return walk_parent(self, (node, info) => { + if (node instanceof AST_Scope && node !== self) { + var parent = info.parent(); + + if ( + parent instanceof AST_Call + && parent.expression === node + // Async/Generators aren't guaranteed to sync evaluate all of + // their body steps, so it's possible they close over the variable. + && !(node.async || node.is_generator) + ) { + return; + } + + if (walk(node, find_ref)) return walk_abort; + + return true; + } + }); +} + +const ASSIGN_OPS = makePredicate("+ - / * % >> << >>> | ^ &"); +const ASSIGN_OPS_COMMUTATIVE = makePredicate("* | ^ &"); +def_optimize(AST_Assign, function(self, compressor) { + if (self.logical) { + return self.lift_sequences(compressor); + } + + var def; + if (compressor.option("dead_code") + && self.left instanceof AST_SymbolRef + && (def = self.left.definition()).scope === compressor.find_parent(AST_Lambda)) { + var level = 0, node, parent = self; + do { + node = parent; + parent = compressor.parent(level++); + if (parent instanceof AST_Exit) { + if (in_try(level, parent)) break; + if (is_reachable(def.scope, [ def ])) break; + if (self.operator == "=") return self.right; + def.fixed = false; + return make_node(AST_Binary, self, { + operator: self.operator.slice(0, -1), + left: self.left, + right: self.right + }).optimize(compressor); + } + } while (parent instanceof AST_Binary && parent.right === node + || parent instanceof AST_Sequence && parent.tail_node() === node); + } + self = self.lift_sequences(compressor); + if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) { + // x = expr1 OP expr2 + if (self.right.left instanceof AST_SymbolRef + && self.right.left.name == self.left.name + && ASSIGN_OPS.has(self.right.operator)) { + // x = x - 2 ---> x -= 2 + self.operator = self.right.operator + "="; + self.right = self.right.right; + } else if (self.right.right instanceof AST_SymbolRef + && self.right.right.name == self.left.name + && ASSIGN_OPS_COMMUTATIVE.has(self.right.operator) + && !self.right.left.has_side_effects(compressor)) { + // x = 2 & x ---> x &= 2 + self.operator = self.right.operator + "="; + self.right = self.right.left; + } + } + return self; + + function in_try(level, node) { + var right = self.right; + self.right = make_node(AST_Null, right); + var may_throw = node.may_throw(compressor); + self.right = right; + var scope = self.left.definition().scope; + var parent; + while ((parent = compressor.parent(level++)) !== scope) { + if (parent instanceof AST_Try) { + if (parent.bfinally) return true; + if (may_throw && parent.bcatch) return true; + } + } + } +}); + +def_optimize(AST_DefaultAssign, function(self, compressor) { + if (!compressor.option("evaluate")) { + return self; + } + var evaluateRight = self.right.evaluate(compressor); + + // `[x = undefined] = foo` ---> `[x] = foo` + if (evaluateRight === undefined) { + self = self.left; + } else if (evaluateRight !== self.right) { + evaluateRight = make_node_from_constant(evaluateRight, self.right); + self.right = best_of_expression(evaluateRight, self.right); + } + + return self; +}); + +function is_nullish_check(check, check_subject, compressor) { + if (check_subject.may_throw(compressor)) return false; + + let nullish_side; + + // foo == null + if ( + check instanceof AST_Binary + && check.operator === "==" + // which side is nullish? + && ( + (nullish_side = is_nullish(check.left, compressor) && check.left) + || (nullish_side = is_nullish(check.right, compressor) && check.right) + ) + // is the other side the same as the check_subject + && ( + nullish_side === check.left + ? check.right + : check.left + ).equivalent_to(check_subject) + ) { + return true; + } + + // foo === null || foo === undefined + if (check instanceof AST_Binary && check.operator === "||") { + let null_cmp; + let undefined_cmp; + + const find_comparison = cmp => { + if (!( + cmp instanceof AST_Binary + && (cmp.operator === "===" || cmp.operator === "==") + )) { + return false; + } + + let found = 0; + let defined_side; + + if (cmp.left instanceof AST_Null) { + found++; + null_cmp = cmp; + defined_side = cmp.right; + } + if (cmp.right instanceof AST_Null) { + found++; + null_cmp = cmp; + defined_side = cmp.left; + } + if (is_undefined(cmp.left, compressor)) { + found++; + undefined_cmp = cmp; + defined_side = cmp.right; + } + if (is_undefined(cmp.right, compressor)) { + found++; + undefined_cmp = cmp; + defined_side = cmp.left; + } + + if (found !== 1) { + return false; + } + + if (!defined_side.equivalent_to(check_subject)) { + return false; + } + + return true; + }; + + if (!find_comparison(check.left)) return false; + if (!find_comparison(check.right)) return false; + + if (null_cmp && undefined_cmp && null_cmp !== undefined_cmp) { + return true; + } + } + + return false; +} + +def_optimize(AST_Conditional, function(self, compressor) { + if (!compressor.option("conditionals")) return self; + // This looks like lift_sequences(), should probably be under "sequences" + if (self.condition instanceof AST_Sequence) { + var expressions = self.condition.expressions.slice(); + self.condition = expressions.pop(); + expressions.push(self); + return make_sequence(self, expressions); + } + var cond = self.condition.evaluate(compressor); + if (cond !== self.condition) { + if (cond) { + return maintain_this_binding(compressor.parent(), compressor.self(), self.consequent); + } else { + return maintain_this_binding(compressor.parent(), compressor.self(), self.alternative); + } + } + var negated = cond.negate(compressor, first_in_statement(compressor)); + if (best_of(compressor, cond, negated) === negated) { + self = make_node(AST_Conditional, self, { + condition: negated, + consequent: self.alternative, + alternative: self.consequent + }); + } + var condition = self.condition; + var consequent = self.consequent; + var alternative = self.alternative; + // x?x:y --> x||y + if (condition instanceof AST_SymbolRef + && consequent instanceof AST_SymbolRef + && condition.definition() === consequent.definition()) { + return make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative + }); + } + // if (foo) exp = something; else exp = something_else; + // | + // v + // exp = foo ? something : something_else; + if ( + consequent instanceof AST_Assign + && alternative instanceof AST_Assign + && consequent.operator === alternative.operator + && consequent.logical === alternative.logical + && consequent.left.equivalent_to(alternative.left) + && (!self.condition.has_side_effects(compressor) + || consequent.operator == "=" + && !consequent.left.has_side_effects(compressor)) + ) { + return make_node(AST_Assign, self, { + operator: consequent.operator, + left: consequent.left, + logical: consequent.logical, + right: make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.right, + alternative: alternative.right + }) + }); + } + // x ? y(a) : y(b) --> y(x ? a : b) + var arg_index; + if (consequent instanceof AST_Call + && alternative.TYPE === consequent.TYPE + && consequent.args.length > 0 + && consequent.args.length == alternative.args.length + && consequent.expression.equivalent_to(alternative.expression) + && !self.condition.has_side_effects(compressor) + && !consequent.expression.has_side_effects(compressor) + && typeof (arg_index = single_arg_diff()) == "number") { + var node = consequent.clone(); + node.args[arg_index] = make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.args[arg_index], + alternative: alternative.args[arg_index] + }); + return node; + } + // a ? b : c ? b : d --> (a || c) ? b : d + if (alternative instanceof AST_Conditional + && consequent.equivalent_to(alternative.consequent)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative.condition + }), + consequent: consequent, + alternative: alternative.alternative + }).optimize(compressor); + } + + // a == null ? b : a -> a ?? b + if ( + compressor.option("ecma") >= 2020 && + is_nullish_check(condition, alternative, compressor) + ) { + return make_node(AST_Binary, self, { + operator: "??", + left: alternative, + right: consequent + }).optimize(compressor); + } + + // a ? b : (c, b) --> (a || c), b + if (alternative instanceof AST_Sequence + && consequent.equivalent_to(alternative.expressions[alternative.expressions.length - 1])) { + return make_sequence(self, [ + make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: make_sequence(self, alternative.expressions.slice(0, -1)) + }), + consequent + ]).optimize(compressor); + } + // a ? b : (c && b) --> (a || c) && b + if (alternative instanceof AST_Binary + && alternative.operator == "&&" + && consequent.equivalent_to(alternative.right)) { + return make_node(AST_Binary, self, { + operator: "&&", + left: make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative.left + }), + right: consequent + }).optimize(compressor); + } + // x?y?z:a:a --> x&&y?z:a + if (consequent instanceof AST_Conditional + && consequent.alternative.equivalent_to(alternative)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + left: self.condition, + operator: "&&", + right: consequent.condition + }), + consequent: consequent.consequent, + alternative: alternative + }); + } + // x ? y : y --> x, y + if (consequent.equivalent_to(alternative)) { + return make_sequence(self, [ + self.condition, + consequent + ]).optimize(compressor); + } + // x ? y || z : z --> x && y || z + if (consequent instanceof AST_Binary + && consequent.operator == "||" + && consequent.right.equivalent_to(alternative)) { + return make_node(AST_Binary, self, { + operator: "||", + left: make_node(AST_Binary, self, { + operator: "&&", + left: self.condition, + right: consequent.left + }), + right: alternative + }).optimize(compressor); + } + + const in_bool = compressor.in_boolean_context(); + if (is_true(self.consequent)) { + if (is_false(self.alternative)) { + // c ? true : false ---> !!c + return booleanize(self.condition); + } + // c ? true : x ---> !!c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition), + right: self.alternative + }); + } + if (is_false(self.consequent)) { + if (is_true(self.alternative)) { + // c ? false : true ---> !c + return booleanize(self.condition.negate(compressor)); + } + // c ? false : x ---> !c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition.negate(compressor)), + right: self.alternative + }); + } + if (is_true(self.alternative)) { + // c ? x : true ---> !c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition.negate(compressor)), + right: self.consequent + }); + } + if (is_false(self.alternative)) { + // c ? x : false ---> !!c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition), + right: self.consequent + }); + } + + return self; + + function booleanize(node) { + if (node.is_boolean()) return node; + // !!expression + return make_node(AST_UnaryPrefix, node, { + operator: "!", + expression: node.negate(compressor) + }); + } + + // AST_True or !0 + function is_true(node) { + return node instanceof AST_True + || in_bool + && node instanceof AST_Constant + && node.getValue() + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && !node.expression.getValue()); + } + // AST_False or !1 + function is_false(node) { + return node instanceof AST_False + || in_bool + && node instanceof AST_Constant + && !node.getValue() + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && node.expression.getValue()); + } + + function single_arg_diff() { + var a = consequent.args; + var b = alternative.args; + for (var i = 0, len = a.length; i < len; i++) { + if (a[i] instanceof AST_Expansion) return; + if (!a[i].equivalent_to(b[i])) { + if (b[i] instanceof AST_Expansion) return; + for (var j = i + 1; j < len; j++) { + if (a[j] instanceof AST_Expansion) return; + if (!a[j].equivalent_to(b[j])) return; + } + return i; + } + } + } +}); + +def_optimize(AST_Boolean, function(self, compressor) { + if (compressor.in_boolean_context()) return make_node(AST_Number, self, { + value: +self.value + }); + var p = compressor.parent(); + if (compressor.option("booleans_as_integers")) { + if (p instanceof AST_Binary && (p.operator == "===" || p.operator == "!==")) { + p.operator = p.operator.replace(/=$/, ""); + } + return make_node(AST_Number, self, { + value: +self.value + }); + } + if (compressor.option("booleans")) { + if (p instanceof AST_Binary && (p.operator == "==" + || p.operator == "!=")) { + return make_node(AST_Number, self, { + value: +self.value + }); + } + return make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: make_node(AST_Number, self, { + value: 1 - self.value + }) + }); + } + return self; +}); + +function safe_to_flatten(value, compressor) { + if (value instanceof AST_SymbolRef) { + value = value.fixed_value(); + } + if (!value) return false; + if (!(value instanceof AST_Lambda || value instanceof AST_Class)) return true; + if (!(value instanceof AST_Lambda && value.contains_this())) return true; + return compressor.parent() instanceof AST_New; +} + +AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) { + if (!compressor.option("properties")) return; + if (key === "__proto__") return; + + var arrows = compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015; + var expr = this.expression; + if (expr instanceof AST_Object) { + var props = expr.properties; + + for (var i = props.length; --i >= 0;) { + var prop = props[i]; + + if ("" + (prop instanceof AST_ConciseMethod ? prop.key.name : prop.key) == key) { + const all_props_flattenable = props.every((p) => + (p instanceof AST_ObjectKeyVal + || arrows && p instanceof AST_ConciseMethod && !p.is_generator + ) + && !p.computed_key() + ); + + if (!all_props_flattenable) return; + if (!safe_to_flatten(prop.value, compressor)) return; + + return make_node(AST_Sub, this, { + expression: make_node(AST_Array, expr, { + elements: props.map(function(prop) { + var v = prop.value; + if (v instanceof AST_Accessor) { + v = make_node(AST_Function, v, v); + } + + var k = prop.key; + if (k instanceof AST_Node && !(k instanceof AST_SymbolMethod)) { + return make_sequence(prop, [ k, v ]); + } + + return v; + }) + }), + property: make_node(AST_Number, this, { + value: i + }) + }); + } + } + } +}); + +def_optimize(AST_Sub, function(self, compressor) { + var expr = self.expression; + var prop = self.property; + if (compressor.option("properties")) { + var key = prop.evaluate(compressor); + if (key !== prop) { + if (typeof key == "string") { + if (key == "undefined") { + key = undefined; + } else { + var value = parseFloat(key); + if (value.toString() == key) { + key = value; + } + } + } + prop = self.property = best_of_expression(prop, make_node_from_constant(key, prop).transform(compressor)); + var property = "" + key; + if (is_basic_identifier_string(property) + && property.length <= prop.size() + 1) { + return make_node(AST_Dot, self, { + expression: expr, + optional: self.optional, + property: property, + quote: prop.quote, + }).optimize(compressor); + } + } + } + var fn; + OPT_ARGUMENTS: if (compressor.option("arguments") + && expr instanceof AST_SymbolRef + && expr.name == "arguments" + && expr.definition().orig.length == 1 + && (fn = expr.scope) instanceof AST_Lambda + && fn.uses_arguments + && !(fn instanceof AST_Arrow) + && prop instanceof AST_Number) { + var index = prop.getValue(); + var params = new Set(); + var argnames = fn.argnames; + for (var n = 0; n < argnames.length; n++) { + if (!(argnames[n] instanceof AST_SymbolFunarg)) { + break OPT_ARGUMENTS; // destructuring parameter - bail + } + var param = argnames[n].name; + if (params.has(param)) { + break OPT_ARGUMENTS; // duplicate parameter - bail + } + params.add(param); + } + var argname = fn.argnames[index]; + if (argname && compressor.has_directive("use strict")) { + var def = argname.definition(); + if (!compressor.option("reduce_vars") || def.assignments || def.orig.length > 1) { + argname = null; + } + } else if (!argname && !compressor.option("keep_fargs") && index < fn.argnames.length + 5) { + while (index >= fn.argnames.length) { + argname = fn.create_symbol(AST_SymbolFunarg, { + source: fn, + scope: fn, + tentative_name: "argument_" + fn.argnames.length, + }); + fn.argnames.push(argname); + } + } + if (argname) { + var sym = make_node(AST_SymbolRef, self, argname); + sym.reference({}); + clear_flag(argname, UNUSED); + return sym; + } + } + if (is_lhs(self, compressor.parent())) return self; + if (key !== prop) { + var sub = self.flatten_object(property, compressor); + if (sub) { + expr = self.expression = sub.expression; + prop = self.property = sub.property; + } + } + if (compressor.option("properties") && compressor.option("side_effects") + && prop instanceof AST_Number && expr instanceof AST_Array) { + var index = prop.getValue(); + var elements = expr.elements; + var retValue = elements[index]; + FLATTEN: if (safe_to_flatten(retValue, compressor)) { + var flatten = true; + var values = []; + for (var i = elements.length; --i > index;) { + var value = elements[i].drop_side_effect_free(compressor); + if (value) { + values.unshift(value); + if (flatten && value.has_side_effects(compressor)) flatten = false; + } + } + if (retValue instanceof AST_Expansion) break FLATTEN; + retValue = retValue instanceof AST_Hole ? make_node(AST_Undefined, retValue) : retValue; + if (!flatten) values.unshift(retValue); + while (--i >= 0) { + var value = elements[i]; + if (value instanceof AST_Expansion) break FLATTEN; + value = value.drop_side_effect_free(compressor); + if (value) values.unshift(value); + else index--; + } + if (flatten) { + values.push(retValue); + return make_sequence(self, values).optimize(compressor); + } else return make_node(AST_Sub, self, { + expression: make_node(AST_Array, expr, { + elements: values + }), + property: make_node(AST_Number, prop, { + value: index + }) + }); + } + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +def_optimize(AST_Chain, function (self, compressor) { + if (is_nullish(self.expression, compressor)) { + let parent = compressor.parent(); + // It's valid to delete a nullish optional chain, but if we optimized + // this to `delete undefined` then it would appear to be a syntax error + // when we try to optimize the delete. Thankfully, `delete 0` is fine. + if (parent instanceof AST_UnaryPrefix && parent.operator === "delete") { + return make_node_from_constant(0, self); + } + return make_node(AST_Undefined, self); + } + return self; +}); + +AST_Lambda.DEFMETHOD("contains_this", function() { + return walk(this, node => { + if (node instanceof AST_This) return walk_abort; + if ( + node !== this + && node instanceof AST_Scope + && !(node instanceof AST_Arrow) + ) { + return true; + } + }); +}); + +def_optimize(AST_Dot, function(self, compressor) { + const parent = compressor.parent(); + if (is_lhs(self, parent)) return self; + if (compressor.option("unsafe_proto") + && self.expression instanceof AST_Dot + && self.expression.property == "prototype") { + var exp = self.expression.expression; + if (is_undeclared_ref(exp)) switch (exp.name) { + case "Array": + self.expression = make_node(AST_Array, self.expression, { + elements: [] + }); + break; + case "Function": + self.expression = make_node(AST_Function, self.expression, { + argnames: [], + body: [] + }); + break; + case "Number": + self.expression = make_node(AST_Number, self.expression, { + value: 0 + }); + break; + case "Object": + self.expression = make_node(AST_Object, self.expression, { + properties: [] + }); + break; + case "RegExp": + self.expression = make_node(AST_RegExp, self.expression, { + value: { source: "t", flags: "" } + }); + break; + case "String": + self.expression = make_node(AST_String, self.expression, { + value: "" + }); + break; + } + } + if (!(parent instanceof AST_Call) || !has_annotation(parent, _NOINLINE)) { + const sub = self.flatten_object(self.property, compressor); + if (sub) return sub.optimize(compressor); + } + let ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +function literals_in_boolean_context(self, compressor) { + if (compressor.in_boolean_context()) { + return best_of(compressor, self, make_sequence(self, [ + self, + make_node(AST_True, self) + ]).optimize(compressor)); + } + return self; +} + +function inline_array_like_spread(elements) { + for (var i = 0; i < elements.length; i++) { + var el = elements[i]; + if (el instanceof AST_Expansion) { + var expr = el.expression; + if ( + expr instanceof AST_Array + && !expr.elements.some(elm => elm instanceof AST_Hole) + ) { + elements.splice(i, 1, ...expr.elements); + // Step back one, as the element at i is now new. + i--; + } + // In array-like spread, spreading a non-iterable value is TypeError. + // We therefore can’t optimize anything else, unlike with object spread. + } + } +} + +def_optimize(AST_Array, function(self, compressor) { + var optimized = literals_in_boolean_context(self, compressor); + if (optimized !== self) { + return optimized; + } + inline_array_like_spread(self.elements); + return self; +}); + +function inline_object_prop_spread(props, compressor) { + for (var i = 0; i < props.length; i++) { + var prop = props[i]; + if (prop instanceof AST_Expansion) { + const expr = prop.expression; + if ( + expr instanceof AST_Object + && expr.properties.every(prop => prop instanceof AST_ObjectKeyVal) + ) { + props.splice(i, 1, ...expr.properties); + // Step back one, as the property at i is now new. + i--; + } else if (expr instanceof AST_Constant + && !(expr instanceof AST_String)) { + // Unlike array-like spread, in object spread, spreading a + // non-iterable value silently does nothing; it is thus safe + // to remove. AST_String is the only iterable AST_Constant. + props.splice(i, 1); + i--; + } else if (is_nullish(expr, compressor)) { + // Likewise, null and undefined can be silently removed. + props.splice(i, 1); + i--; + } + } + } +} + +def_optimize(AST_Object, function(self, compressor) { + var optimized = literals_in_boolean_context(self, compressor); + if (optimized !== self) { + return optimized; + } + inline_object_prop_spread(self.properties, compressor); + return self; +}); + +def_optimize(AST_RegExp, literals_in_boolean_context); + +def_optimize(AST_Return, function(self, compressor) { + if (self.value && is_undefined(self.value, compressor)) { + self.value = null; + } + return self; +}); + +def_optimize(AST_Arrow, opt_AST_Lambda); + +def_optimize(AST_Function, function(self, compressor) { + self = opt_AST_Lambda(self, compressor); + if (compressor.option("unsafe_arrows") + && compressor.option("ecma") >= 2015 + && !self.name + && !self.is_generator + && !self.uses_arguments + && !self.pinned()) { + const uses_this = walk(self, node => { + if (node instanceof AST_This) return walk_abort; + }); + if (!uses_this) return make_node(AST_Arrow, self, self).optimize(compressor); + } + return self; +}); + +def_optimize(AST_Class, function(self) { + // HACK to avoid compress failure. + // AST_Class is not really an AST_Scope/AST_Block as it lacks a body. + return self; +}); + +def_optimize(AST_Yield, function(self, compressor) { + if (self.expression && !self.is_star && is_undefined(self.expression, compressor)) { + self.expression = null; + } + return self; +}); + +def_optimize(AST_TemplateString, function(self, compressor) { + if ( + !compressor.option("evaluate") + || compressor.parent() instanceof AST_PrefixedTemplateString + ) { + return self; + } + + var segments = []; + for (var i = 0; i < self.segments.length; i++) { + var segment = self.segments[i]; + if (segment instanceof AST_Node) { + var result = segment.evaluate(compressor); + // Evaluate to constant value + // Constant value shorter than ${segment} + if (result !== segment && (result + "").length <= segment.size() + "${}".length) { + // There should always be a previous and next segment if segment is a node + segments[segments.length - 1].value = segments[segments.length - 1].value + result + self.segments[++i].value; + continue; + } + // `before ${`innerBefore ${any} innerAfter`} after` => `before innerBefore ${any} innerAfter after` + // TODO: + // `before ${'test' + foo} after` => `before innerBefore ${any} innerAfter after` + // `before ${foo + 'test} after` => `before innerBefore ${any} innerAfter after` + if (segment instanceof AST_TemplateString) { + var inners = segment.segments; + segments[segments.length - 1].value += inners[0].value; + for (var j = 1; j < inners.length; j++) { + segment = inners[j]; + segments.push(segment); + } + continue; + } + } + segments.push(segment); + } + self.segments = segments; + + // `foo` => "foo" + if (segments.length == 1) { + return make_node(AST_String, self, segments[0]); + } + + if ( + segments.length === 3 + && segments[1] instanceof AST_Node + && ( + segments[1].is_string(compressor) + || segments[1].is_number(compressor) + || is_nullish(segments[1], compressor) + || compressor.option("unsafe") + ) + ) { + // `foo${bar}` => "foo" + bar + if (segments[2].value === "") { + return make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_String, self, { + value: segments[0].value, + }), + right: segments[1], + }); + } + // `${bar}baz` => bar + "baz" + if (segments[0].value === "") { + return make_node(AST_Binary, self, { + operator: "+", + left: segments[1], + right: make_node(AST_String, self, { + value: segments[2].value, + }), + }); + } + } + return self; +}); + +def_optimize(AST_PrefixedTemplateString, function(self) { + return self; +}); + +// ["p"]:1 ---> p:1 +// [42]:1 ---> 42:1 +function lift_key(self, compressor) { + if (!compressor.option("computed_props")) return self; + // save a comparison in the typical case + if (!(self.key instanceof AST_Constant)) return self; + // allow certain acceptable props as not all AST_Constants are true constants + if (self.key instanceof AST_String || self.key instanceof AST_Number) { + if (self.key.value === "__proto__") return self; + if (self.key.value == "constructor" + && compressor.parent() instanceof AST_Class) return self; + if (self instanceof AST_ObjectKeyVal) { + self.quote = self.key.quote; + self.key = self.key.value; + } else if (self instanceof AST_ClassProperty) { + self.quote = self.key.quote; + self.key = make_node(AST_SymbolClassProperty, self.key, { + name: self.key.value + }); + } else { + self.quote = self.key.quote; + self.key = make_node(AST_SymbolMethod, self.key, { + name: self.key.value + }); + } + } + return self; +} + +def_optimize(AST_ObjectProperty, lift_key); + +def_optimize(AST_ConciseMethod, function(self, compressor) { + lift_key(self, compressor); + // p(){return x;} ---> p:()=>x + if (compressor.option("arrows") + && compressor.parent() instanceof AST_Object + && !self.is_generator + && !self.value.uses_arguments + && !self.value.pinned() + && self.value.body.length == 1 + && self.value.body[0] instanceof AST_Return + && self.value.body[0].value + && !self.value.contains_this()) { + var arrow = make_node(AST_Arrow, self.value, self.value); + arrow.async = self.async; + arrow.is_generator = self.is_generator; + return make_node(AST_ObjectKeyVal, self, { + key: self.key instanceof AST_SymbolMethod ? self.key.name : self.key, + value: arrow, + quote: self.quote, + }); + } + return self; +}); + +def_optimize(AST_ObjectKeyVal, function(self, compressor) { + lift_key(self, compressor); + // p:function(){} ---> p(){} + // p:function*(){} ---> *p(){} + // p:async function(){} ---> async p(){} + // p:()=>{} ---> p(){} + // p:async()=>{} ---> async p(){} + var unsafe_methods = compressor.option("unsafe_methods"); + if (unsafe_methods + && compressor.option("ecma") >= 2015 + && (!(unsafe_methods instanceof RegExp) || unsafe_methods.test(self.key + ""))) { + var key = self.key; + var value = self.value; + var is_arrow_with_block = value instanceof AST_Arrow + && Array.isArray(value.body) + && !value.contains_this(); + if ((is_arrow_with_block || value instanceof AST_Function) && !value.name) { + return make_node(AST_ConciseMethod, self, { + async: value.async, + is_generator: value.is_generator, + key: key instanceof AST_Node ? key : make_node(AST_SymbolMethod, self, { + name: key, + }), + value: make_node(AST_Accessor, value, value), + quote: self.quote, + }); + } + } + return self; +}); + +def_optimize(AST_Destructuring, function(self, compressor) { + if (compressor.option("pure_getters") == true + && compressor.option("unused") + && !self.is_array + && Array.isArray(self.names) + && !is_destructuring_export_decl(compressor) + && !(self.names[self.names.length - 1] instanceof AST_Expansion)) { + var keep = []; + for (var i = 0; i < self.names.length; i++) { + var elem = self.names[i]; + if (!(elem instanceof AST_ObjectKeyVal + && typeof elem.key == "string" + && elem.value instanceof AST_SymbolDeclaration + && !should_retain(compressor, elem.value.definition()))) { + keep.push(elem); + } + } + if (keep.length != self.names.length) { + self.names = keep; + } + } + return self; + + function is_destructuring_export_decl(compressor) { + var ancestors = [/^VarDef$/, /^(Const|Let|Var)$/, /^Export$/]; + for (var a = 0, p = 0, len = ancestors.length; a < len; p++) { + var parent = compressor.parent(p); + if (!parent) return false; + if (a === 0 && parent.TYPE == "Destructuring") continue; + if (!ancestors[a].test(parent.TYPE)) { + return false; + } + a++; + } + return true; + } + + function should_retain(compressor, def) { + if (def.references.length) return true; + if (!def.global) return false; + if (compressor.toplevel.vars) { + if (compressor.top_retain) { + return compressor.top_retain(def); + } + return false; + } + return true; + } +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +// a small wrapper around fitzgen's source-map library +async function SourceMap(options) { + options = defaults(options, { + file : null, + root : null, + orig : null, + + orig_line_diff : 0, + dest_line_diff : 0, + }); + + var orig_map; + var generator = new MOZ_SourceMap__default['default'].SourceMapGenerator({ + file : options.file, + sourceRoot : options.root + }); + + if (options.orig) { + orig_map = await new MOZ_SourceMap__default['default'].SourceMapConsumer(options.orig); + orig_map.sources.forEach(function(source) { + var sourceContent = orig_map.sourceContentFor(source, true); + if (sourceContent) { + generator.setSourceContent(source, sourceContent); + } + }); + } + + function add(source, gen_line, gen_col, orig_line, orig_col, name) { + if (orig_map) { + var info = orig_map.originalPositionFor({ + line: orig_line, + column: orig_col + }); + if (info.source === null) { + return; + } + source = info.source; + orig_line = info.line; + orig_col = info.column; + name = info.name || name; + } + generator.addMapping({ + generated : { line: gen_line + options.dest_line_diff, column: gen_col }, + original : { line: orig_line + options.orig_line_diff, column: orig_col }, + source : source, + name : name + }); + } + + return { + add : add, + get : function() { return generator; }, + toString : function() { return generator.toString(); }, + destroy : function () { + if (orig_map && orig_map.destroy) { + orig_map.destroy(); + } + } + }; +} + +var domprops = [ + "$&", + "$'", + "$*", + "$+", + "$1", + "$2", + "$3", + "$4", + "$5", + "$6", + "$7", + "$8", + "$9", + "$_", + "$`", + "$input", + "-moz-animation", + "-moz-animation-delay", + "-moz-animation-direction", + "-moz-animation-duration", + "-moz-animation-fill-mode", + "-moz-animation-iteration-count", + "-moz-animation-name", + "-moz-animation-play-state", + "-moz-animation-timing-function", + "-moz-appearance", + "-moz-backface-visibility", + "-moz-border-end", + "-moz-border-end-color", + "-moz-border-end-style", + "-moz-border-end-width", + "-moz-border-image", + "-moz-border-start", + "-moz-border-start-color", + "-moz-border-start-style", + "-moz-border-start-width", + "-moz-box-align", + "-moz-box-direction", + "-moz-box-flex", + "-moz-box-ordinal-group", + "-moz-box-orient", + "-moz-box-pack", + "-moz-box-sizing", + "-moz-float-edge", + "-moz-font-feature-settings", + "-moz-font-language-override", + "-moz-force-broken-image-icon", + "-moz-hyphens", + "-moz-image-region", + "-moz-margin-end", + "-moz-margin-start", + "-moz-orient", + "-moz-osx-font-smoothing", + "-moz-outline-radius", + "-moz-outline-radius-bottomleft", + "-moz-outline-radius-bottomright", + "-moz-outline-radius-topleft", + "-moz-outline-radius-topright", + "-moz-padding-end", + "-moz-padding-start", + "-moz-perspective", + "-moz-perspective-origin", + "-moz-tab-size", + "-moz-text-size-adjust", + "-moz-transform", + "-moz-transform-origin", + "-moz-transform-style", + "-moz-transition", + "-moz-transition-delay", + "-moz-transition-duration", + "-moz-transition-property", + "-moz-transition-timing-function", + "-moz-user-focus", + "-moz-user-input", + "-moz-user-modify", + "-moz-user-select", + "-moz-window-dragging", + "-webkit-align-content", + "-webkit-align-items", + "-webkit-align-self", + "-webkit-animation", + "-webkit-animation-delay", + "-webkit-animation-direction", + "-webkit-animation-duration", + "-webkit-animation-fill-mode", + "-webkit-animation-iteration-count", + "-webkit-animation-name", + "-webkit-animation-play-state", + "-webkit-animation-timing-function", + "-webkit-appearance", + "-webkit-backface-visibility", + "-webkit-background-clip", + "-webkit-background-origin", + "-webkit-background-size", + "-webkit-border-bottom-left-radius", + "-webkit-border-bottom-right-radius", + "-webkit-border-image", + "-webkit-border-radius", + "-webkit-border-top-left-radius", + "-webkit-border-top-right-radius", + "-webkit-box-align", + "-webkit-box-direction", + "-webkit-box-flex", + "-webkit-box-ordinal-group", + "-webkit-box-orient", + "-webkit-box-pack", + "-webkit-box-shadow", + "-webkit-box-sizing", + "-webkit-filter", + "-webkit-flex", + "-webkit-flex-basis", + "-webkit-flex-direction", + "-webkit-flex-flow", + "-webkit-flex-grow", + "-webkit-flex-shrink", + "-webkit-flex-wrap", + "-webkit-justify-content", + "-webkit-line-clamp", + "-webkit-mask", + "-webkit-mask-clip", + "-webkit-mask-composite", + "-webkit-mask-image", + "-webkit-mask-origin", + "-webkit-mask-position", + "-webkit-mask-position-x", + "-webkit-mask-position-y", + "-webkit-mask-repeat", + "-webkit-mask-size", + "-webkit-order", + "-webkit-perspective", + "-webkit-perspective-origin", + "-webkit-text-fill-color", + "-webkit-text-size-adjust", + "-webkit-text-stroke", + "-webkit-text-stroke-color", + "-webkit-text-stroke-width", + "-webkit-transform", + "-webkit-transform-origin", + "-webkit-transform-style", + "-webkit-transition", + "-webkit-transition-delay", + "-webkit-transition-duration", + "-webkit-transition-property", + "-webkit-transition-timing-function", + "-webkit-user-select", + "0", + "1", + "10", + "11", + "12", + "13", + "14", + "15", + "16", + "17", + "18", + "19", + "2", + "20", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "@@iterator", + "ABORT_ERR", + "ACTIVE", + "ACTIVE_ATTRIBUTES", + "ACTIVE_TEXTURE", + "ACTIVE_UNIFORMS", + "ACTIVE_UNIFORM_BLOCKS", + "ADDITION", + "ALIASED_LINE_WIDTH_RANGE", + "ALIASED_POINT_SIZE_RANGE", + "ALLOW_KEYBOARD_INPUT", + "ALLPASS", + "ALPHA", + "ALPHA_BITS", + "ALREADY_SIGNALED", + "ALT_MASK", + "ALWAYS", + "ANY_SAMPLES_PASSED", + "ANY_SAMPLES_PASSED_CONSERVATIVE", + "ANY_TYPE", + "ANY_UNORDERED_NODE_TYPE", + "ARRAY_BUFFER", + "ARRAY_BUFFER_BINDING", + "ATTACHED_SHADERS", + "ATTRIBUTE_NODE", + "AT_TARGET", + "AbortController", + "AbortSignal", + "AbsoluteOrientationSensor", + "AbstractRange", + "Accelerometer", + "AddSearchProvider", + "AggregateError", + "AnalyserNode", + "Animation", + "AnimationEffect", + "AnimationEvent", + "AnimationPlaybackEvent", + "AnimationTimeline", + "AnonXMLHttpRequest", + "Any", + "ApplicationCache", + "ApplicationCacheErrorEvent", + "Array", + "ArrayBuffer", + "ArrayType", + "Atomics", + "Attr", + "Audio", + "AudioBuffer", + "AudioBufferSourceNode", + "AudioContext", + "AudioDestinationNode", + "AudioListener", + "AudioNode", + "AudioParam", + "AudioParamMap", + "AudioProcessingEvent", + "AudioScheduledSourceNode", + "AudioStreamTrack", + "AudioWorklet", + "AudioWorkletNode", + "AuthenticatorAssertionResponse", + "AuthenticatorAttestationResponse", + "AuthenticatorResponse", + "AutocompleteErrorEvent", + "BACK", + "BAD_BOUNDARYPOINTS_ERR", + "BAD_REQUEST", + "BANDPASS", + "BLEND", + "BLEND_COLOR", + "BLEND_DST_ALPHA", + "BLEND_DST_RGB", + "BLEND_EQUATION", + "BLEND_EQUATION_ALPHA", + "BLEND_EQUATION_RGB", + "BLEND_SRC_ALPHA", + "BLEND_SRC_RGB", + "BLUE_BITS", + "BLUR", + "BOOL", + "BOOLEAN_TYPE", + "BOOL_VEC2", + "BOOL_VEC3", + "BOOL_VEC4", + "BOTH", + "BROWSER_DEFAULT_WEBGL", + "BUBBLING_PHASE", + "BUFFER_SIZE", + "BUFFER_USAGE", + "BYTE", + "BYTES_PER_ELEMENT", + "BackgroundFetchManager", + "BackgroundFetchRecord", + "BackgroundFetchRegistration", + "BarProp", + "BarcodeDetector", + "BaseAudioContext", + "BaseHref", + "BatteryManager", + "BeforeInstallPromptEvent", + "BeforeLoadEvent", + "BeforeUnloadEvent", + "BigInt", + "BigInt64Array", + "BigUint64Array", + "BiquadFilterNode", + "Blob", + "BlobEvent", + "Bluetooth", + "BluetoothCharacteristicProperties", + "BluetoothDevice", + "BluetoothRemoteGATTCharacteristic", + "BluetoothRemoteGATTDescriptor", + "BluetoothRemoteGATTServer", + "BluetoothRemoteGATTService", + "BluetoothUUID", + "Boolean", + "BroadcastChannel", + "ByteLengthQueuingStrategy", + "CAPTURING_PHASE", + "CCW", + "CDATASection", + "CDATA_SECTION_NODE", + "CHANGE", + "CHARSET_RULE", + "CHECKING", + "CLAMP_TO_EDGE", + "CLICK", + "CLOSED", + "CLOSING", + "COLOR", + "COLOR_ATTACHMENT0", + "COLOR_ATTACHMENT1", + "COLOR_ATTACHMENT10", + "COLOR_ATTACHMENT11", + "COLOR_ATTACHMENT12", + "COLOR_ATTACHMENT13", + "COLOR_ATTACHMENT14", + "COLOR_ATTACHMENT15", + "COLOR_ATTACHMENT2", + "COLOR_ATTACHMENT3", + "COLOR_ATTACHMENT4", + "COLOR_ATTACHMENT5", + "COLOR_ATTACHMENT6", + "COLOR_ATTACHMENT7", + "COLOR_ATTACHMENT8", + "COLOR_ATTACHMENT9", + "COLOR_BUFFER_BIT", + "COLOR_CLEAR_VALUE", + "COLOR_WRITEMASK", + "COMMENT_NODE", + "COMPARE_REF_TO_TEXTURE", + "COMPILE_STATUS", + "COMPRESSED_RGBA_S3TC_DXT1_EXT", + "COMPRESSED_RGBA_S3TC_DXT3_EXT", + "COMPRESSED_RGBA_S3TC_DXT5_EXT", + "COMPRESSED_RGB_S3TC_DXT1_EXT", + "COMPRESSED_TEXTURE_FORMATS", + "CONDITION_SATISFIED", + "CONFIGURATION_UNSUPPORTED", + "CONNECTING", + "CONSTANT_ALPHA", + "CONSTANT_COLOR", + "CONSTRAINT_ERR", + "CONTEXT_LOST_WEBGL", + "CONTROL_MASK", + "COPY_READ_BUFFER", + "COPY_READ_BUFFER_BINDING", + "COPY_WRITE_BUFFER", + "COPY_WRITE_BUFFER_BINDING", + "COUNTER_STYLE_RULE", + "CSS", + "CSS2Properties", + "CSSAnimation", + "CSSCharsetRule", + "CSSConditionRule", + "CSSCounterStyleRule", + "CSSFontFaceRule", + "CSSFontFeatureValuesRule", + "CSSGroupingRule", + "CSSImageValue", + "CSSImportRule", + "CSSKeyframeRule", + "CSSKeyframesRule", + "CSSKeywordValue", + "CSSMathInvert", + "CSSMathMax", + "CSSMathMin", + "CSSMathNegate", + "CSSMathProduct", + "CSSMathSum", + "CSSMathValue", + "CSSMatrixComponent", + "CSSMediaRule", + "CSSMozDocumentRule", + "CSSNameSpaceRule", + "CSSNamespaceRule", + "CSSNumericArray", + "CSSNumericValue", + "CSSPageRule", + "CSSPerspective", + "CSSPositionValue", + "CSSPrimitiveValue", + "CSSRotate", + "CSSRule", + "CSSRuleList", + "CSSScale", + "CSSSkew", + "CSSSkewX", + "CSSSkewY", + "CSSStyleDeclaration", + "CSSStyleRule", + "CSSStyleSheet", + "CSSStyleValue", + "CSSSupportsRule", + "CSSTransformComponent", + "CSSTransformValue", + "CSSTransition", + "CSSTranslate", + "CSSUnitValue", + "CSSUnknownRule", + "CSSUnparsedValue", + "CSSValue", + "CSSValueList", + "CSSVariableReferenceValue", + "CSSVariablesDeclaration", + "CSSVariablesRule", + "CSSViewportRule", + "CSS_ATTR", + "CSS_CM", + "CSS_COUNTER", + "CSS_CUSTOM", + "CSS_DEG", + "CSS_DIMENSION", + "CSS_EMS", + "CSS_EXS", + "CSS_FILTER_BLUR", + "CSS_FILTER_BRIGHTNESS", + "CSS_FILTER_CONTRAST", + "CSS_FILTER_CUSTOM", + "CSS_FILTER_DROP_SHADOW", + "CSS_FILTER_GRAYSCALE", + "CSS_FILTER_HUE_ROTATE", + "CSS_FILTER_INVERT", + "CSS_FILTER_OPACITY", + "CSS_FILTER_REFERENCE", + "CSS_FILTER_SATURATE", + "CSS_FILTER_SEPIA", + "CSS_GRAD", + "CSS_HZ", + "CSS_IDENT", + "CSS_IN", + "CSS_INHERIT", + "CSS_KHZ", + "CSS_MATRIX", + "CSS_MATRIX3D", + "CSS_MM", + "CSS_MS", + "CSS_NUMBER", + "CSS_PC", + "CSS_PERCENTAGE", + "CSS_PERSPECTIVE", + "CSS_PRIMITIVE_VALUE", + "CSS_PT", + "CSS_PX", + "CSS_RAD", + "CSS_RECT", + "CSS_RGBCOLOR", + "CSS_ROTATE", + "CSS_ROTATE3D", + "CSS_ROTATEX", + "CSS_ROTATEY", + "CSS_ROTATEZ", + "CSS_S", + "CSS_SCALE", + "CSS_SCALE3D", + "CSS_SCALEX", + "CSS_SCALEY", + "CSS_SCALEZ", + "CSS_SKEW", + "CSS_SKEWX", + "CSS_SKEWY", + "CSS_STRING", + "CSS_TRANSLATE", + "CSS_TRANSLATE3D", + "CSS_TRANSLATEX", + "CSS_TRANSLATEY", + "CSS_TRANSLATEZ", + "CSS_UNKNOWN", + "CSS_URI", + "CSS_VALUE_LIST", + "CSS_VH", + "CSS_VMAX", + "CSS_VMIN", + "CSS_VW", + "CULL_FACE", + "CULL_FACE_MODE", + "CURRENT_PROGRAM", + "CURRENT_QUERY", + "CURRENT_VERTEX_ATTRIB", + "CUSTOM", + "CW", + "Cache", + "CacheStorage", + "CanvasCaptureMediaStream", + "CanvasCaptureMediaStreamTrack", + "CanvasGradient", + "CanvasPattern", + "CanvasRenderingContext2D", + "CaretPosition", + "ChannelMergerNode", + "ChannelSplitterNode", + "CharacterData", + "ClientRect", + "ClientRectList", + "Clipboard", + "ClipboardEvent", + "ClipboardItem", + "CloseEvent", + "Collator", + "CommandEvent", + "Comment", + "CompileError", + "CompositionEvent", + "CompressionStream", + "Console", + "ConstantSourceNode", + "Controllers", + "ConvolverNode", + "CountQueuingStrategy", + "Counter", + "Credential", + "CredentialsContainer", + "Crypto", + "CryptoKey", + "CustomElementRegistry", + "CustomEvent", + "DATABASE_ERR", + "DATA_CLONE_ERR", + "DATA_ERR", + "DBLCLICK", + "DECR", + "DECR_WRAP", + "DELETE_STATUS", + "DEPTH", + "DEPTH24_STENCIL8", + "DEPTH32F_STENCIL8", + "DEPTH_ATTACHMENT", + "DEPTH_BITS", + "DEPTH_BUFFER_BIT", + "DEPTH_CLEAR_VALUE", + "DEPTH_COMPONENT", + "DEPTH_COMPONENT16", + "DEPTH_COMPONENT24", + "DEPTH_COMPONENT32F", + "DEPTH_FUNC", + "DEPTH_RANGE", + "DEPTH_STENCIL", + "DEPTH_STENCIL_ATTACHMENT", + "DEPTH_TEST", + "DEPTH_WRITEMASK", + "DEVICE_INELIGIBLE", + "DIRECTION_DOWN", + "DIRECTION_LEFT", + "DIRECTION_RIGHT", + "DIRECTION_UP", + "DISABLED", + "DISPATCH_REQUEST_ERR", + "DITHER", + "DOCUMENT_FRAGMENT_NODE", + "DOCUMENT_NODE", + "DOCUMENT_POSITION_CONTAINED_BY", + "DOCUMENT_POSITION_CONTAINS", + "DOCUMENT_POSITION_DISCONNECTED", + "DOCUMENT_POSITION_FOLLOWING", + "DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC", + "DOCUMENT_POSITION_PRECEDING", + "DOCUMENT_TYPE_NODE", + "DOMCursor", + "DOMError", + "DOMException", + "DOMImplementation", + "DOMImplementationLS", + "DOMMatrix", + "DOMMatrixReadOnly", + "DOMParser", + "DOMPoint", + "DOMPointReadOnly", + "DOMQuad", + "DOMRect", + "DOMRectList", + "DOMRectReadOnly", + "DOMRequest", + "DOMSTRING_SIZE_ERR", + "DOMSettableTokenList", + "DOMStringList", + "DOMStringMap", + "DOMTokenList", + "DOMTransactionEvent", + "DOM_DELTA_LINE", + "DOM_DELTA_PAGE", + "DOM_DELTA_PIXEL", + "DOM_INPUT_METHOD_DROP", + "DOM_INPUT_METHOD_HANDWRITING", + "DOM_INPUT_METHOD_IME", + "DOM_INPUT_METHOD_KEYBOARD", + "DOM_INPUT_METHOD_MULTIMODAL", + "DOM_INPUT_METHOD_OPTION", + "DOM_INPUT_METHOD_PASTE", + "DOM_INPUT_METHOD_SCRIPT", + "DOM_INPUT_METHOD_UNKNOWN", + "DOM_INPUT_METHOD_VOICE", + "DOM_KEY_LOCATION_JOYSTICK", + "DOM_KEY_LOCATION_LEFT", + "DOM_KEY_LOCATION_MOBILE", + "DOM_KEY_LOCATION_NUMPAD", + "DOM_KEY_LOCATION_RIGHT", + "DOM_KEY_LOCATION_STANDARD", + "DOM_VK_0", + "DOM_VK_1", + "DOM_VK_2", + "DOM_VK_3", + "DOM_VK_4", + "DOM_VK_5", + "DOM_VK_6", + "DOM_VK_7", + "DOM_VK_8", + "DOM_VK_9", + "DOM_VK_A", + "DOM_VK_ACCEPT", + "DOM_VK_ADD", + "DOM_VK_ALT", + "DOM_VK_ALTGR", + "DOM_VK_AMPERSAND", + "DOM_VK_ASTERISK", + "DOM_VK_AT", + "DOM_VK_ATTN", + "DOM_VK_B", + "DOM_VK_BACKSPACE", + "DOM_VK_BACK_QUOTE", + "DOM_VK_BACK_SLASH", + "DOM_VK_BACK_SPACE", + "DOM_VK_C", + "DOM_VK_CANCEL", + "DOM_VK_CAPS_LOCK", + "DOM_VK_CIRCUMFLEX", + "DOM_VK_CLEAR", + "DOM_VK_CLOSE_BRACKET", + "DOM_VK_CLOSE_CURLY_BRACKET", + "DOM_VK_CLOSE_PAREN", + "DOM_VK_COLON", + "DOM_VK_COMMA", + "DOM_VK_CONTEXT_MENU", + "DOM_VK_CONTROL", + "DOM_VK_CONVERT", + "DOM_VK_CRSEL", + "DOM_VK_CTRL", + "DOM_VK_D", + "DOM_VK_DECIMAL", + "DOM_VK_DELETE", + "DOM_VK_DIVIDE", + "DOM_VK_DOLLAR", + "DOM_VK_DOUBLE_QUOTE", + "DOM_VK_DOWN", + "DOM_VK_E", + "DOM_VK_EISU", + "DOM_VK_END", + "DOM_VK_ENTER", + "DOM_VK_EQUALS", + "DOM_VK_EREOF", + "DOM_VK_ESCAPE", + "DOM_VK_EXCLAMATION", + "DOM_VK_EXECUTE", + "DOM_VK_EXSEL", + "DOM_VK_F", + "DOM_VK_F1", + "DOM_VK_F10", + "DOM_VK_F11", + "DOM_VK_F12", + "DOM_VK_F13", + "DOM_VK_F14", + "DOM_VK_F15", + "DOM_VK_F16", + "DOM_VK_F17", + "DOM_VK_F18", + "DOM_VK_F19", + "DOM_VK_F2", + "DOM_VK_F20", + "DOM_VK_F21", + "DOM_VK_F22", + "DOM_VK_F23", + "DOM_VK_F24", + "DOM_VK_F25", + "DOM_VK_F26", + "DOM_VK_F27", + "DOM_VK_F28", + "DOM_VK_F29", + "DOM_VK_F3", + "DOM_VK_F30", + "DOM_VK_F31", + "DOM_VK_F32", + "DOM_VK_F33", + "DOM_VK_F34", + "DOM_VK_F35", + "DOM_VK_F36", + "DOM_VK_F4", + "DOM_VK_F5", + "DOM_VK_F6", + "DOM_VK_F7", + "DOM_VK_F8", + "DOM_VK_F9", + "DOM_VK_FINAL", + "DOM_VK_FRONT", + "DOM_VK_G", + "DOM_VK_GREATER_THAN", + "DOM_VK_H", + "DOM_VK_HANGUL", + "DOM_VK_HANJA", + "DOM_VK_HASH", + "DOM_VK_HELP", + "DOM_VK_HK_TOGGLE", + "DOM_VK_HOME", + "DOM_VK_HYPHEN_MINUS", + "DOM_VK_I", + "DOM_VK_INSERT", + "DOM_VK_J", + "DOM_VK_JUNJA", + "DOM_VK_K", + "DOM_VK_KANA", + "DOM_VK_KANJI", + "DOM_VK_L", + "DOM_VK_LEFT", + "DOM_VK_LEFT_TAB", + "DOM_VK_LESS_THAN", + "DOM_VK_M", + "DOM_VK_META", + "DOM_VK_MODECHANGE", + "DOM_VK_MULTIPLY", + "DOM_VK_N", + "DOM_VK_NONCONVERT", + "DOM_VK_NUMPAD0", + "DOM_VK_NUMPAD1", + "DOM_VK_NUMPAD2", + "DOM_VK_NUMPAD3", + "DOM_VK_NUMPAD4", + "DOM_VK_NUMPAD5", + "DOM_VK_NUMPAD6", + "DOM_VK_NUMPAD7", + "DOM_VK_NUMPAD8", + "DOM_VK_NUMPAD9", + "DOM_VK_NUM_LOCK", + "DOM_VK_O", + "DOM_VK_OEM_1", + "DOM_VK_OEM_102", + "DOM_VK_OEM_2", + "DOM_VK_OEM_3", + "DOM_VK_OEM_4", + "DOM_VK_OEM_5", + "DOM_VK_OEM_6", + "DOM_VK_OEM_7", + "DOM_VK_OEM_8", + "DOM_VK_OEM_COMMA", + "DOM_VK_OEM_MINUS", + "DOM_VK_OEM_PERIOD", + "DOM_VK_OEM_PLUS", + "DOM_VK_OPEN_BRACKET", + "DOM_VK_OPEN_CURLY_BRACKET", + "DOM_VK_OPEN_PAREN", + "DOM_VK_P", + "DOM_VK_PA1", + "DOM_VK_PAGEDOWN", + "DOM_VK_PAGEUP", + "DOM_VK_PAGE_DOWN", + "DOM_VK_PAGE_UP", + "DOM_VK_PAUSE", + "DOM_VK_PERCENT", + "DOM_VK_PERIOD", + "DOM_VK_PIPE", + "DOM_VK_PLAY", + "DOM_VK_PLUS", + "DOM_VK_PRINT", + "DOM_VK_PRINTSCREEN", + "DOM_VK_PROCESSKEY", + "DOM_VK_PROPERITES", + "DOM_VK_Q", + "DOM_VK_QUESTION_MARK", + "DOM_VK_QUOTE", + "DOM_VK_R", + "DOM_VK_REDO", + "DOM_VK_RETURN", + "DOM_VK_RIGHT", + "DOM_VK_S", + "DOM_VK_SCROLL_LOCK", + "DOM_VK_SELECT", + "DOM_VK_SEMICOLON", + "DOM_VK_SEPARATOR", + "DOM_VK_SHIFT", + "DOM_VK_SLASH", + "DOM_VK_SLEEP", + "DOM_VK_SPACE", + "DOM_VK_SUBTRACT", + "DOM_VK_T", + "DOM_VK_TAB", + "DOM_VK_TILDE", + "DOM_VK_U", + "DOM_VK_UNDERSCORE", + "DOM_VK_UNDO", + "DOM_VK_UNICODE", + "DOM_VK_UP", + "DOM_VK_V", + "DOM_VK_VOLUME_DOWN", + "DOM_VK_VOLUME_MUTE", + "DOM_VK_VOLUME_UP", + "DOM_VK_W", + "DOM_VK_WIN", + "DOM_VK_WINDOW", + "DOM_VK_WIN_ICO_00", + "DOM_VK_WIN_ICO_CLEAR", + "DOM_VK_WIN_ICO_HELP", + "DOM_VK_WIN_OEM_ATTN", + "DOM_VK_WIN_OEM_AUTO", + "DOM_VK_WIN_OEM_BACKTAB", + "DOM_VK_WIN_OEM_CLEAR", + "DOM_VK_WIN_OEM_COPY", + "DOM_VK_WIN_OEM_CUSEL", + "DOM_VK_WIN_OEM_ENLW", + "DOM_VK_WIN_OEM_FINISH", + "DOM_VK_WIN_OEM_FJ_JISHO", + "DOM_VK_WIN_OEM_FJ_LOYA", + "DOM_VK_WIN_OEM_FJ_MASSHOU", + "DOM_VK_WIN_OEM_FJ_ROYA", + "DOM_VK_WIN_OEM_FJ_TOUROKU", + "DOM_VK_WIN_OEM_JUMP", + "DOM_VK_WIN_OEM_PA1", + "DOM_VK_WIN_OEM_PA2", + "DOM_VK_WIN_OEM_PA3", + "DOM_VK_WIN_OEM_RESET", + "DOM_VK_WIN_OEM_WSCTRL", + "DOM_VK_X", + "DOM_VK_XF86XK_ADD_FAVORITE", + "DOM_VK_XF86XK_APPLICATION_LEFT", + "DOM_VK_XF86XK_APPLICATION_RIGHT", + "DOM_VK_XF86XK_AUDIO_CYCLE_TRACK", + "DOM_VK_XF86XK_AUDIO_FORWARD", + "DOM_VK_XF86XK_AUDIO_LOWER_VOLUME", + "DOM_VK_XF86XK_AUDIO_MEDIA", + "DOM_VK_XF86XK_AUDIO_MUTE", + "DOM_VK_XF86XK_AUDIO_NEXT", + "DOM_VK_XF86XK_AUDIO_PAUSE", + "DOM_VK_XF86XK_AUDIO_PLAY", + "DOM_VK_XF86XK_AUDIO_PREV", + "DOM_VK_XF86XK_AUDIO_RAISE_VOLUME", + "DOM_VK_XF86XK_AUDIO_RANDOM_PLAY", + "DOM_VK_XF86XK_AUDIO_RECORD", + "DOM_VK_XF86XK_AUDIO_REPEAT", + "DOM_VK_XF86XK_AUDIO_REWIND", + "DOM_VK_XF86XK_AUDIO_STOP", + "DOM_VK_XF86XK_AWAY", + "DOM_VK_XF86XK_BACK", + "DOM_VK_XF86XK_BACK_FORWARD", + "DOM_VK_XF86XK_BATTERY", + "DOM_VK_XF86XK_BLUE", + "DOM_VK_XF86XK_BLUETOOTH", + "DOM_VK_XF86XK_BOOK", + "DOM_VK_XF86XK_BRIGHTNESS_ADJUST", + "DOM_VK_XF86XK_CALCULATOR", + "DOM_VK_XF86XK_CALENDAR", + "DOM_VK_XF86XK_CD", + "DOM_VK_XF86XK_CLOSE", + "DOM_VK_XF86XK_COMMUNITY", + "DOM_VK_XF86XK_CONTRAST_ADJUST", + "DOM_VK_XF86XK_COPY", + "DOM_VK_XF86XK_CUT", + "DOM_VK_XF86XK_CYCLE_ANGLE", + "DOM_VK_XF86XK_DISPLAY", + "DOM_VK_XF86XK_DOCUMENTS", + "DOM_VK_XF86XK_DOS", + "DOM_VK_XF86XK_EJECT", + "DOM_VK_XF86XK_EXCEL", + "DOM_VK_XF86XK_EXPLORER", + "DOM_VK_XF86XK_FAVORITES", + "DOM_VK_XF86XK_FINANCE", + "DOM_VK_XF86XK_FORWARD", + "DOM_VK_XF86XK_FRAME_BACK", + "DOM_VK_XF86XK_FRAME_FORWARD", + "DOM_VK_XF86XK_GAME", + "DOM_VK_XF86XK_GO", + "DOM_VK_XF86XK_GREEN", + "DOM_VK_XF86XK_HIBERNATE", + "DOM_VK_XF86XK_HISTORY", + "DOM_VK_XF86XK_HOME_PAGE", + "DOM_VK_XF86XK_HOT_LINKS", + "DOM_VK_XF86XK_I_TOUCH", + "DOM_VK_XF86XK_KBD_BRIGHTNESS_DOWN", + "DOM_VK_XF86XK_KBD_BRIGHTNESS_UP", + "DOM_VK_XF86XK_KBD_LIGHT_ON_OFF", + "DOM_VK_XF86XK_LAUNCH0", + "DOM_VK_XF86XK_LAUNCH1", + "DOM_VK_XF86XK_LAUNCH2", + "DOM_VK_XF86XK_LAUNCH3", + "DOM_VK_XF86XK_LAUNCH4", + "DOM_VK_XF86XK_LAUNCH5", + "DOM_VK_XF86XK_LAUNCH6", + "DOM_VK_XF86XK_LAUNCH7", + "DOM_VK_XF86XK_LAUNCH8", + "DOM_VK_XF86XK_LAUNCH9", + "DOM_VK_XF86XK_LAUNCH_A", + "DOM_VK_XF86XK_LAUNCH_B", + "DOM_VK_XF86XK_LAUNCH_C", + "DOM_VK_XF86XK_LAUNCH_D", + "DOM_VK_XF86XK_LAUNCH_E", + "DOM_VK_XF86XK_LAUNCH_F", + "DOM_VK_XF86XK_LIGHT_BULB", + "DOM_VK_XF86XK_LOG_OFF", + "DOM_VK_XF86XK_MAIL", + "DOM_VK_XF86XK_MAIL_FORWARD", + "DOM_VK_XF86XK_MARKET", + "DOM_VK_XF86XK_MEETING", + "DOM_VK_XF86XK_MEMO", + "DOM_VK_XF86XK_MENU_KB", + "DOM_VK_XF86XK_MENU_PB", + "DOM_VK_XF86XK_MESSENGER", + "DOM_VK_XF86XK_MON_BRIGHTNESS_DOWN", + "DOM_VK_XF86XK_MON_BRIGHTNESS_UP", + "DOM_VK_XF86XK_MUSIC", + "DOM_VK_XF86XK_MY_COMPUTER", + "DOM_VK_XF86XK_MY_SITES", + "DOM_VK_XF86XK_NEW", + "DOM_VK_XF86XK_NEWS", + "DOM_VK_XF86XK_OFFICE_HOME", + "DOM_VK_XF86XK_OPEN", + "DOM_VK_XF86XK_OPEN_URL", + "DOM_VK_XF86XK_OPTION", + "DOM_VK_XF86XK_PASTE", + "DOM_VK_XF86XK_PHONE", + "DOM_VK_XF86XK_PICTURES", + "DOM_VK_XF86XK_POWER_DOWN", + "DOM_VK_XF86XK_POWER_OFF", + "DOM_VK_XF86XK_RED", + "DOM_VK_XF86XK_REFRESH", + "DOM_VK_XF86XK_RELOAD", + "DOM_VK_XF86XK_REPLY", + "DOM_VK_XF86XK_ROCKER_DOWN", + "DOM_VK_XF86XK_ROCKER_ENTER", + "DOM_VK_XF86XK_ROCKER_UP", + "DOM_VK_XF86XK_ROTATE_WINDOWS", + "DOM_VK_XF86XK_ROTATION_KB", + "DOM_VK_XF86XK_ROTATION_PB", + "DOM_VK_XF86XK_SAVE", + "DOM_VK_XF86XK_SCREEN_SAVER", + "DOM_VK_XF86XK_SCROLL_CLICK", + "DOM_VK_XF86XK_SCROLL_DOWN", + "DOM_VK_XF86XK_SCROLL_UP", + "DOM_VK_XF86XK_SEARCH", + "DOM_VK_XF86XK_SEND", + "DOM_VK_XF86XK_SHOP", + "DOM_VK_XF86XK_SPELL", + "DOM_VK_XF86XK_SPLIT_SCREEN", + "DOM_VK_XF86XK_STANDBY", + "DOM_VK_XF86XK_START", + "DOM_VK_XF86XK_STOP", + "DOM_VK_XF86XK_SUBTITLE", + "DOM_VK_XF86XK_SUPPORT", + "DOM_VK_XF86XK_SUSPEND", + "DOM_VK_XF86XK_TASK_PANE", + "DOM_VK_XF86XK_TERMINAL", + "DOM_VK_XF86XK_TIME", + "DOM_VK_XF86XK_TOOLS", + "DOM_VK_XF86XK_TOP_MENU", + "DOM_VK_XF86XK_TO_DO_LIST", + "DOM_VK_XF86XK_TRAVEL", + "DOM_VK_XF86XK_USER1KB", + "DOM_VK_XF86XK_USER2KB", + "DOM_VK_XF86XK_USER_PB", + "DOM_VK_XF86XK_UWB", + "DOM_VK_XF86XK_VENDOR_HOME", + "DOM_VK_XF86XK_VIDEO", + "DOM_VK_XF86XK_VIEW", + "DOM_VK_XF86XK_WAKE_UP", + "DOM_VK_XF86XK_WEB_CAM", + "DOM_VK_XF86XK_WHEEL_BUTTON", + "DOM_VK_XF86XK_WLAN", + "DOM_VK_XF86XK_WORD", + "DOM_VK_XF86XK_WWW", + "DOM_VK_XF86XK_XFER", + "DOM_VK_XF86XK_YELLOW", + "DOM_VK_XF86XK_ZOOM_IN", + "DOM_VK_XF86XK_ZOOM_OUT", + "DOM_VK_Y", + "DOM_VK_Z", + "DOM_VK_ZOOM", + "DONE", + "DONT_CARE", + "DOWNLOADING", + "DRAGDROP", + "DRAW_BUFFER0", + "DRAW_BUFFER1", + "DRAW_BUFFER10", + "DRAW_BUFFER11", + "DRAW_BUFFER12", + "DRAW_BUFFER13", + "DRAW_BUFFER14", + "DRAW_BUFFER15", + "DRAW_BUFFER2", + "DRAW_BUFFER3", + "DRAW_BUFFER4", + "DRAW_BUFFER5", + "DRAW_BUFFER6", + "DRAW_BUFFER7", + "DRAW_BUFFER8", + "DRAW_BUFFER9", + "DRAW_FRAMEBUFFER", + "DRAW_FRAMEBUFFER_BINDING", + "DST_ALPHA", + "DST_COLOR", + "DYNAMIC_COPY", + "DYNAMIC_DRAW", + "DYNAMIC_READ", + "DataChannel", + "DataTransfer", + "DataTransferItem", + "DataTransferItemList", + "DataView", + "Date", + "DateTimeFormat", + "DecompressionStream", + "DelayNode", + "DeprecationReportBody", + "DesktopNotification", + "DesktopNotificationCenter", + "DeviceLightEvent", + "DeviceMotionEvent", + "DeviceMotionEventAcceleration", + "DeviceMotionEventRotationRate", + "DeviceOrientationEvent", + "DeviceProximityEvent", + "DeviceStorage", + "DeviceStorageChangeEvent", + "Directory", + "DisplayNames", + "Document", + "DocumentFragment", + "DocumentTimeline", + "DocumentType", + "DragEvent", + "DynamicsCompressorNode", + "E", + "ELEMENT_ARRAY_BUFFER", + "ELEMENT_ARRAY_BUFFER_BINDING", + "ELEMENT_NODE", + "EMPTY", + "ENCODING_ERR", + "ENDED", + "END_TO_END", + "END_TO_START", + "ENTITY_NODE", + "ENTITY_REFERENCE_NODE", + "EPSILON", + "EQUAL", + "EQUALPOWER", + "ERROR", + "EXPONENTIAL_DISTANCE", + "Element", + "ElementInternals", + "ElementQuery", + "EnterPictureInPictureEvent", + "Entity", + "EntityReference", + "Error", + "ErrorEvent", + "EvalError", + "Event", + "EventException", + "EventSource", + "EventTarget", + "External", + "FASTEST", + "FIDOSDK", + "FILTER_ACCEPT", + "FILTER_INTERRUPT", + "FILTER_REJECT", + "FILTER_SKIP", + "FINISHED_STATE", + "FIRST_ORDERED_NODE_TYPE", + "FLOAT", + "FLOAT_32_UNSIGNED_INT_24_8_REV", + "FLOAT_MAT2", + "FLOAT_MAT2x3", + "FLOAT_MAT2x4", + "FLOAT_MAT3", + "FLOAT_MAT3x2", + "FLOAT_MAT3x4", + "FLOAT_MAT4", + "FLOAT_MAT4x2", + "FLOAT_MAT4x3", + "FLOAT_VEC2", + "FLOAT_VEC3", + "FLOAT_VEC4", + "FOCUS", + "FONT_FACE_RULE", + "FONT_FEATURE_VALUES_RULE", + "FRAGMENT_SHADER", + "FRAGMENT_SHADER_DERIVATIVE_HINT", + "FRAGMENT_SHADER_DERIVATIVE_HINT_OES", + "FRAMEBUFFER", + "FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE", + "FRAMEBUFFER_ATTACHMENT_BLUE_SIZE", + "FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING", + "FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE", + "FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE", + "FRAMEBUFFER_ATTACHMENT_GREEN_SIZE", + "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME", + "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE", + "FRAMEBUFFER_ATTACHMENT_RED_SIZE", + "FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL", + "FRAMEBUFFER_BINDING", + "FRAMEBUFFER_COMPLETE", + "FRAMEBUFFER_DEFAULT", + "FRAMEBUFFER_INCOMPLETE_ATTACHMENT", + "FRAMEBUFFER_INCOMPLETE_DIMENSIONS", + "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", + "FRAMEBUFFER_INCOMPLETE_MULTISAMPLE", + "FRAMEBUFFER_UNSUPPORTED", + "FRONT", + "FRONT_AND_BACK", + "FRONT_FACE", + "FUNC_ADD", + "FUNC_REVERSE_SUBTRACT", + "FUNC_SUBTRACT", + "FeaturePolicy", + "FeaturePolicyViolationReportBody", + "FederatedCredential", + "Feed", + "FeedEntry", + "File", + "FileError", + "FileList", + "FileReader", + "FileSystem", + "FileSystemDirectoryEntry", + "FileSystemDirectoryReader", + "FileSystemEntry", + "FileSystemFileEntry", + "FinalizationRegistry", + "FindInPage", + "Float32Array", + "Float64Array", + "FocusEvent", + "FontFace", + "FontFaceSet", + "FontFaceSetLoadEvent", + "FormData", + "FormDataEvent", + "FragmentDirective", + "Function", + "GENERATE_MIPMAP_HINT", + "GEQUAL", + "GREATER", + "GREEN_BITS", + "GainNode", + "Gamepad", + "GamepadAxisMoveEvent", + "GamepadButton", + "GamepadButtonEvent", + "GamepadEvent", + "GamepadHapticActuator", + "GamepadPose", + "Geolocation", + "GeolocationCoordinates", + "GeolocationPosition", + "GeolocationPositionError", + "GestureEvent", + "Global", + "Gyroscope", + "HALF_FLOAT", + "HAVE_CURRENT_DATA", + "HAVE_ENOUGH_DATA", + "HAVE_FUTURE_DATA", + "HAVE_METADATA", + "HAVE_NOTHING", + "HEADERS_RECEIVED", + "HIDDEN", + "HIERARCHY_REQUEST_ERR", + "HIGHPASS", + "HIGHSHELF", + "HIGH_FLOAT", + "HIGH_INT", + "HORIZONTAL", + "HORIZONTAL_AXIS", + "HRTF", + "HTMLAllCollection", + "HTMLAnchorElement", + "HTMLAppletElement", + "HTMLAreaElement", + "HTMLAudioElement", + "HTMLBRElement", + "HTMLBaseElement", + "HTMLBaseFontElement", + "HTMLBlockquoteElement", + "HTMLBodyElement", + "HTMLButtonElement", + "HTMLCanvasElement", + "HTMLCollection", + "HTMLCommandElement", + "HTMLContentElement", + "HTMLDListElement", + "HTMLDataElement", + "HTMLDataListElement", + "HTMLDetailsElement", + "HTMLDialogElement", + "HTMLDirectoryElement", + "HTMLDivElement", + "HTMLDocument", + "HTMLElement", + "HTMLEmbedElement", + "HTMLFieldSetElement", + "HTMLFontElement", + "HTMLFormControlsCollection", + "HTMLFormElement", + "HTMLFrameElement", + "HTMLFrameSetElement", + "HTMLHRElement", + "HTMLHeadElement", + "HTMLHeadingElement", + "HTMLHtmlElement", + "HTMLIFrameElement", + "HTMLImageElement", + "HTMLInputElement", + "HTMLIsIndexElement", + "HTMLKeygenElement", + "HTMLLIElement", + "HTMLLabelElement", + "HTMLLegendElement", + "HTMLLinkElement", + "HTMLMapElement", + "HTMLMarqueeElement", + "HTMLMediaElement", + "HTMLMenuElement", + "HTMLMenuItemElement", + "HTMLMetaElement", + "HTMLMeterElement", + "HTMLModElement", + "HTMLOListElement", + "HTMLObjectElement", + "HTMLOptGroupElement", + "HTMLOptionElement", + "HTMLOptionsCollection", + "HTMLOutputElement", + "HTMLParagraphElement", + "HTMLParamElement", + "HTMLPictureElement", + "HTMLPreElement", + "HTMLProgressElement", + "HTMLPropertiesCollection", + "HTMLQuoteElement", + "HTMLScriptElement", + "HTMLSelectElement", + "HTMLShadowElement", + "HTMLSlotElement", + "HTMLSourceElement", + "HTMLSpanElement", + "HTMLStyleElement", + "HTMLTableCaptionElement", + "HTMLTableCellElement", + "HTMLTableColElement", + "HTMLTableElement", + "HTMLTableRowElement", + "HTMLTableSectionElement", + "HTMLTemplateElement", + "HTMLTextAreaElement", + "HTMLTimeElement", + "HTMLTitleElement", + "HTMLTrackElement", + "HTMLUListElement", + "HTMLUnknownElement", + "HTMLVideoElement", + "HashChangeEvent", + "Headers", + "History", + "Hz", + "ICE_CHECKING", + "ICE_CLOSED", + "ICE_COMPLETED", + "ICE_CONNECTED", + "ICE_FAILED", + "ICE_GATHERING", + "ICE_WAITING", + "IDBCursor", + "IDBCursorWithValue", + "IDBDatabase", + "IDBDatabaseException", + "IDBFactory", + "IDBFileHandle", + "IDBFileRequest", + "IDBIndex", + "IDBKeyRange", + "IDBMutableFile", + "IDBObjectStore", + "IDBOpenDBRequest", + "IDBRequest", + "IDBTransaction", + "IDBVersionChangeEvent", + "IDLE", + "IIRFilterNode", + "IMPLEMENTATION_COLOR_READ_FORMAT", + "IMPLEMENTATION_COLOR_READ_TYPE", + "IMPORT_RULE", + "INCR", + "INCR_WRAP", + "INDEX_SIZE_ERR", + "INT", + "INTERLEAVED_ATTRIBS", + "INT_2_10_10_10_REV", + "INT_SAMPLER_2D", + "INT_SAMPLER_2D_ARRAY", + "INT_SAMPLER_3D", + "INT_SAMPLER_CUBE", + "INT_VEC2", + "INT_VEC3", + "INT_VEC4", + "INUSE_ATTRIBUTE_ERR", + "INVALID_ACCESS_ERR", + "INVALID_CHARACTER_ERR", + "INVALID_ENUM", + "INVALID_EXPRESSION_ERR", + "INVALID_FRAMEBUFFER_OPERATION", + "INVALID_INDEX", + "INVALID_MODIFICATION_ERR", + "INVALID_NODE_TYPE_ERR", + "INVALID_OPERATION", + "INVALID_STATE_ERR", + "INVALID_VALUE", + "INVERSE_DISTANCE", + "INVERT", + "IceCandidate", + "IdleDeadline", + "Image", + "ImageBitmap", + "ImageBitmapRenderingContext", + "ImageCapture", + "ImageData", + "Infinity", + "InputDeviceCapabilities", + "InputDeviceInfo", + "InputEvent", + "InputMethodContext", + "InstallTrigger", + "InstallTriggerImpl", + "Instance", + "Int16Array", + "Int32Array", + "Int8Array", + "Intent", + "InternalError", + "IntersectionObserver", + "IntersectionObserverEntry", + "Intl", + "IsSearchProviderInstalled", + "Iterator", + "JSON", + "KEEP", + "KEYDOWN", + "KEYFRAMES_RULE", + "KEYFRAME_RULE", + "KEYPRESS", + "KEYUP", + "KeyEvent", + "Keyboard", + "KeyboardEvent", + "KeyboardLayoutMap", + "KeyframeEffect", + "LENGTHADJUST_SPACING", + "LENGTHADJUST_SPACINGANDGLYPHS", + "LENGTHADJUST_UNKNOWN", + "LEQUAL", + "LESS", + "LINEAR", + "LINEAR_DISTANCE", + "LINEAR_MIPMAP_LINEAR", + "LINEAR_MIPMAP_NEAREST", + "LINES", + "LINE_LOOP", + "LINE_STRIP", + "LINE_WIDTH", + "LINK_STATUS", + "LIVE", + "LN10", + "LN2", + "LOADED", + "LOADING", + "LOG10E", + "LOG2E", + "LOWPASS", + "LOWSHELF", + "LOW_FLOAT", + "LOW_INT", + "LSException", + "LSParserFilter", + "LUMINANCE", + "LUMINANCE_ALPHA", + "LargestContentfulPaint", + "LayoutShift", + "LayoutShiftAttribution", + "LinearAccelerationSensor", + "LinkError", + "ListFormat", + "LocalMediaStream", + "Locale", + "Location", + "Lock", + "LockManager", + "MAX", + "MAX_3D_TEXTURE_SIZE", + "MAX_ARRAY_TEXTURE_LAYERS", + "MAX_CLIENT_WAIT_TIMEOUT_WEBGL", + "MAX_COLOR_ATTACHMENTS", + "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS", + "MAX_COMBINED_TEXTURE_IMAGE_UNITS", + "MAX_COMBINED_UNIFORM_BLOCKS", + "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS", + "MAX_CUBE_MAP_TEXTURE_SIZE", + "MAX_DRAW_BUFFERS", + "MAX_ELEMENTS_INDICES", + "MAX_ELEMENTS_VERTICES", + "MAX_ELEMENT_INDEX", + "MAX_FRAGMENT_INPUT_COMPONENTS", + "MAX_FRAGMENT_UNIFORM_BLOCKS", + "MAX_FRAGMENT_UNIFORM_COMPONENTS", + "MAX_FRAGMENT_UNIFORM_VECTORS", + "MAX_PROGRAM_TEXEL_OFFSET", + "MAX_RENDERBUFFER_SIZE", + "MAX_SAFE_INTEGER", + "MAX_SAMPLES", + "MAX_SERVER_WAIT_TIMEOUT", + "MAX_TEXTURE_IMAGE_UNITS", + "MAX_TEXTURE_LOD_BIAS", + "MAX_TEXTURE_MAX_ANISOTROPY_EXT", + "MAX_TEXTURE_SIZE", + "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS", + "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS", + "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS", + "MAX_UNIFORM_BLOCK_SIZE", + "MAX_UNIFORM_BUFFER_BINDINGS", + "MAX_VALUE", + "MAX_VARYING_COMPONENTS", + "MAX_VARYING_VECTORS", + "MAX_VERTEX_ATTRIBS", + "MAX_VERTEX_OUTPUT_COMPONENTS", + "MAX_VERTEX_TEXTURE_IMAGE_UNITS", + "MAX_VERTEX_UNIFORM_BLOCKS", + "MAX_VERTEX_UNIFORM_COMPONENTS", + "MAX_VERTEX_UNIFORM_VECTORS", + "MAX_VIEWPORT_DIMS", + "MEDIA_ERR_ABORTED", + "MEDIA_ERR_DECODE", + "MEDIA_ERR_ENCRYPTED", + "MEDIA_ERR_NETWORK", + "MEDIA_ERR_SRC_NOT_SUPPORTED", + "MEDIA_KEYERR_CLIENT", + "MEDIA_KEYERR_DOMAIN", + "MEDIA_KEYERR_HARDWARECHANGE", + "MEDIA_KEYERR_OUTPUT", + "MEDIA_KEYERR_SERVICE", + "MEDIA_KEYERR_UNKNOWN", + "MEDIA_RULE", + "MEDIUM_FLOAT", + "MEDIUM_INT", + "META_MASK", + "MIDIAccess", + "MIDIConnectionEvent", + "MIDIInput", + "MIDIInputMap", + "MIDIMessageEvent", + "MIDIOutput", + "MIDIOutputMap", + "MIDIPort", + "MIN", + "MIN_PROGRAM_TEXEL_OFFSET", + "MIN_SAFE_INTEGER", + "MIN_VALUE", + "MIRRORED_REPEAT", + "MODE_ASYNCHRONOUS", + "MODE_SYNCHRONOUS", + "MODIFICATION", + "MOUSEDOWN", + "MOUSEDRAG", + "MOUSEMOVE", + "MOUSEOUT", + "MOUSEOVER", + "MOUSEUP", + "MOZ_KEYFRAMES_RULE", + "MOZ_KEYFRAME_RULE", + "MOZ_SOURCE_CURSOR", + "MOZ_SOURCE_ERASER", + "MOZ_SOURCE_KEYBOARD", + "MOZ_SOURCE_MOUSE", + "MOZ_SOURCE_PEN", + "MOZ_SOURCE_TOUCH", + "MOZ_SOURCE_UNKNOWN", + "MSGESTURE_FLAG_BEGIN", + "MSGESTURE_FLAG_CANCEL", + "MSGESTURE_FLAG_END", + "MSGESTURE_FLAG_INERTIA", + "MSGESTURE_FLAG_NONE", + "MSPOINTER_TYPE_MOUSE", + "MSPOINTER_TYPE_PEN", + "MSPOINTER_TYPE_TOUCH", + "MS_ASYNC_CALLBACK_STATUS_ASSIGN_DELEGATE", + "MS_ASYNC_CALLBACK_STATUS_CANCEL", + "MS_ASYNC_CALLBACK_STATUS_CHOOSEANY", + "MS_ASYNC_CALLBACK_STATUS_ERROR", + "MS_ASYNC_CALLBACK_STATUS_JOIN", + "MS_ASYNC_OP_STATUS_CANCELED", + "MS_ASYNC_OP_STATUS_ERROR", + "MS_ASYNC_OP_STATUS_SUCCESS", + "MS_MANIPULATION_STATE_ACTIVE", + "MS_MANIPULATION_STATE_CANCELLED", + "MS_MANIPULATION_STATE_COMMITTED", + "MS_MANIPULATION_STATE_DRAGGING", + "MS_MANIPULATION_STATE_INERTIA", + "MS_MANIPULATION_STATE_PRESELECT", + "MS_MANIPULATION_STATE_SELECTING", + "MS_MANIPULATION_STATE_STOPPED", + "MS_MEDIA_ERR_ENCRYPTED", + "MS_MEDIA_KEYERR_CLIENT", + "MS_MEDIA_KEYERR_DOMAIN", + "MS_MEDIA_KEYERR_HARDWARECHANGE", + "MS_MEDIA_KEYERR_OUTPUT", + "MS_MEDIA_KEYERR_SERVICE", + "MS_MEDIA_KEYERR_UNKNOWN", + "Map", + "Math", + "MathMLElement", + "MediaCapabilities", + "MediaCapabilitiesInfo", + "MediaController", + "MediaDeviceInfo", + "MediaDevices", + "MediaElementAudioSourceNode", + "MediaEncryptedEvent", + "MediaError", + "MediaKeyError", + "MediaKeyEvent", + "MediaKeyMessageEvent", + "MediaKeyNeededEvent", + "MediaKeySession", + "MediaKeyStatusMap", + "MediaKeySystemAccess", + "MediaKeys", + "MediaList", + "MediaMetadata", + "MediaQueryList", + "MediaQueryListEvent", + "MediaRecorder", + "MediaRecorderErrorEvent", + "MediaSession", + "MediaSettingsRange", + "MediaSource", + "MediaStream", + "MediaStreamAudioDestinationNode", + "MediaStreamAudioSourceNode", + "MediaStreamEvent", + "MediaStreamTrack", + "MediaStreamTrackAudioSourceNode", + "MediaStreamTrackEvent", + "Memory", + "MessageChannel", + "MessageEvent", + "MessagePort", + "Methods", + "MimeType", + "MimeTypeArray", + "Module", + "MouseEvent", + "MouseScrollEvent", + "MozAnimation", + "MozAnimationDelay", + "MozAnimationDirection", + "MozAnimationDuration", + "MozAnimationFillMode", + "MozAnimationIterationCount", + "MozAnimationName", + "MozAnimationPlayState", + "MozAnimationTimingFunction", + "MozAppearance", + "MozBackfaceVisibility", + "MozBinding", + "MozBorderBottomColors", + "MozBorderEnd", + "MozBorderEndColor", + "MozBorderEndStyle", + "MozBorderEndWidth", + "MozBorderImage", + "MozBorderLeftColors", + "MozBorderRightColors", + "MozBorderStart", + "MozBorderStartColor", + "MozBorderStartStyle", + "MozBorderStartWidth", + "MozBorderTopColors", + "MozBoxAlign", + "MozBoxDirection", + "MozBoxFlex", + "MozBoxOrdinalGroup", + "MozBoxOrient", + "MozBoxPack", + "MozBoxSizing", + "MozCSSKeyframeRule", + "MozCSSKeyframesRule", + "MozColumnCount", + "MozColumnFill", + "MozColumnGap", + "MozColumnRule", + "MozColumnRuleColor", + "MozColumnRuleStyle", + "MozColumnRuleWidth", + "MozColumnWidth", + "MozColumns", + "MozContactChangeEvent", + "MozFloatEdge", + "MozFontFeatureSettings", + "MozFontLanguageOverride", + "MozForceBrokenImageIcon", + "MozHyphens", + "MozImageRegion", + "MozMarginEnd", + "MozMarginStart", + "MozMmsEvent", + "MozMmsMessage", + "MozMobileMessageThread", + "MozOSXFontSmoothing", + "MozOrient", + "MozOsxFontSmoothing", + "MozOutlineRadius", + "MozOutlineRadiusBottomleft", + "MozOutlineRadiusBottomright", + "MozOutlineRadiusTopleft", + "MozOutlineRadiusTopright", + "MozPaddingEnd", + "MozPaddingStart", + "MozPerspective", + "MozPerspectiveOrigin", + "MozPowerManager", + "MozSettingsEvent", + "MozSmsEvent", + "MozSmsMessage", + "MozStackSizing", + "MozTabSize", + "MozTextAlignLast", + "MozTextDecorationColor", + "MozTextDecorationLine", + "MozTextDecorationStyle", + "MozTextSizeAdjust", + "MozTransform", + "MozTransformOrigin", + "MozTransformStyle", + "MozTransition", + "MozTransitionDelay", + "MozTransitionDuration", + "MozTransitionProperty", + "MozTransitionTimingFunction", + "MozUserFocus", + "MozUserInput", + "MozUserModify", + "MozUserSelect", + "MozWindowDragging", + "MozWindowShadow", + "MutationEvent", + "MutationObserver", + "MutationRecord", + "NAMESPACE_ERR", + "NAMESPACE_RULE", + "NEAREST", + "NEAREST_MIPMAP_LINEAR", + "NEAREST_MIPMAP_NEAREST", + "NEGATIVE_INFINITY", + "NETWORK_EMPTY", + "NETWORK_ERR", + "NETWORK_IDLE", + "NETWORK_LOADED", + "NETWORK_LOADING", + "NETWORK_NO_SOURCE", + "NEVER", + "NEW", + "NEXT", + "NEXT_NO_DUPLICATE", + "NICEST", + "NODE_AFTER", + "NODE_BEFORE", + "NODE_BEFORE_AND_AFTER", + "NODE_INSIDE", + "NONE", + "NON_TRANSIENT_ERR", + "NOTATION_NODE", + "NOTCH", + "NOTEQUAL", + "NOT_ALLOWED_ERR", + "NOT_FOUND_ERR", + "NOT_READABLE_ERR", + "NOT_SUPPORTED_ERR", + "NO_DATA_ALLOWED_ERR", + "NO_ERR", + "NO_ERROR", + "NO_MODIFICATION_ALLOWED_ERR", + "NUMBER_TYPE", + "NUM_COMPRESSED_TEXTURE_FORMATS", + "NaN", + "NamedNodeMap", + "NavigationPreloadManager", + "Navigator", + "NearbyLinks", + "NetworkInformation", + "Node", + "NodeFilter", + "NodeIterator", + "NodeList", + "Notation", + "Notification", + "NotifyPaintEvent", + "Number", + "NumberFormat", + "OBJECT_TYPE", + "OBSOLETE", + "OK", + "ONE", + "ONE_MINUS_CONSTANT_ALPHA", + "ONE_MINUS_CONSTANT_COLOR", + "ONE_MINUS_DST_ALPHA", + "ONE_MINUS_DST_COLOR", + "ONE_MINUS_SRC_ALPHA", + "ONE_MINUS_SRC_COLOR", + "OPEN", + "OPENED", + "OPENING", + "ORDERED_NODE_ITERATOR_TYPE", + "ORDERED_NODE_SNAPSHOT_TYPE", + "OTHER_ERROR", + "OUT_OF_MEMORY", + "Object", + "OfflineAudioCompletionEvent", + "OfflineAudioContext", + "OfflineResourceList", + "OffscreenCanvas", + "OffscreenCanvasRenderingContext2D", + "Option", + "OrientationSensor", + "OscillatorNode", + "OverconstrainedError", + "OverflowEvent", + "PACK_ALIGNMENT", + "PACK_ROW_LENGTH", + "PACK_SKIP_PIXELS", + "PACK_SKIP_ROWS", + "PAGE_RULE", + "PARSE_ERR", + "PATHSEG_ARC_ABS", + "PATHSEG_ARC_REL", + "PATHSEG_CLOSEPATH", + "PATHSEG_CURVETO_CUBIC_ABS", + "PATHSEG_CURVETO_CUBIC_REL", + "PATHSEG_CURVETO_CUBIC_SMOOTH_ABS", + "PATHSEG_CURVETO_CUBIC_SMOOTH_REL", + "PATHSEG_CURVETO_QUADRATIC_ABS", + "PATHSEG_CURVETO_QUADRATIC_REL", + "PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS", + "PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL", + "PATHSEG_LINETO_ABS", + "PATHSEG_LINETO_HORIZONTAL_ABS", + "PATHSEG_LINETO_HORIZONTAL_REL", + "PATHSEG_LINETO_REL", + "PATHSEG_LINETO_VERTICAL_ABS", + "PATHSEG_LINETO_VERTICAL_REL", + "PATHSEG_MOVETO_ABS", + "PATHSEG_MOVETO_REL", + "PATHSEG_UNKNOWN", + "PATH_EXISTS_ERR", + "PEAKING", + "PERMISSION_DENIED", + "PERSISTENT", + "PI", + "PIXEL_PACK_BUFFER", + "PIXEL_PACK_BUFFER_BINDING", + "PIXEL_UNPACK_BUFFER", + "PIXEL_UNPACK_BUFFER_BINDING", + "PLAYING_STATE", + "POINTS", + "POLYGON_OFFSET_FACTOR", + "POLYGON_OFFSET_FILL", + "POLYGON_OFFSET_UNITS", + "POSITION_UNAVAILABLE", + "POSITIVE_INFINITY", + "PREV", + "PREV_NO_DUPLICATE", + "PROCESSING_INSTRUCTION_NODE", + "PageChangeEvent", + "PageTransitionEvent", + "PaintRequest", + "PaintRequestList", + "PannerNode", + "PasswordCredential", + "Path2D", + "PaymentAddress", + "PaymentInstruments", + "PaymentManager", + "PaymentMethodChangeEvent", + "PaymentRequest", + "PaymentRequestUpdateEvent", + "PaymentResponse", + "Performance", + "PerformanceElementTiming", + "PerformanceEntry", + "PerformanceEventTiming", + "PerformanceLongTaskTiming", + "PerformanceMark", + "PerformanceMeasure", + "PerformanceNavigation", + "PerformanceNavigationTiming", + "PerformanceObserver", + "PerformanceObserverEntryList", + "PerformancePaintTiming", + "PerformanceResourceTiming", + "PerformanceServerTiming", + "PerformanceTiming", + "PeriodicSyncManager", + "PeriodicWave", + "PermissionStatus", + "Permissions", + "PhotoCapabilities", + "PictureInPictureWindow", + "Plugin", + "PluginArray", + "PluralRules", + "PointerEvent", + "PopStateEvent", + "PopupBlockedEvent", + "Presentation", + "PresentationAvailability", + "PresentationConnection", + "PresentationConnectionAvailableEvent", + "PresentationConnectionCloseEvent", + "PresentationConnectionList", + "PresentationReceiver", + "PresentationRequest", + "ProcessingInstruction", + "ProgressEvent", + "Promise", + "PromiseRejectionEvent", + "PropertyNodeList", + "Proxy", + "PublicKeyCredential", + "PushManager", + "PushSubscription", + "PushSubscriptionOptions", + "Q", + "QUERY_RESULT", + "QUERY_RESULT_AVAILABLE", + "QUOTA_ERR", + "QUOTA_EXCEEDED_ERR", + "QueryInterface", + "R11F_G11F_B10F", + "R16F", + "R16I", + "R16UI", + "R32F", + "R32I", + "R32UI", + "R8", + "R8I", + "R8UI", + "R8_SNORM", + "RASTERIZER_DISCARD", + "READ_BUFFER", + "READ_FRAMEBUFFER", + "READ_FRAMEBUFFER_BINDING", + "READ_ONLY", + "READ_ONLY_ERR", + "READ_WRITE", + "RED", + "RED_BITS", + "RED_INTEGER", + "REMOVAL", + "RENDERBUFFER", + "RENDERBUFFER_ALPHA_SIZE", + "RENDERBUFFER_BINDING", + "RENDERBUFFER_BLUE_SIZE", + "RENDERBUFFER_DEPTH_SIZE", + "RENDERBUFFER_GREEN_SIZE", + "RENDERBUFFER_HEIGHT", + "RENDERBUFFER_INTERNAL_FORMAT", + "RENDERBUFFER_RED_SIZE", + "RENDERBUFFER_SAMPLES", + "RENDERBUFFER_STENCIL_SIZE", + "RENDERBUFFER_WIDTH", + "RENDERER", + "RENDERING_INTENT_ABSOLUTE_COLORIMETRIC", + "RENDERING_INTENT_AUTO", + "RENDERING_INTENT_PERCEPTUAL", + "RENDERING_INTENT_RELATIVE_COLORIMETRIC", + "RENDERING_INTENT_SATURATION", + "RENDERING_INTENT_UNKNOWN", + "REPEAT", + "REPLACE", + "RG", + "RG16F", + "RG16I", + "RG16UI", + "RG32F", + "RG32I", + "RG32UI", + "RG8", + "RG8I", + "RG8UI", + "RG8_SNORM", + "RGB", + "RGB10_A2", + "RGB10_A2UI", + "RGB16F", + "RGB16I", + "RGB16UI", + "RGB32F", + "RGB32I", + "RGB32UI", + "RGB565", + "RGB5_A1", + "RGB8", + "RGB8I", + "RGB8UI", + "RGB8_SNORM", + "RGB9_E5", + "RGBA", + "RGBA16F", + "RGBA16I", + "RGBA16UI", + "RGBA32F", + "RGBA32I", + "RGBA32UI", + "RGBA4", + "RGBA8", + "RGBA8I", + "RGBA8UI", + "RGBA8_SNORM", + "RGBA_INTEGER", + "RGBColor", + "RGB_INTEGER", + "RG_INTEGER", + "ROTATION_CLOCKWISE", + "ROTATION_COUNTERCLOCKWISE", + "RTCCertificate", + "RTCDTMFSender", + "RTCDTMFToneChangeEvent", + "RTCDataChannel", + "RTCDataChannelEvent", + "RTCDtlsTransport", + "RTCError", + "RTCErrorEvent", + "RTCIceCandidate", + "RTCIceTransport", + "RTCPeerConnection", + "RTCPeerConnectionIceErrorEvent", + "RTCPeerConnectionIceEvent", + "RTCRtpReceiver", + "RTCRtpSender", + "RTCRtpTransceiver", + "RTCSctpTransport", + "RTCSessionDescription", + "RTCStatsReport", + "RTCTrackEvent", + "RadioNodeList", + "Range", + "RangeError", + "RangeException", + "ReadableStream", + "ReadableStreamDefaultReader", + "RecordErrorEvent", + "Rect", + "ReferenceError", + "Reflect", + "RegExp", + "RelativeOrientationSensor", + "RelativeTimeFormat", + "RemotePlayback", + "Report", + "ReportBody", + "ReportingObserver", + "Request", + "ResizeObserver", + "ResizeObserverEntry", + "ResizeObserverSize", + "Response", + "RuntimeError", + "SAMPLER_2D", + "SAMPLER_2D_ARRAY", + "SAMPLER_2D_ARRAY_SHADOW", + "SAMPLER_2D_SHADOW", + "SAMPLER_3D", + "SAMPLER_BINDING", + "SAMPLER_CUBE", + "SAMPLER_CUBE_SHADOW", + "SAMPLES", + "SAMPLE_ALPHA_TO_COVERAGE", + "SAMPLE_BUFFERS", + "SAMPLE_COVERAGE", + "SAMPLE_COVERAGE_INVERT", + "SAMPLE_COVERAGE_VALUE", + "SAWTOOTH", + "SCHEDULED_STATE", + "SCISSOR_BOX", + "SCISSOR_TEST", + "SCROLL_PAGE_DOWN", + "SCROLL_PAGE_UP", + "SDP_ANSWER", + "SDP_OFFER", + "SDP_PRANSWER", + "SECURITY_ERR", + "SELECT", + "SEPARATE_ATTRIBS", + "SERIALIZE_ERR", + "SEVERITY_ERROR", + "SEVERITY_FATAL_ERROR", + "SEVERITY_WARNING", + "SHADER_COMPILER", + "SHADER_TYPE", + "SHADING_LANGUAGE_VERSION", + "SHIFT_MASK", + "SHORT", + "SHOWING", + "SHOW_ALL", + "SHOW_ATTRIBUTE", + "SHOW_CDATA_SECTION", + "SHOW_COMMENT", + "SHOW_DOCUMENT", + "SHOW_DOCUMENT_FRAGMENT", + "SHOW_DOCUMENT_TYPE", + "SHOW_ELEMENT", + "SHOW_ENTITY", + "SHOW_ENTITY_REFERENCE", + "SHOW_NOTATION", + "SHOW_PROCESSING_INSTRUCTION", + "SHOW_TEXT", + "SIGNALED", + "SIGNED_NORMALIZED", + "SINE", + "SOUNDFIELD", + "SQLException", + "SQRT1_2", + "SQRT2", + "SQUARE", + "SRC_ALPHA", + "SRC_ALPHA_SATURATE", + "SRC_COLOR", + "SRGB", + "SRGB8", + "SRGB8_ALPHA8", + "START_TO_END", + "START_TO_START", + "STATIC_COPY", + "STATIC_DRAW", + "STATIC_READ", + "STENCIL", + "STENCIL_ATTACHMENT", + "STENCIL_BACK_FAIL", + "STENCIL_BACK_FUNC", + "STENCIL_BACK_PASS_DEPTH_FAIL", + "STENCIL_BACK_PASS_DEPTH_PASS", + "STENCIL_BACK_REF", + "STENCIL_BACK_VALUE_MASK", + "STENCIL_BACK_WRITEMASK", + "STENCIL_BITS", + "STENCIL_BUFFER_BIT", + "STENCIL_CLEAR_VALUE", + "STENCIL_FAIL", + "STENCIL_FUNC", + "STENCIL_INDEX", + "STENCIL_INDEX8", + "STENCIL_PASS_DEPTH_FAIL", + "STENCIL_PASS_DEPTH_PASS", + "STENCIL_REF", + "STENCIL_TEST", + "STENCIL_VALUE_MASK", + "STENCIL_WRITEMASK", + "STREAM_COPY", + "STREAM_DRAW", + "STREAM_READ", + "STRING_TYPE", + "STYLE_RULE", + "SUBPIXEL_BITS", + "SUPPORTS_RULE", + "SVGAElement", + "SVGAltGlyphDefElement", + "SVGAltGlyphElement", + "SVGAltGlyphItemElement", + "SVGAngle", + "SVGAnimateColorElement", + "SVGAnimateElement", + "SVGAnimateMotionElement", + "SVGAnimateTransformElement", + "SVGAnimatedAngle", + "SVGAnimatedBoolean", + "SVGAnimatedEnumeration", + "SVGAnimatedInteger", + "SVGAnimatedLength", + "SVGAnimatedLengthList", + "SVGAnimatedNumber", + "SVGAnimatedNumberList", + "SVGAnimatedPreserveAspectRatio", + "SVGAnimatedRect", + "SVGAnimatedString", + "SVGAnimatedTransformList", + "SVGAnimationElement", + "SVGCircleElement", + "SVGClipPathElement", + "SVGColor", + "SVGComponentTransferFunctionElement", + "SVGCursorElement", + "SVGDefsElement", + "SVGDescElement", + "SVGDiscardElement", + "SVGDocument", + "SVGElement", + "SVGElementInstance", + "SVGElementInstanceList", + "SVGEllipseElement", + "SVGException", + "SVGFEBlendElement", + "SVGFEColorMatrixElement", + "SVGFEComponentTransferElement", + "SVGFECompositeElement", + "SVGFEConvolveMatrixElement", + "SVGFEDiffuseLightingElement", + "SVGFEDisplacementMapElement", + "SVGFEDistantLightElement", + "SVGFEDropShadowElement", + "SVGFEFloodElement", + "SVGFEFuncAElement", + "SVGFEFuncBElement", + "SVGFEFuncGElement", + "SVGFEFuncRElement", + "SVGFEGaussianBlurElement", + "SVGFEImageElement", + "SVGFEMergeElement", + "SVGFEMergeNodeElement", + "SVGFEMorphologyElement", + "SVGFEOffsetElement", + "SVGFEPointLightElement", + "SVGFESpecularLightingElement", + "SVGFESpotLightElement", + "SVGFETileElement", + "SVGFETurbulenceElement", + "SVGFilterElement", + "SVGFontElement", + "SVGFontFaceElement", + "SVGFontFaceFormatElement", + "SVGFontFaceNameElement", + "SVGFontFaceSrcElement", + "SVGFontFaceUriElement", + "SVGForeignObjectElement", + "SVGGElement", + "SVGGeometryElement", + "SVGGlyphElement", + "SVGGlyphRefElement", + "SVGGradientElement", + "SVGGraphicsElement", + "SVGHKernElement", + "SVGImageElement", + "SVGLength", + "SVGLengthList", + "SVGLineElement", + "SVGLinearGradientElement", + "SVGMPathElement", + "SVGMarkerElement", + "SVGMaskElement", + "SVGMatrix", + "SVGMetadataElement", + "SVGMissingGlyphElement", + "SVGNumber", + "SVGNumberList", + "SVGPaint", + "SVGPathElement", + "SVGPathSeg", + "SVGPathSegArcAbs", + "SVGPathSegArcRel", + "SVGPathSegClosePath", + "SVGPathSegCurvetoCubicAbs", + "SVGPathSegCurvetoCubicRel", + "SVGPathSegCurvetoCubicSmoothAbs", + "SVGPathSegCurvetoCubicSmoothRel", + "SVGPathSegCurvetoQuadraticAbs", + "SVGPathSegCurvetoQuadraticRel", + "SVGPathSegCurvetoQuadraticSmoothAbs", + "SVGPathSegCurvetoQuadraticSmoothRel", + "SVGPathSegLinetoAbs", + "SVGPathSegLinetoHorizontalAbs", + "SVGPathSegLinetoHorizontalRel", + "SVGPathSegLinetoRel", + "SVGPathSegLinetoVerticalAbs", + "SVGPathSegLinetoVerticalRel", + "SVGPathSegList", + "SVGPathSegMovetoAbs", + "SVGPathSegMovetoRel", + "SVGPatternElement", + "SVGPoint", + "SVGPointList", + "SVGPolygonElement", + "SVGPolylineElement", + "SVGPreserveAspectRatio", + "SVGRadialGradientElement", + "SVGRect", + "SVGRectElement", + "SVGRenderingIntent", + "SVGSVGElement", + "SVGScriptElement", + "SVGSetElement", + "SVGStopElement", + "SVGStringList", + "SVGStyleElement", + "SVGSwitchElement", + "SVGSymbolElement", + "SVGTRefElement", + "SVGTSpanElement", + "SVGTextContentElement", + "SVGTextElement", + "SVGTextPathElement", + "SVGTextPositioningElement", + "SVGTitleElement", + "SVGTransform", + "SVGTransformList", + "SVGUnitTypes", + "SVGUseElement", + "SVGVKernElement", + "SVGViewElement", + "SVGViewSpec", + "SVGZoomAndPan", + "SVGZoomEvent", + "SVG_ANGLETYPE_DEG", + "SVG_ANGLETYPE_GRAD", + "SVG_ANGLETYPE_RAD", + "SVG_ANGLETYPE_UNKNOWN", + "SVG_ANGLETYPE_UNSPECIFIED", + "SVG_CHANNEL_A", + "SVG_CHANNEL_B", + "SVG_CHANNEL_G", + "SVG_CHANNEL_R", + "SVG_CHANNEL_UNKNOWN", + "SVG_COLORTYPE_CURRENTCOLOR", + "SVG_COLORTYPE_RGBCOLOR", + "SVG_COLORTYPE_RGBCOLOR_ICCCOLOR", + "SVG_COLORTYPE_UNKNOWN", + "SVG_EDGEMODE_DUPLICATE", + "SVG_EDGEMODE_NONE", + "SVG_EDGEMODE_UNKNOWN", + "SVG_EDGEMODE_WRAP", + "SVG_FEBLEND_MODE_COLOR", + "SVG_FEBLEND_MODE_COLOR_BURN", + "SVG_FEBLEND_MODE_COLOR_DODGE", + "SVG_FEBLEND_MODE_DARKEN", + "SVG_FEBLEND_MODE_DIFFERENCE", + "SVG_FEBLEND_MODE_EXCLUSION", + "SVG_FEBLEND_MODE_HARD_LIGHT", + "SVG_FEBLEND_MODE_HUE", + "SVG_FEBLEND_MODE_LIGHTEN", + "SVG_FEBLEND_MODE_LUMINOSITY", + "SVG_FEBLEND_MODE_MULTIPLY", + "SVG_FEBLEND_MODE_NORMAL", + "SVG_FEBLEND_MODE_OVERLAY", + "SVG_FEBLEND_MODE_SATURATION", + "SVG_FEBLEND_MODE_SCREEN", + "SVG_FEBLEND_MODE_SOFT_LIGHT", + "SVG_FEBLEND_MODE_UNKNOWN", + "SVG_FECOLORMATRIX_TYPE_HUEROTATE", + "SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA", + "SVG_FECOLORMATRIX_TYPE_MATRIX", + "SVG_FECOLORMATRIX_TYPE_SATURATE", + "SVG_FECOLORMATRIX_TYPE_UNKNOWN", + "SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE", + "SVG_FECOMPONENTTRANSFER_TYPE_GAMMA", + "SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY", + "SVG_FECOMPONENTTRANSFER_TYPE_LINEAR", + "SVG_FECOMPONENTTRANSFER_TYPE_TABLE", + "SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN", + "SVG_FECOMPOSITE_OPERATOR_ARITHMETIC", + "SVG_FECOMPOSITE_OPERATOR_ATOP", + "SVG_FECOMPOSITE_OPERATOR_IN", + "SVG_FECOMPOSITE_OPERATOR_OUT", + "SVG_FECOMPOSITE_OPERATOR_OVER", + "SVG_FECOMPOSITE_OPERATOR_UNKNOWN", + "SVG_FECOMPOSITE_OPERATOR_XOR", + "SVG_INVALID_VALUE_ERR", + "SVG_LENGTHTYPE_CM", + "SVG_LENGTHTYPE_EMS", + "SVG_LENGTHTYPE_EXS", + "SVG_LENGTHTYPE_IN", + "SVG_LENGTHTYPE_MM", + "SVG_LENGTHTYPE_NUMBER", + "SVG_LENGTHTYPE_PC", + "SVG_LENGTHTYPE_PERCENTAGE", + "SVG_LENGTHTYPE_PT", + "SVG_LENGTHTYPE_PX", + "SVG_LENGTHTYPE_UNKNOWN", + "SVG_MARKERUNITS_STROKEWIDTH", + "SVG_MARKERUNITS_UNKNOWN", + "SVG_MARKERUNITS_USERSPACEONUSE", + "SVG_MARKER_ORIENT_ANGLE", + "SVG_MARKER_ORIENT_AUTO", + "SVG_MARKER_ORIENT_UNKNOWN", + "SVG_MASKTYPE_ALPHA", + "SVG_MASKTYPE_LUMINANCE", + "SVG_MATRIX_NOT_INVERTABLE", + "SVG_MEETORSLICE_MEET", + "SVG_MEETORSLICE_SLICE", + "SVG_MEETORSLICE_UNKNOWN", + "SVG_MORPHOLOGY_OPERATOR_DILATE", + "SVG_MORPHOLOGY_OPERATOR_ERODE", + "SVG_MORPHOLOGY_OPERATOR_UNKNOWN", + "SVG_PAINTTYPE_CURRENTCOLOR", + "SVG_PAINTTYPE_NONE", + "SVG_PAINTTYPE_RGBCOLOR", + "SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR", + "SVG_PAINTTYPE_UNKNOWN", + "SVG_PAINTTYPE_URI", + "SVG_PAINTTYPE_URI_CURRENTCOLOR", + "SVG_PAINTTYPE_URI_NONE", + "SVG_PAINTTYPE_URI_RGBCOLOR", + "SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR", + "SVG_PRESERVEASPECTRATIO_NONE", + "SVG_PRESERVEASPECTRATIO_UNKNOWN", + "SVG_PRESERVEASPECTRATIO_XMAXYMAX", + "SVG_PRESERVEASPECTRATIO_XMAXYMID", + "SVG_PRESERVEASPECTRATIO_XMAXYMIN", + "SVG_PRESERVEASPECTRATIO_XMIDYMAX", + "SVG_PRESERVEASPECTRATIO_XMIDYMID", + "SVG_PRESERVEASPECTRATIO_XMIDYMIN", + "SVG_PRESERVEASPECTRATIO_XMINYMAX", + "SVG_PRESERVEASPECTRATIO_XMINYMID", + "SVG_PRESERVEASPECTRATIO_XMINYMIN", + "SVG_SPREADMETHOD_PAD", + "SVG_SPREADMETHOD_REFLECT", + "SVG_SPREADMETHOD_REPEAT", + "SVG_SPREADMETHOD_UNKNOWN", + "SVG_STITCHTYPE_NOSTITCH", + "SVG_STITCHTYPE_STITCH", + "SVG_STITCHTYPE_UNKNOWN", + "SVG_TRANSFORM_MATRIX", + "SVG_TRANSFORM_ROTATE", + "SVG_TRANSFORM_SCALE", + "SVG_TRANSFORM_SKEWX", + "SVG_TRANSFORM_SKEWY", + "SVG_TRANSFORM_TRANSLATE", + "SVG_TRANSFORM_UNKNOWN", + "SVG_TURBULENCE_TYPE_FRACTALNOISE", + "SVG_TURBULENCE_TYPE_TURBULENCE", + "SVG_TURBULENCE_TYPE_UNKNOWN", + "SVG_UNIT_TYPE_OBJECTBOUNDINGBOX", + "SVG_UNIT_TYPE_UNKNOWN", + "SVG_UNIT_TYPE_USERSPACEONUSE", + "SVG_WRONG_TYPE_ERR", + "SVG_ZOOMANDPAN_DISABLE", + "SVG_ZOOMANDPAN_MAGNIFY", + "SVG_ZOOMANDPAN_UNKNOWN", + "SYNC_CONDITION", + "SYNC_FENCE", + "SYNC_FLAGS", + "SYNC_FLUSH_COMMANDS_BIT", + "SYNC_GPU_COMMANDS_COMPLETE", + "SYNC_STATUS", + "SYNTAX_ERR", + "SavedPages", + "Screen", + "ScreenOrientation", + "Script", + "ScriptProcessorNode", + "ScrollAreaEvent", + "SecurityPolicyViolationEvent", + "Selection", + "Sensor", + "SensorErrorEvent", + "ServiceWorker", + "ServiceWorkerContainer", + "ServiceWorkerRegistration", + "SessionDescription", + "Set", + "ShadowRoot", + "SharedArrayBuffer", + "SharedWorker", + "SimpleGestureEvent", + "SourceBuffer", + "SourceBufferList", + "SpeechSynthesis", + "SpeechSynthesisErrorEvent", + "SpeechSynthesisEvent", + "SpeechSynthesisUtterance", + "SpeechSynthesisVoice", + "StaticRange", + "StereoPannerNode", + "StopIteration", + "Storage", + "StorageEvent", + "StorageManager", + "String", + "StructType", + "StylePropertyMap", + "StylePropertyMapReadOnly", + "StyleSheet", + "StyleSheetList", + "SubmitEvent", + "SubtleCrypto", + "Symbol", + "SyncManager", + "SyntaxError", + "TEMPORARY", + "TEXTPATH_METHODTYPE_ALIGN", + "TEXTPATH_METHODTYPE_STRETCH", + "TEXTPATH_METHODTYPE_UNKNOWN", + "TEXTPATH_SPACINGTYPE_AUTO", + "TEXTPATH_SPACINGTYPE_EXACT", + "TEXTPATH_SPACINGTYPE_UNKNOWN", + "TEXTURE", + "TEXTURE0", + "TEXTURE1", + "TEXTURE10", + "TEXTURE11", + "TEXTURE12", + "TEXTURE13", + "TEXTURE14", + "TEXTURE15", + "TEXTURE16", + "TEXTURE17", + "TEXTURE18", + "TEXTURE19", + "TEXTURE2", + "TEXTURE20", + "TEXTURE21", + "TEXTURE22", + "TEXTURE23", + "TEXTURE24", + "TEXTURE25", + "TEXTURE26", + "TEXTURE27", + "TEXTURE28", + "TEXTURE29", + "TEXTURE3", + "TEXTURE30", + "TEXTURE31", + "TEXTURE4", + "TEXTURE5", + "TEXTURE6", + "TEXTURE7", + "TEXTURE8", + "TEXTURE9", + "TEXTURE_2D", + "TEXTURE_2D_ARRAY", + "TEXTURE_3D", + "TEXTURE_BASE_LEVEL", + "TEXTURE_BINDING_2D", + "TEXTURE_BINDING_2D_ARRAY", + "TEXTURE_BINDING_3D", + "TEXTURE_BINDING_CUBE_MAP", + "TEXTURE_COMPARE_FUNC", + "TEXTURE_COMPARE_MODE", + "TEXTURE_CUBE_MAP", + "TEXTURE_CUBE_MAP_NEGATIVE_X", + "TEXTURE_CUBE_MAP_NEGATIVE_Y", + "TEXTURE_CUBE_MAP_NEGATIVE_Z", + "TEXTURE_CUBE_MAP_POSITIVE_X", + "TEXTURE_CUBE_MAP_POSITIVE_Y", + "TEXTURE_CUBE_MAP_POSITIVE_Z", + "TEXTURE_IMMUTABLE_FORMAT", + "TEXTURE_IMMUTABLE_LEVELS", + "TEXTURE_MAG_FILTER", + "TEXTURE_MAX_ANISOTROPY_EXT", + "TEXTURE_MAX_LEVEL", + "TEXTURE_MAX_LOD", + "TEXTURE_MIN_FILTER", + "TEXTURE_MIN_LOD", + "TEXTURE_WRAP_R", + "TEXTURE_WRAP_S", + "TEXTURE_WRAP_T", + "TEXT_NODE", + "TIMEOUT", + "TIMEOUT_ERR", + "TIMEOUT_EXPIRED", + "TIMEOUT_IGNORED", + "TOO_LARGE_ERR", + "TRANSACTION_INACTIVE_ERR", + "TRANSFORM_FEEDBACK", + "TRANSFORM_FEEDBACK_ACTIVE", + "TRANSFORM_FEEDBACK_BINDING", + "TRANSFORM_FEEDBACK_BUFFER", + "TRANSFORM_FEEDBACK_BUFFER_BINDING", + "TRANSFORM_FEEDBACK_BUFFER_MODE", + "TRANSFORM_FEEDBACK_BUFFER_SIZE", + "TRANSFORM_FEEDBACK_BUFFER_START", + "TRANSFORM_FEEDBACK_PAUSED", + "TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN", + "TRANSFORM_FEEDBACK_VARYINGS", + "TRIANGLE", + "TRIANGLES", + "TRIANGLE_FAN", + "TRIANGLE_STRIP", + "TYPE_BACK_FORWARD", + "TYPE_ERR", + "TYPE_MISMATCH_ERR", + "TYPE_NAVIGATE", + "TYPE_RELOAD", + "TYPE_RESERVED", + "Table", + "TaskAttributionTiming", + "Text", + "TextDecoder", + "TextDecoderStream", + "TextEncoder", + "TextEncoderStream", + "TextEvent", + "TextMetrics", + "TextTrack", + "TextTrackCue", + "TextTrackCueList", + "TextTrackList", + "TimeEvent", + "TimeRanges", + "Touch", + "TouchEvent", + "TouchList", + "TrackEvent", + "TransformStream", + "TransitionEvent", + "TreeWalker", + "TrustedHTML", + "TrustedScript", + "TrustedScriptURL", + "TrustedTypePolicy", + "TrustedTypePolicyFactory", + "TypeError", + "TypedObject", + "U2F", + "UIEvent", + "UNCACHED", + "UNIFORM_ARRAY_STRIDE", + "UNIFORM_BLOCK_ACTIVE_UNIFORMS", + "UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES", + "UNIFORM_BLOCK_BINDING", + "UNIFORM_BLOCK_DATA_SIZE", + "UNIFORM_BLOCK_INDEX", + "UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER", + "UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER", + "UNIFORM_BUFFER", + "UNIFORM_BUFFER_BINDING", + "UNIFORM_BUFFER_OFFSET_ALIGNMENT", + "UNIFORM_BUFFER_SIZE", + "UNIFORM_BUFFER_START", + "UNIFORM_IS_ROW_MAJOR", + "UNIFORM_MATRIX_STRIDE", + "UNIFORM_OFFSET", + "UNIFORM_SIZE", + "UNIFORM_TYPE", + "UNKNOWN_ERR", + "UNKNOWN_RULE", + "UNMASKED_RENDERER_WEBGL", + "UNMASKED_VENDOR_WEBGL", + "UNORDERED_NODE_ITERATOR_TYPE", + "UNORDERED_NODE_SNAPSHOT_TYPE", + "UNPACK_ALIGNMENT", + "UNPACK_COLORSPACE_CONVERSION_WEBGL", + "UNPACK_FLIP_Y_WEBGL", + "UNPACK_IMAGE_HEIGHT", + "UNPACK_PREMULTIPLY_ALPHA_WEBGL", + "UNPACK_ROW_LENGTH", + "UNPACK_SKIP_IMAGES", + "UNPACK_SKIP_PIXELS", + "UNPACK_SKIP_ROWS", + "UNSCHEDULED_STATE", + "UNSENT", + "UNSIGNALED", + "UNSIGNED_BYTE", + "UNSIGNED_INT", + "UNSIGNED_INT_10F_11F_11F_REV", + "UNSIGNED_INT_24_8", + "UNSIGNED_INT_2_10_10_10_REV", + "UNSIGNED_INT_5_9_9_9_REV", + "UNSIGNED_INT_SAMPLER_2D", + "UNSIGNED_INT_SAMPLER_2D_ARRAY", + "UNSIGNED_INT_SAMPLER_3D", + "UNSIGNED_INT_SAMPLER_CUBE", + "UNSIGNED_INT_VEC2", + "UNSIGNED_INT_VEC3", + "UNSIGNED_INT_VEC4", + "UNSIGNED_NORMALIZED", + "UNSIGNED_SHORT", + "UNSIGNED_SHORT_4_4_4_4", + "UNSIGNED_SHORT_5_5_5_1", + "UNSIGNED_SHORT_5_6_5", + "UNSPECIFIED_EVENT_TYPE_ERR", + "UPDATEREADY", + "URIError", + "URL", + "URLSearchParams", + "URLUnencoded", + "URL_MISMATCH_ERR", + "USB", + "USBAlternateInterface", + "USBConfiguration", + "USBConnectionEvent", + "USBDevice", + "USBEndpoint", + "USBInTransferResult", + "USBInterface", + "USBIsochronousInTransferPacket", + "USBIsochronousInTransferResult", + "USBIsochronousOutTransferPacket", + "USBIsochronousOutTransferResult", + "USBOutTransferResult", + "UTC", + "Uint16Array", + "Uint32Array", + "Uint8Array", + "Uint8ClampedArray", + "UserActivation", + "UserMessageHandler", + "UserMessageHandlersNamespace", + "UserProximityEvent", + "VALIDATE_STATUS", + "VALIDATION_ERR", + "VARIABLES_RULE", + "VENDOR", + "VERSION", + "VERSION_CHANGE", + "VERSION_ERR", + "VERTEX_ARRAY_BINDING", + "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING", + "VERTEX_ATTRIB_ARRAY_DIVISOR", + "VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE", + "VERTEX_ATTRIB_ARRAY_ENABLED", + "VERTEX_ATTRIB_ARRAY_INTEGER", + "VERTEX_ATTRIB_ARRAY_NORMALIZED", + "VERTEX_ATTRIB_ARRAY_POINTER", + "VERTEX_ATTRIB_ARRAY_SIZE", + "VERTEX_ATTRIB_ARRAY_STRIDE", + "VERTEX_ATTRIB_ARRAY_TYPE", + "VERTEX_SHADER", + "VERTICAL", + "VERTICAL_AXIS", + "VER_ERR", + "VIEWPORT", + "VIEWPORT_RULE", + "VRDisplay", + "VRDisplayCapabilities", + "VRDisplayEvent", + "VREyeParameters", + "VRFieldOfView", + "VRFrameData", + "VRPose", + "VRStageParameters", + "VTTCue", + "VTTRegion", + "ValidityState", + "VideoPlaybackQuality", + "VideoStreamTrack", + "VisualViewport", + "WAIT_FAILED", + "WEBKIT_FILTER_RULE", + "WEBKIT_KEYFRAMES_RULE", + "WEBKIT_KEYFRAME_RULE", + "WEBKIT_REGION_RULE", + "WRONG_DOCUMENT_ERR", + "WakeLock", + "WakeLockSentinel", + "WasmAnyRef", + "WaveShaperNode", + "WeakMap", + "WeakRef", + "WeakSet", + "WebAssembly", + "WebGL2RenderingContext", + "WebGLActiveInfo", + "WebGLBuffer", + "WebGLContextEvent", + "WebGLFramebuffer", + "WebGLProgram", + "WebGLQuery", + "WebGLRenderbuffer", + "WebGLRenderingContext", + "WebGLSampler", + "WebGLShader", + "WebGLShaderPrecisionFormat", + "WebGLSync", + "WebGLTexture", + "WebGLTransformFeedback", + "WebGLUniformLocation", + "WebGLVertexArray", + "WebGLVertexArrayObject", + "WebKitAnimationEvent", + "WebKitBlobBuilder", + "WebKitCSSFilterRule", + "WebKitCSSFilterValue", + "WebKitCSSKeyframeRule", + "WebKitCSSKeyframesRule", + "WebKitCSSMatrix", + "WebKitCSSRegionRule", + "WebKitCSSTransformValue", + "WebKitDataCue", + "WebKitGamepad", + "WebKitMediaKeyError", + "WebKitMediaKeyMessageEvent", + "WebKitMediaKeySession", + "WebKitMediaKeys", + "WebKitMediaSource", + "WebKitMutationObserver", + "WebKitNamespace", + "WebKitPlaybackTargetAvailabilityEvent", + "WebKitPoint", + "WebKitShadowRoot", + "WebKitSourceBuffer", + "WebKitSourceBufferList", + "WebKitTransitionEvent", + "WebSocket", + "WebkitAlignContent", + "WebkitAlignItems", + "WebkitAlignSelf", + "WebkitAnimation", + "WebkitAnimationDelay", + "WebkitAnimationDirection", + "WebkitAnimationDuration", + "WebkitAnimationFillMode", + "WebkitAnimationIterationCount", + "WebkitAnimationName", + "WebkitAnimationPlayState", + "WebkitAnimationTimingFunction", + "WebkitAppearance", + "WebkitBackfaceVisibility", + "WebkitBackgroundClip", + "WebkitBackgroundOrigin", + "WebkitBackgroundSize", + "WebkitBorderBottomLeftRadius", + "WebkitBorderBottomRightRadius", + "WebkitBorderImage", + "WebkitBorderRadius", + "WebkitBorderTopLeftRadius", + "WebkitBorderTopRightRadius", + "WebkitBoxAlign", + "WebkitBoxDirection", + "WebkitBoxFlex", + "WebkitBoxOrdinalGroup", + "WebkitBoxOrient", + "WebkitBoxPack", + "WebkitBoxShadow", + "WebkitBoxSizing", + "WebkitFilter", + "WebkitFlex", + "WebkitFlexBasis", + "WebkitFlexDirection", + "WebkitFlexFlow", + "WebkitFlexGrow", + "WebkitFlexShrink", + "WebkitFlexWrap", + "WebkitJustifyContent", + "WebkitLineClamp", + "WebkitMask", + "WebkitMaskClip", + "WebkitMaskComposite", + "WebkitMaskImage", + "WebkitMaskOrigin", + "WebkitMaskPosition", + "WebkitMaskPositionX", + "WebkitMaskPositionY", + "WebkitMaskRepeat", + "WebkitMaskSize", + "WebkitOrder", + "WebkitPerspective", + "WebkitPerspectiveOrigin", + "WebkitTextFillColor", + "WebkitTextSizeAdjust", + "WebkitTextStroke", + "WebkitTextStrokeColor", + "WebkitTextStrokeWidth", + "WebkitTransform", + "WebkitTransformOrigin", + "WebkitTransformStyle", + "WebkitTransition", + "WebkitTransitionDelay", + "WebkitTransitionDuration", + "WebkitTransitionProperty", + "WebkitTransitionTimingFunction", + "WebkitUserSelect", + "WheelEvent", + "Window", + "Worker", + "Worklet", + "WritableStream", + "WritableStreamDefaultWriter", + "XMLDocument", + "XMLHttpRequest", + "XMLHttpRequestEventTarget", + "XMLHttpRequestException", + "XMLHttpRequestProgressEvent", + "XMLHttpRequestUpload", + "XMLSerializer", + "XMLStylesheetProcessingInstruction", + "XPathEvaluator", + "XPathException", + "XPathExpression", + "XPathNSResolver", + "XPathResult", + "XRBoundedReferenceSpace", + "XRDOMOverlayState", + "XRFrame", + "XRHitTestResult", + "XRHitTestSource", + "XRInputSource", + "XRInputSourceArray", + "XRInputSourceEvent", + "XRInputSourcesChangeEvent", + "XRLayer", + "XRPose", + "XRRay", + "XRReferenceSpace", + "XRReferenceSpaceEvent", + "XRRenderState", + "XRRigidTransform", + "XRSession", + "XRSessionEvent", + "XRSpace", + "XRSystem", + "XRTransientInputHitTestResult", + "XRTransientInputHitTestSource", + "XRView", + "XRViewerPose", + "XRViewport", + "XRWebGLLayer", + "XSLTProcessor", + "ZERO", + "_XD0M_", + "_YD0M_", + "__defineGetter__", + "__defineSetter__", + "__lookupGetter__", + "__lookupSetter__", + "__opera", + "__proto__", + "_browserjsran", + "a", + "aLink", + "abbr", + "abort", + "aborted", + "abs", + "absolute", + "acceleration", + "accelerationIncludingGravity", + "accelerator", + "accept", + "acceptCharset", + "acceptNode", + "accessKey", + "accessKeyLabel", + "accuracy", + "acos", + "acosh", + "action", + "actionURL", + "actions", + "activated", + "active", + "activeCues", + "activeElement", + "activeSourceBuffers", + "activeSourceCount", + "activeTexture", + "activeVRDisplays", + "actualBoundingBoxAscent", + "actualBoundingBoxDescent", + "actualBoundingBoxLeft", + "actualBoundingBoxRight", + "add", + "addAll", + "addBehavior", + "addCandidate", + "addColorStop", + "addCue", + "addElement", + "addEventListener", + "addFilter", + "addFromString", + "addFromUri", + "addIceCandidate", + "addImport", + "addListener", + "addModule", + "addNamed", + "addPageRule", + "addPath", + "addPointer", + "addRange", + "addRegion", + "addRule", + "addSearchEngine", + "addSourceBuffer", + "addStream", + "addTextTrack", + "addTrack", + "addTransceiver", + "addWakeLockListener", + "added", + "addedNodes", + "additionalName", + "additiveSymbols", + "addons", + "address", + "addressLine", + "adoptNode", + "adoptedStyleSheets", + "adr", + "advance", + "after", + "album", + "alert", + "algorithm", + "align", + "align-content", + "align-items", + "align-self", + "alignContent", + "alignItems", + "alignSelf", + "alignmentBaseline", + "alinkColor", + "all", + "allSettled", + "allow", + "allowFullscreen", + "allowPaymentRequest", + "allowedDirections", + "allowedFeatures", + "allowedToPlay", + "allowsFeature", + "alpha", + "alt", + "altGraphKey", + "altHtml", + "altKey", + "altLeft", + "alternate", + "alternateSetting", + "alternates", + "altitude", + "altitudeAccuracy", + "amplitude", + "ancestorOrigins", + "anchor", + "anchorNode", + "anchorOffset", + "anchors", + "and", + "angle", + "angularAcceleration", + "angularVelocity", + "animVal", + "animate", + "animatedInstanceRoot", + "animatedNormalizedPathSegList", + "animatedPathSegList", + "animatedPoints", + "animation", + "animation-delay", + "animation-direction", + "animation-duration", + "animation-fill-mode", + "animation-iteration-count", + "animation-name", + "animation-play-state", + "animation-timing-function", + "animationDelay", + "animationDirection", + "animationDuration", + "animationFillMode", + "animationIterationCount", + "animationName", + "animationPlayState", + "animationStartTime", + "animationTimingFunction", + "animationsPaused", + "anniversary", + "antialias", + "anticipatedRemoval", + "any", + "app", + "appCodeName", + "appMinorVersion", + "appName", + "appNotifications", + "appVersion", + "appearance", + "append", + "appendBuffer", + "appendChild", + "appendData", + "appendItem", + "appendMedium", + "appendNamed", + "appendRule", + "appendStream", + "appendWindowEnd", + "appendWindowStart", + "applets", + "applicationCache", + "applicationServerKey", + "apply", + "applyConstraints", + "applyElement", + "arc", + "arcTo", + "archive", + "areas", + "arguments", + "ariaAtomic", + "ariaAutoComplete", + "ariaBusy", + "ariaChecked", + "ariaColCount", + "ariaColIndex", + "ariaColSpan", + "ariaCurrent", + "ariaDescription", + "ariaDisabled", + "ariaExpanded", + "ariaHasPopup", + "ariaHidden", + "ariaKeyShortcuts", + "ariaLabel", + "ariaLevel", + "ariaLive", + "ariaModal", + "ariaMultiLine", + "ariaMultiSelectable", + "ariaOrientation", + "ariaPlaceholder", + "ariaPosInSet", + "ariaPressed", + "ariaReadOnly", + "ariaRelevant", + "ariaRequired", + "ariaRoleDescription", + "ariaRowCount", + "ariaRowIndex", + "ariaRowSpan", + "ariaSelected", + "ariaSetSize", + "ariaSort", + "ariaValueMax", + "ariaValueMin", + "ariaValueNow", + "ariaValueText", + "arrayBuffer", + "artist", + "artwork", + "as", + "asIntN", + "asUintN", + "asin", + "asinh", + "assert", + "assign", + "assignedElements", + "assignedNodes", + "assignedSlot", + "async", + "asyncIterator", + "atEnd", + "atan", + "atan2", + "atanh", + "atob", + "attachEvent", + "attachInternals", + "attachShader", + "attachShadow", + "attachments", + "attack", + "attestationObject", + "attrChange", + "attrName", + "attributeFilter", + "attributeName", + "attributeNamespace", + "attributeOldValue", + "attributeStyleMap", + "attributes", + "attribution", + "audioBitsPerSecond", + "audioTracks", + "audioWorklet", + "authenticatedSignedWrites", + "authenticatorData", + "autoIncrement", + "autobuffer", + "autocapitalize", + "autocomplete", + "autocorrect", + "autofocus", + "automationRate", + "autoplay", + "availHeight", + "availLeft", + "availTop", + "availWidth", + "availability", + "available", + "aversion", + "ax", + "axes", + "axis", + "ay", + "azimuth", + "b", + "back", + "backface-visibility", + "backfaceVisibility", + "background", + "background-attachment", + "background-blend-mode", + "background-clip", + "background-color", + "background-image", + "background-origin", + "background-position", + "background-position-x", + "background-position-y", + "background-repeat", + "background-size", + "backgroundAttachment", + "backgroundBlendMode", + "backgroundClip", + "backgroundColor", + "backgroundFetch", + "backgroundImage", + "backgroundOrigin", + "backgroundPosition", + "backgroundPositionX", + "backgroundPositionY", + "backgroundRepeat", + "backgroundSize", + "badInput", + "badge", + "balance", + "baseFrequencyX", + "baseFrequencyY", + "baseLatency", + "baseLayer", + "baseNode", + "baseOffset", + "baseURI", + "baseVal", + "baselineShift", + "battery", + "bday", + "before", + "beginElement", + "beginElementAt", + "beginPath", + "beginQuery", + "beginTransformFeedback", + "behavior", + "behaviorCookie", + "behaviorPart", + "behaviorUrns", + "beta", + "bezierCurveTo", + "bgColor", + "bgProperties", + "bias", + "big", + "bigint64", + "biguint64", + "binaryType", + "bind", + "bindAttribLocation", + "bindBuffer", + "bindBufferBase", + "bindBufferRange", + "bindFramebuffer", + "bindRenderbuffer", + "bindSampler", + "bindTexture", + "bindTransformFeedback", + "bindVertexArray", + "blendColor", + "blendEquation", + "blendEquationSeparate", + "blendFunc", + "blendFuncSeparate", + "blink", + "blitFramebuffer", + "blob", + "block-size", + "blockDirection", + "blockSize", + "blockedURI", + "blue", + "bluetooth", + "blur", + "body", + "bodyUsed", + "bold", + "bookmarks", + "booleanValue", + "border", + "border-block", + "border-block-color", + "border-block-end", + "border-block-end-color", + "border-block-end-style", + "border-block-end-width", + "border-block-start", + "border-block-start-color", + "border-block-start-style", + "border-block-start-width", + "border-block-style", + "border-block-width", + "border-bottom", + "border-bottom-color", + "border-bottom-left-radius", + "border-bottom-right-radius", + "border-bottom-style", + "border-bottom-width", + "border-collapse", + "border-color", + "border-end-end-radius", + "border-end-start-radius", + "border-image", + "border-image-outset", + "border-image-repeat", + "border-image-slice", + "border-image-source", + "border-image-width", + "border-inline", + "border-inline-color", + "border-inline-end", + "border-inline-end-color", + "border-inline-end-style", + "border-inline-end-width", + "border-inline-start", + "border-inline-start-color", + "border-inline-start-style", + "border-inline-start-width", + "border-inline-style", + "border-inline-width", + "border-left", + "border-left-color", + "border-left-style", + "border-left-width", + "border-radius", + "border-right", + "border-right-color", + "border-right-style", + "border-right-width", + "border-spacing", + "border-start-end-radius", + "border-start-start-radius", + "border-style", + "border-top", + "border-top-color", + "border-top-left-radius", + "border-top-right-radius", + "border-top-style", + "border-top-width", + "border-width", + "borderBlock", + "borderBlockColor", + "borderBlockEnd", + "borderBlockEndColor", + "borderBlockEndStyle", + "borderBlockEndWidth", + "borderBlockStart", + "borderBlockStartColor", + "borderBlockStartStyle", + "borderBlockStartWidth", + "borderBlockStyle", + "borderBlockWidth", + "borderBottom", + "borderBottomColor", + "borderBottomLeftRadius", + "borderBottomRightRadius", + "borderBottomStyle", + "borderBottomWidth", + "borderBoxSize", + "borderCollapse", + "borderColor", + "borderColorDark", + "borderColorLight", + "borderEndEndRadius", + "borderEndStartRadius", + "borderImage", + "borderImageOutset", + "borderImageRepeat", + "borderImageSlice", + "borderImageSource", + "borderImageWidth", + "borderInline", + "borderInlineColor", + "borderInlineEnd", + "borderInlineEndColor", + "borderInlineEndStyle", + "borderInlineEndWidth", + "borderInlineStart", + "borderInlineStartColor", + "borderInlineStartStyle", + "borderInlineStartWidth", + "borderInlineStyle", + "borderInlineWidth", + "borderLeft", + "borderLeftColor", + "borderLeftStyle", + "borderLeftWidth", + "borderRadius", + "borderRight", + "borderRightColor", + "borderRightStyle", + "borderRightWidth", + "borderSpacing", + "borderStartEndRadius", + "borderStartStartRadius", + "borderStyle", + "borderTop", + "borderTopColor", + "borderTopLeftRadius", + "borderTopRightRadius", + "borderTopStyle", + "borderTopWidth", + "borderWidth", + "bottom", + "bottomMargin", + "bound", + "boundElements", + "boundingClientRect", + "boundingHeight", + "boundingLeft", + "boundingTop", + "boundingWidth", + "bounds", + "boundsGeometry", + "box-decoration-break", + "box-shadow", + "box-sizing", + "boxDecorationBreak", + "boxShadow", + "boxSizing", + "break-after", + "break-before", + "break-inside", + "breakAfter", + "breakBefore", + "breakInside", + "broadcast", + "browserLanguage", + "btoa", + "bubbles", + "buffer", + "bufferData", + "bufferDepth", + "bufferSize", + "bufferSubData", + "buffered", + "bufferedAmount", + "bufferedAmountLowThreshold", + "buildID", + "buildNumber", + "button", + "buttonID", + "buttons", + "byteLength", + "byteOffset", + "bytesWritten", + "c", + "cache", + "caches", + "call", + "caller", + "canBeFormatted", + "canBeMounted", + "canBeShared", + "canHaveChildren", + "canHaveHTML", + "canInsertDTMF", + "canMakePayment", + "canPlayType", + "canPresent", + "canTrickleIceCandidates", + "cancel", + "cancelAndHoldAtTime", + "cancelAnimationFrame", + "cancelBubble", + "cancelIdleCallback", + "cancelScheduledValues", + "cancelVideoFrameCallback", + "cancelWatchAvailability", + "cancelable", + "candidate", + "canonicalUUID", + "canvas", + "capabilities", + "caption", + "caption-side", + "captionSide", + "capture", + "captureEvents", + "captureStackTrace", + "captureStream", + "caret-color", + "caretBidiLevel", + "caretColor", + "caretPositionFromPoint", + "caretRangeFromPoint", + "cast", + "catch", + "category", + "cbrt", + "cd", + "ceil", + "cellIndex", + "cellPadding", + "cellSpacing", + "cells", + "ch", + "chOff", + "chain", + "challenge", + "changeType", + "changedTouches", + "channel", + "channelCount", + "channelCountMode", + "channelInterpretation", + "char", + "charAt", + "charCode", + "charCodeAt", + "charIndex", + "charLength", + "characterData", + "characterDataOldValue", + "characterSet", + "characteristic", + "charging", + "chargingTime", + "charset", + "check", + "checkEnclosure", + "checkFramebufferStatus", + "checkIntersection", + "checkValidity", + "checked", + "childElementCount", + "childList", + "childNodes", + "children", + "chrome", + "ciphertext", + "cite", + "city", + "claimInterface", + "claimed", + "classList", + "className", + "classid", + "clear", + "clearAppBadge", + "clearAttributes", + "clearBufferfi", + "clearBufferfv", + "clearBufferiv", + "clearBufferuiv", + "clearColor", + "clearData", + "clearDepth", + "clearHalt", + "clearImmediate", + "clearInterval", + "clearLiveSeekableRange", + "clearMarks", + "clearMaxGCPauseAccumulator", + "clearMeasures", + "clearParameters", + "clearRect", + "clearResourceTimings", + "clearShadow", + "clearStencil", + "clearTimeout", + "clearWatch", + "click", + "clickCount", + "clientDataJSON", + "clientHeight", + "clientInformation", + "clientLeft", + "clientRect", + "clientRects", + "clientTop", + "clientWaitSync", + "clientWidth", + "clientX", + "clientY", + "clip", + "clip-path", + "clip-rule", + "clipBottom", + "clipLeft", + "clipPath", + "clipPathUnits", + "clipRight", + "clipRule", + "clipTop", + "clipboard", + "clipboardData", + "clone", + "cloneContents", + "cloneNode", + "cloneRange", + "close", + "closePath", + "closed", + "closest", + "clz", + "clz32", + "cm", + "cmp", + "code", + "codeBase", + "codePointAt", + "codeType", + "colSpan", + "collapse", + "collapseToEnd", + "collapseToStart", + "collapsed", + "collect", + "colno", + "color", + "color-adjust", + "color-interpolation", + "color-interpolation-filters", + "colorAdjust", + "colorDepth", + "colorInterpolation", + "colorInterpolationFilters", + "colorMask", + "colorType", + "cols", + "column-count", + "column-fill", + "column-gap", + "column-rule", + "column-rule-color", + "column-rule-style", + "column-rule-width", + "column-span", + "column-width", + "columnCount", + "columnFill", + "columnGap", + "columnNumber", + "columnRule", + "columnRuleColor", + "columnRuleStyle", + "columnRuleWidth", + "columnSpan", + "columnWidth", + "columns", + "command", + "commit", + "commitPreferences", + "commitStyles", + "commonAncestorContainer", + "compact", + "compareBoundaryPoints", + "compareDocumentPosition", + "compareEndPoints", + "compareExchange", + "compareNode", + "comparePoint", + "compatMode", + "compatible", + "compile", + "compileShader", + "compileStreaming", + "complete", + "component", + "componentFromPoint", + "composed", + "composedPath", + "composite", + "compositionEndOffset", + "compositionStartOffset", + "compressedTexImage2D", + "compressedTexImage3D", + "compressedTexSubImage2D", + "compressedTexSubImage3D", + "computedStyleMap", + "concat", + "conditionText", + "coneInnerAngle", + "coneOuterAngle", + "coneOuterGain", + "configuration", + "configurationName", + "configurationValue", + "configurations", + "confirm", + "confirmComposition", + "confirmSiteSpecificTrackingException", + "confirmWebWideTrackingException", + "connect", + "connectEnd", + "connectShark", + "connectStart", + "connected", + "connection", + "connectionList", + "connectionSpeed", + "connectionState", + "connections", + "console", + "consolidate", + "constraint", + "constrictionActive", + "construct", + "constructor", + "contactID", + "contain", + "containerId", + "containerName", + "containerSrc", + "containerType", + "contains", + "containsNode", + "content", + "contentBoxSize", + "contentDocument", + "contentEditable", + "contentHint", + "contentOverflow", + "contentRect", + "contentScriptType", + "contentStyleType", + "contentType", + "contentWindow", + "context", + "contextMenu", + "contextmenu", + "continue", + "continuePrimaryKey", + "continuous", + "control", + "controlTransferIn", + "controlTransferOut", + "controller", + "controls", + "controlsList", + "convertPointFromNode", + "convertQuadFromNode", + "convertRectFromNode", + "convertToBlob", + "convertToSpecifiedUnits", + "cookie", + "cookieEnabled", + "coords", + "copyBufferSubData", + "copyFromChannel", + "copyTexImage2D", + "copyTexSubImage2D", + "copyTexSubImage3D", + "copyToChannel", + "copyWithin", + "correspondingElement", + "correspondingUseElement", + "corruptedVideoFrames", + "cos", + "cosh", + "count", + "countReset", + "counter-increment", + "counter-reset", + "counter-set", + "counterIncrement", + "counterReset", + "counterSet", + "country", + "cpuClass", + "cpuSleepAllowed", + "create", + "createAnalyser", + "createAnswer", + "createAttribute", + "createAttributeNS", + "createBiquadFilter", + "createBuffer", + "createBufferSource", + "createCDATASection", + "createCSSStyleSheet", + "createCaption", + "createChannelMerger", + "createChannelSplitter", + "createComment", + "createConstantSource", + "createContextualFragment", + "createControlRange", + "createConvolver", + "createDTMFSender", + "createDataChannel", + "createDelay", + "createDelayNode", + "createDocument", + "createDocumentFragment", + "createDocumentType", + "createDynamicsCompressor", + "createElement", + "createElementNS", + "createEntityReference", + "createEvent", + "createEventObject", + "createExpression", + "createFramebuffer", + "createFunction", + "createGain", + "createGainNode", + "createHTML", + "createHTMLDocument", + "createIIRFilter", + "createImageBitmap", + "createImageData", + "createIndex", + "createJavaScriptNode", + "createLinearGradient", + "createMediaElementSource", + "createMediaKeys", + "createMediaStreamDestination", + "createMediaStreamSource", + "createMediaStreamTrackSource", + "createMutableFile", + "createNSResolver", + "createNodeIterator", + "createNotification", + "createObjectStore", + "createObjectURL", + "createOffer", + "createOscillator", + "createPanner", + "createPattern", + "createPeriodicWave", + "createPolicy", + "createPopup", + "createProcessingInstruction", + "createProgram", + "createQuery", + "createRadialGradient", + "createRange", + "createRangeCollection", + "createReader", + "createRenderbuffer", + "createSVGAngle", + "createSVGLength", + "createSVGMatrix", + "createSVGNumber", + "createSVGPathSegArcAbs", + "createSVGPathSegArcRel", + "createSVGPathSegClosePath", + "createSVGPathSegCurvetoCubicAbs", + "createSVGPathSegCurvetoCubicRel", + "createSVGPathSegCurvetoCubicSmoothAbs", + "createSVGPathSegCurvetoCubicSmoothRel", + "createSVGPathSegCurvetoQuadraticAbs", + "createSVGPathSegCurvetoQuadraticRel", + "createSVGPathSegCurvetoQuadraticSmoothAbs", + "createSVGPathSegCurvetoQuadraticSmoothRel", + "createSVGPathSegLinetoAbs", + "createSVGPathSegLinetoHorizontalAbs", + "createSVGPathSegLinetoHorizontalRel", + "createSVGPathSegLinetoRel", + "createSVGPathSegLinetoVerticalAbs", + "createSVGPathSegLinetoVerticalRel", + "createSVGPathSegMovetoAbs", + "createSVGPathSegMovetoRel", + "createSVGPoint", + "createSVGRect", + "createSVGTransform", + "createSVGTransformFromMatrix", + "createSampler", + "createScript", + "createScriptProcessor", + "createScriptURL", + "createSession", + "createShader", + "createShadowRoot", + "createStereoPanner", + "createStyleSheet", + "createTBody", + "createTFoot", + "createTHead", + "createTextNode", + "createTextRange", + "createTexture", + "createTouch", + "createTouchList", + "createTransformFeedback", + "createTreeWalker", + "createVertexArray", + "createWaveShaper", + "creationTime", + "credentials", + "crossOrigin", + "crossOriginIsolated", + "crypto", + "csi", + "csp", + "cssFloat", + "cssRules", + "cssText", + "cssValueType", + "ctrlKey", + "ctrlLeft", + "cues", + "cullFace", + "currentDirection", + "currentLocalDescription", + "currentNode", + "currentPage", + "currentRect", + "currentRemoteDescription", + "currentScale", + "currentScript", + "currentSrc", + "currentState", + "currentStyle", + "currentTarget", + "currentTime", + "currentTranslate", + "currentView", + "cursor", + "curve", + "customElements", + "customError", + "cx", + "cy", + "d", + "data", + "dataFld", + "dataFormatAs", + "dataLoss", + "dataLossMessage", + "dataPageSize", + "dataSrc", + "dataTransfer", + "database", + "databases", + "dataset", + "dateTime", + "db", + "debug", + "debuggerEnabled", + "declare", + "decode", + "decodeAudioData", + "decodeURI", + "decodeURIComponent", + "decodedBodySize", + "decoding", + "decodingInfo", + "decrypt", + "default", + "defaultCharset", + "defaultChecked", + "defaultMuted", + "defaultPlaybackRate", + "defaultPolicy", + "defaultPrevented", + "defaultRequest", + "defaultSelected", + "defaultStatus", + "defaultURL", + "defaultValue", + "defaultView", + "defaultstatus", + "defer", + "define", + "defineMagicFunction", + "defineMagicVariable", + "defineProperties", + "defineProperty", + "deg", + "delay", + "delayTime", + "delegatesFocus", + "delete", + "deleteBuffer", + "deleteCaption", + "deleteCell", + "deleteContents", + "deleteData", + "deleteDatabase", + "deleteFramebuffer", + "deleteFromDocument", + "deleteIndex", + "deleteMedium", + "deleteObjectStore", + "deleteProgram", + "deleteProperty", + "deleteQuery", + "deleteRenderbuffer", + "deleteRow", + "deleteRule", + "deleteSampler", + "deleteShader", + "deleteSync", + "deleteTFoot", + "deleteTHead", + "deleteTexture", + "deleteTransformFeedback", + "deleteVertexArray", + "deliverChangeRecords", + "delivery", + "deliveryInfo", + "deliveryStatus", + "deliveryTimestamp", + "delta", + "deltaMode", + "deltaX", + "deltaY", + "deltaZ", + "dependentLocality", + "depthFar", + "depthFunc", + "depthMask", + "depthNear", + "depthRange", + "deref", + "deriveBits", + "deriveKey", + "description", + "deselectAll", + "designMode", + "desiredSize", + "destination", + "destinationURL", + "detach", + "detachEvent", + "detachShader", + "detail", + "details", + "detect", + "detune", + "device", + "deviceClass", + "deviceId", + "deviceMemory", + "devicePixelContentBoxSize", + "devicePixelRatio", + "deviceProtocol", + "deviceSubclass", + "deviceVersionMajor", + "deviceVersionMinor", + "deviceVersionSubminor", + "deviceXDPI", + "deviceYDPI", + "didTimeout", + "diffuseConstant", + "digest", + "dimensions", + "dir", + "dirName", + "direction", + "dirxml", + "disable", + "disablePictureInPicture", + "disableRemotePlayback", + "disableVertexAttribArray", + "disabled", + "dischargingTime", + "disconnect", + "disconnectShark", + "dispatchEvent", + "display", + "displayId", + "displayName", + "disposition", + "distanceModel", + "div", + "divisor", + "djsapi", + "djsproxy", + "doImport", + "doNotTrack", + "doScroll", + "doctype", + "document", + "documentElement", + "documentMode", + "documentURI", + "dolphin", + "dolphinGameCenter", + "dolphininfo", + "dolphinmeta", + "domComplete", + "domContentLoadedEventEnd", + "domContentLoadedEventStart", + "domInteractive", + "domLoading", + "domOverlayState", + "domain", + "domainLookupEnd", + "domainLookupStart", + "dominant-baseline", + "dominantBaseline", + "done", + "dopplerFactor", + "dotAll", + "downDegrees", + "downlink", + "download", + "downloadTotal", + "downloaded", + "dpcm", + "dpi", + "dppx", + "dragDrop", + "draggable", + "drawArrays", + "drawArraysInstanced", + "drawArraysInstancedANGLE", + "drawBuffers", + "drawCustomFocusRing", + "drawElements", + "drawElementsInstanced", + "drawElementsInstancedANGLE", + "drawFocusIfNeeded", + "drawImage", + "drawImageFromRect", + "drawRangeElements", + "drawSystemFocusRing", + "drawingBufferHeight", + "drawingBufferWidth", + "dropEffect", + "droppedVideoFrames", + "dropzone", + "dtmf", + "dump", + "dumpProfile", + "duplicate", + "durability", + "duration", + "dvname", + "dvnum", + "dx", + "dy", + "dynsrc", + "e", + "edgeMode", + "effect", + "effectAllowed", + "effectiveDirective", + "effectiveType", + "elapsedTime", + "element", + "elementFromPoint", + "elementTiming", + "elements", + "elementsFromPoint", + "elevation", + "ellipse", + "em", + "email", + "embeds", + "emma", + "empty", + "empty-cells", + "emptyCells", + "emptyHTML", + "emptyScript", + "emulatedPosition", + "enable", + "enableBackground", + "enableDelegations", + "enableStyleSheetsForSet", + "enableVertexAttribArray", + "enabled", + "enabledPlugin", + "encode", + "encodeInto", + "encodeURI", + "encodeURIComponent", + "encodedBodySize", + "encoding", + "encodingInfo", + "encrypt", + "enctype", + "end", + "endContainer", + "endElement", + "endElementAt", + "endOfStream", + "endOffset", + "endQuery", + "endTime", + "endTransformFeedback", + "ended", + "endpoint", + "endpointNumber", + "endpoints", + "endsWith", + "enterKeyHint", + "entities", + "entries", + "entryType", + "enumerate", + "enumerateDevices", + "enumerateEditable", + "environmentBlendMode", + "equals", + "error", + "errorCode", + "errorDetail", + "errorText", + "escape", + "estimate", + "eval", + "evaluate", + "event", + "eventPhase", + "every", + "ex", + "exception", + "exchange", + "exec", + "execCommand", + "execCommandShowHelp", + "execScript", + "exitFullscreen", + "exitPictureInPicture", + "exitPointerLock", + "exitPresent", + "exp", + "expand", + "expandEntityReferences", + "expando", + "expansion", + "expiration", + "expirationTime", + "expires", + "expiryDate", + "explicitOriginalTarget", + "expm1", + "exponent", + "exponentialRampToValueAtTime", + "exportKey", + "exports", + "extend", + "extensions", + "extentNode", + "extentOffset", + "external", + "externalResourcesRequired", + "extractContents", + "extractable", + "eye", + "f", + "face", + "factoryReset", + "failureReason", + "fallback", + "family", + "familyName", + "farthestViewportElement", + "fastSeek", + "fatal", + "featureId", + "featurePolicy", + "featureSettings", + "features", + "fenceSync", + "fetch", + "fetchStart", + "fftSize", + "fgColor", + "fieldOfView", + "file", + "fileCreatedDate", + "fileHandle", + "fileModifiedDate", + "fileName", + "fileSize", + "fileUpdatedDate", + "filename", + "files", + "filesystem", + "fill", + "fill-opacity", + "fill-rule", + "fillLightMode", + "fillOpacity", + "fillRect", + "fillRule", + "fillStyle", + "fillText", + "filter", + "filterResX", + "filterResY", + "filterUnits", + "filters", + "finally", + "find", + "findIndex", + "findRule", + "findText", + "finish", + "finished", + "fireEvent", + "firesTouchEvents", + "firstChild", + "firstElementChild", + "firstPage", + "fixed", + "flags", + "flat", + "flatMap", + "flex", + "flex-basis", + "flex-direction", + "flex-flow", + "flex-grow", + "flex-shrink", + "flex-wrap", + "flexBasis", + "flexDirection", + "flexFlow", + "flexGrow", + "flexShrink", + "flexWrap", + "flipX", + "flipY", + "float", + "float32", + "float64", + "flood-color", + "flood-opacity", + "floodColor", + "floodOpacity", + "floor", + "flush", + "focus", + "focusNode", + "focusOffset", + "font", + "font-family", + "font-feature-settings", + "font-kerning", + "font-language-override", + "font-optical-sizing", + "font-size", + "font-size-adjust", + "font-stretch", + "font-style", + "font-synthesis", + "font-variant", + "font-variant-alternates", + "font-variant-caps", + "font-variant-east-asian", + "font-variant-ligatures", + "font-variant-numeric", + "font-variant-position", + "font-variation-settings", + "font-weight", + "fontFamily", + "fontFeatureSettings", + "fontKerning", + "fontLanguageOverride", + "fontOpticalSizing", + "fontSize", + "fontSizeAdjust", + "fontSmoothingEnabled", + "fontStretch", + "fontStyle", + "fontSynthesis", + "fontVariant", + "fontVariantAlternates", + "fontVariantCaps", + "fontVariantEastAsian", + "fontVariantLigatures", + "fontVariantNumeric", + "fontVariantPosition", + "fontVariationSettings", + "fontWeight", + "fontcolor", + "fontfaces", + "fonts", + "fontsize", + "for", + "forEach", + "force", + "forceRedraw", + "form", + "formAction", + "formData", + "formEnctype", + "formMethod", + "formNoValidate", + "formTarget", + "format", + "formatToParts", + "forms", + "forward", + "forwardX", + "forwardY", + "forwardZ", + "foundation", + "fr", + "fragmentDirective", + "frame", + "frameBorder", + "frameElement", + "frameSpacing", + "framebuffer", + "framebufferHeight", + "framebufferRenderbuffer", + "framebufferTexture2D", + "framebufferTextureLayer", + "framebufferWidth", + "frames", + "freeSpace", + "freeze", + "frequency", + "frequencyBinCount", + "from", + "fromCharCode", + "fromCodePoint", + "fromElement", + "fromEntries", + "fromFloat32Array", + "fromFloat64Array", + "fromMatrix", + "fromPoint", + "fromQuad", + "fromRect", + "frontFace", + "fround", + "fullPath", + "fullScreen", + "fullscreen", + "fullscreenElement", + "fullscreenEnabled", + "fx", + "fy", + "gain", + "gamepad", + "gamma", + "gap", + "gatheringState", + "gatt", + "genderIdentity", + "generateCertificate", + "generateKey", + "generateMipmap", + "generateRequest", + "geolocation", + "gestureObject", + "get", + "getActiveAttrib", + "getActiveUniform", + "getActiveUniformBlockName", + "getActiveUniformBlockParameter", + "getActiveUniforms", + "getAdjacentText", + "getAll", + "getAllKeys", + "getAllResponseHeaders", + "getAllowlistForFeature", + "getAnimations", + "getAsFile", + "getAsString", + "getAttachedShaders", + "getAttribLocation", + "getAttribute", + "getAttributeNS", + "getAttributeNames", + "getAttributeNode", + "getAttributeNodeNS", + "getAttributeType", + "getAudioTracks", + "getAvailability", + "getBBox", + "getBattery", + "getBigInt64", + "getBigUint64", + "getBlob", + "getBookmark", + "getBoundingClientRect", + "getBounds", + "getBoxQuads", + "getBufferParameter", + "getBufferSubData", + "getByteFrequencyData", + "getByteTimeDomainData", + "getCSSCanvasContext", + "getCTM", + "getCandidateWindowClientRect", + "getCanonicalLocales", + "getCapabilities", + "getChannelData", + "getCharNumAtPosition", + "getCharacteristic", + "getCharacteristics", + "getClientExtensionResults", + "getClientRect", + "getClientRects", + "getCoalescedEvents", + "getCompositionAlternatives", + "getComputedStyle", + "getComputedTextLength", + "getComputedTiming", + "getConfiguration", + "getConstraints", + "getContext", + "getContextAttributes", + "getContributingSources", + "getCounterValue", + "getCueAsHTML", + "getCueById", + "getCurrentPosition", + "getCurrentTime", + "getData", + "getDatabaseNames", + "getDate", + "getDay", + "getDefaultComputedStyle", + "getDescriptor", + "getDescriptors", + "getDestinationInsertionPoints", + "getDevices", + "getDirectory", + "getDisplayMedia", + "getDistributedNodes", + "getEditable", + "getElementById", + "getElementsByClassName", + "getElementsByName", + "getElementsByTagName", + "getElementsByTagNameNS", + "getEnclosureList", + "getEndPositionOfChar", + "getEntries", + "getEntriesByName", + "getEntriesByType", + "getError", + "getExtension", + "getExtentOfChar", + "getEyeParameters", + "getFeature", + "getFile", + "getFiles", + "getFilesAndDirectories", + "getFingerprints", + "getFloat32", + "getFloat64", + "getFloatFrequencyData", + "getFloatTimeDomainData", + "getFloatValue", + "getFragDataLocation", + "getFrameData", + "getFramebufferAttachmentParameter", + "getFrequencyResponse", + "getFullYear", + "getGamepads", + "getHitTestResults", + "getHitTestResultsForTransientInput", + "getHours", + "getIdentityAssertion", + "getIds", + "getImageData", + "getIndexedParameter", + "getInstalledRelatedApps", + "getInt16", + "getInt32", + "getInt8", + "getInternalformatParameter", + "getIntersectionList", + "getItem", + "getItems", + "getKey", + "getKeyframes", + "getLayers", + "getLayoutMap", + "getLineDash", + "getLocalCandidates", + "getLocalParameters", + "getLocalStreams", + "getMarks", + "getMatchedCSSRules", + "getMaxGCPauseSinceClear", + "getMeasures", + "getMetadata", + "getMilliseconds", + "getMinutes", + "getModifierState", + "getMonth", + "getNamedItem", + "getNamedItemNS", + "getNativeFramebufferScaleFactor", + "getNotifications", + "getNotifier", + "getNumberOfChars", + "getOffsetReferenceSpace", + "getOutputTimestamp", + "getOverrideHistoryNavigationMode", + "getOverrideStyle", + "getOwnPropertyDescriptor", + "getOwnPropertyDescriptors", + "getOwnPropertyNames", + "getOwnPropertySymbols", + "getParameter", + "getParameters", + "getParent", + "getPathSegAtLength", + "getPhotoCapabilities", + "getPhotoSettings", + "getPointAtLength", + "getPose", + "getPredictedEvents", + "getPreference", + "getPreferenceDefault", + "getPresentationAttribute", + "getPreventDefault", + "getPrimaryService", + "getPrimaryServices", + "getProgramInfoLog", + "getProgramParameter", + "getPropertyCSSValue", + "getPropertyPriority", + "getPropertyShorthand", + "getPropertyType", + "getPropertyValue", + "getPrototypeOf", + "getQuery", + "getQueryParameter", + "getRGBColorValue", + "getRandomValues", + "getRangeAt", + "getReader", + "getReceivers", + "getRectValue", + "getRegistration", + "getRegistrations", + "getRemoteCandidates", + "getRemoteCertificates", + "getRemoteParameters", + "getRemoteStreams", + "getRenderbufferParameter", + "getResponseHeader", + "getRoot", + "getRootNode", + "getRotationOfChar", + "getSVGDocument", + "getSamplerParameter", + "getScreenCTM", + "getSeconds", + "getSelectedCandidatePair", + "getSelection", + "getSenders", + "getService", + "getSettings", + "getShaderInfoLog", + "getShaderParameter", + "getShaderPrecisionFormat", + "getShaderSource", + "getSimpleDuration", + "getSiteIcons", + "getSources", + "getSpeculativeParserUrls", + "getStartPositionOfChar", + "getStartTime", + "getState", + "getStats", + "getStatusForPolicy", + "getStorageUpdates", + "getStreamById", + "getStringValue", + "getSubStringLength", + "getSubscription", + "getSupportedConstraints", + "getSupportedExtensions", + "getSupportedFormats", + "getSyncParameter", + "getSynchronizationSources", + "getTags", + "getTargetRanges", + "getTexParameter", + "getTime", + "getTimezoneOffset", + "getTiming", + "getTotalLength", + "getTrackById", + "getTracks", + "getTransceivers", + "getTransform", + "getTransformFeedbackVarying", + "getTransformToElement", + "getTransports", + "getType", + "getTypeMapping", + "getUTCDate", + "getUTCDay", + "getUTCFullYear", + "getUTCHours", + "getUTCMilliseconds", + "getUTCMinutes", + "getUTCMonth", + "getUTCSeconds", + "getUint16", + "getUint32", + "getUint8", + "getUniform", + "getUniformBlockIndex", + "getUniformIndices", + "getUniformLocation", + "getUserMedia", + "getVRDisplays", + "getValues", + "getVarDate", + "getVariableValue", + "getVertexAttrib", + "getVertexAttribOffset", + "getVideoPlaybackQuality", + "getVideoTracks", + "getViewerPose", + "getViewport", + "getVoices", + "getWakeLockState", + "getWriter", + "getYear", + "givenName", + "global", + "globalAlpha", + "globalCompositeOperation", + "globalThis", + "glyphOrientationHorizontal", + "glyphOrientationVertical", + "glyphRef", + "go", + "grabFrame", + "grad", + "gradientTransform", + "gradientUnits", + "grammars", + "green", + "grid", + "grid-area", + "grid-auto-columns", + "grid-auto-flow", + "grid-auto-rows", + "grid-column", + "grid-column-end", + "grid-column-gap", + "grid-column-start", + "grid-gap", + "grid-row", + "grid-row-end", + "grid-row-gap", + "grid-row-start", + "grid-template", + "grid-template-areas", + "grid-template-columns", + "grid-template-rows", + "gridArea", + "gridAutoColumns", + "gridAutoFlow", + "gridAutoRows", + "gridColumn", + "gridColumnEnd", + "gridColumnGap", + "gridColumnStart", + "gridGap", + "gridRow", + "gridRowEnd", + "gridRowGap", + "gridRowStart", + "gridTemplate", + "gridTemplateAreas", + "gridTemplateColumns", + "gridTemplateRows", + "gripSpace", + "group", + "groupCollapsed", + "groupEnd", + "groupId", + "hadRecentInput", + "hand", + "handedness", + "hapticActuators", + "hardwareConcurrency", + "has", + "hasAttribute", + "hasAttributeNS", + "hasAttributes", + "hasBeenActive", + "hasChildNodes", + "hasComposition", + "hasEnrolledInstrument", + "hasExtension", + "hasExternalDisplay", + "hasFeature", + "hasFocus", + "hasInstance", + "hasLayout", + "hasOrientation", + "hasOwnProperty", + "hasPointerCapture", + "hasPosition", + "hasReading", + "hasStorageAccess", + "hash", + "head", + "headers", + "heading", + "height", + "hidden", + "hide", + "hideFocus", + "high", + "highWaterMark", + "hint", + "history", + "honorificPrefix", + "honorificSuffix", + "horizontalOverflow", + "host", + "hostCandidate", + "hostname", + "href", + "hrefTranslate", + "hreflang", + "hspace", + "html5TagCheckInerface", + "htmlFor", + "htmlText", + "httpEquiv", + "httpRequestStatusCode", + "hwTimestamp", + "hyphens", + "hypot", + "iccId", + "iceConnectionState", + "iceGatheringState", + "iceTransport", + "icon", + "iconURL", + "id", + "identifier", + "identity", + "idpLoginUrl", + "ignoreBOM", + "ignoreCase", + "ignoreDepthValues", + "image-orientation", + "image-rendering", + "imageHeight", + "imageOrientation", + "imageRendering", + "imageSizes", + "imageSmoothingEnabled", + "imageSmoothingQuality", + "imageSrcset", + "imageWidth", + "images", + "ime-mode", + "imeMode", + "implementation", + "importKey", + "importNode", + "importStylesheet", + "imports", + "impp", + "imul", + "in", + "in1", + "in2", + "inBandMetadataTrackDispatchType", + "inRange", + "includes", + "incremental", + "indeterminate", + "index", + "indexNames", + "indexOf", + "indexedDB", + "indicate", + "inertiaDestinationX", + "inertiaDestinationY", + "info", + "init", + "initAnimationEvent", + "initBeforeLoadEvent", + "initClipboardEvent", + "initCloseEvent", + "initCommandEvent", + "initCompositionEvent", + "initCustomEvent", + "initData", + "initDataType", + "initDeviceMotionEvent", + "initDeviceOrientationEvent", + "initDragEvent", + "initErrorEvent", + "initEvent", + "initFocusEvent", + "initGestureEvent", + "initHashChangeEvent", + "initKeyEvent", + "initKeyboardEvent", + "initMSManipulationEvent", + "initMessageEvent", + "initMouseEvent", + "initMouseScrollEvent", + "initMouseWheelEvent", + "initMutationEvent", + "initNSMouseEvent", + "initOverflowEvent", + "initPageEvent", + "initPageTransitionEvent", + "initPointerEvent", + "initPopStateEvent", + "initProgressEvent", + "initScrollAreaEvent", + "initSimpleGestureEvent", + "initStorageEvent", + "initTextEvent", + "initTimeEvent", + "initTouchEvent", + "initTransitionEvent", + "initUIEvent", + "initWebKitAnimationEvent", + "initWebKitTransitionEvent", + "initWebKitWheelEvent", + "initWheelEvent", + "initialTime", + "initialize", + "initiatorType", + "inline-size", + "inlineSize", + "inlineVerticalFieldOfView", + "inner", + "innerHTML", + "innerHeight", + "innerText", + "innerWidth", + "input", + "inputBuffer", + "inputEncoding", + "inputMethod", + "inputMode", + "inputSource", + "inputSources", + "inputType", + "inputs", + "insertAdjacentElement", + "insertAdjacentHTML", + "insertAdjacentText", + "insertBefore", + "insertCell", + "insertDTMF", + "insertData", + "insertItemBefore", + "insertNode", + "insertRow", + "insertRule", + "inset", + "inset-block", + "inset-block-end", + "inset-block-start", + "inset-inline", + "inset-inline-end", + "inset-inline-start", + "insetBlock", + "insetBlockEnd", + "insetBlockStart", + "insetInline", + "insetInlineEnd", + "insetInlineStart", + "installing", + "instanceRoot", + "instantiate", + "instantiateStreaming", + "instruments", + "int16", + "int32", + "int8", + "integrity", + "interactionMode", + "intercept", + "interfaceClass", + "interfaceName", + "interfaceNumber", + "interfaceProtocol", + "interfaceSubclass", + "interfaces", + "interimResults", + "internalSubset", + "interpretation", + "intersectionRatio", + "intersectionRect", + "intersectsNode", + "interval", + "invalidIteratorState", + "invalidateFramebuffer", + "invalidateSubFramebuffer", + "inverse", + "invertSelf", + "is", + "is2D", + "isActive", + "isAlternate", + "isArray", + "isBingCurrentSearchDefault", + "isBuffer", + "isCandidateWindowVisible", + "isChar", + "isCollapsed", + "isComposing", + "isConcatSpreadable", + "isConnected", + "isContentEditable", + "isContentHandlerRegistered", + "isContextLost", + "isDefaultNamespace", + "isDirectory", + "isDisabled", + "isEnabled", + "isEqual", + "isEqualNode", + "isExtensible", + "isExternalCTAP2SecurityKeySupported", + "isFile", + "isFinite", + "isFramebuffer", + "isFrozen", + "isGenerator", + "isHTML", + "isHistoryNavigation", + "isId", + "isIdentity", + "isInjected", + "isInteger", + "isIntersecting", + "isLockFree", + "isMap", + "isMultiLine", + "isNaN", + "isOpen", + "isPointInFill", + "isPointInPath", + "isPointInRange", + "isPointInStroke", + "isPrefAlternate", + "isPresenting", + "isPrimary", + "isProgram", + "isPropertyImplicit", + "isProtocolHandlerRegistered", + "isPrototypeOf", + "isQuery", + "isRenderbuffer", + "isSafeInteger", + "isSameNode", + "isSampler", + "isScript", + "isScriptURL", + "isSealed", + "isSecureContext", + "isSessionSupported", + "isShader", + "isSupported", + "isSync", + "isTextEdit", + "isTexture", + "isTransformFeedback", + "isTrusted", + "isTypeSupported", + "isUserVerifyingPlatformAuthenticatorAvailable", + "isVertexArray", + "isView", + "isVisible", + "isochronousTransferIn", + "isochronousTransferOut", + "isolation", + "italics", + "item", + "itemId", + "itemProp", + "itemRef", + "itemScope", + "itemType", + "itemValue", + "items", + "iterateNext", + "iterationComposite", + "iterator", + "javaEnabled", + "jobTitle", + "join", + "json", + "justify-content", + "justify-items", + "justify-self", + "justifyContent", + "justifyItems", + "justifySelf", + "k1", + "k2", + "k3", + "k4", + "kHz", + "keepalive", + "kernelMatrix", + "kernelUnitLengthX", + "kernelUnitLengthY", + "kerning", + "key", + "keyCode", + "keyFor", + "keyIdentifier", + "keyLightEnabled", + "keyLocation", + "keyPath", + "keyStatuses", + "keySystem", + "keyText", + "keyUsage", + "keyboard", + "keys", + "keytype", + "kind", + "knee", + "label", + "labels", + "lang", + "language", + "languages", + "largeArcFlag", + "lastChild", + "lastElementChild", + "lastEventId", + "lastIndex", + "lastIndexOf", + "lastInputTime", + "lastMatch", + "lastMessageSubject", + "lastMessageType", + "lastModified", + "lastModifiedDate", + "lastPage", + "lastParen", + "lastState", + "lastStyleSheetSet", + "latitude", + "layerX", + "layerY", + "layoutFlow", + "layoutGrid", + "layoutGridChar", + "layoutGridLine", + "layoutGridMode", + "layoutGridType", + "lbound", + "left", + "leftContext", + "leftDegrees", + "leftMargin", + "leftProjectionMatrix", + "leftViewMatrix", + "length", + "lengthAdjust", + "lengthComputable", + "letter-spacing", + "letterSpacing", + "level", + "lighting-color", + "lightingColor", + "limitingConeAngle", + "line", + "line-break", + "line-height", + "lineAlign", + "lineBreak", + "lineCap", + "lineDashOffset", + "lineHeight", + "lineJoin", + "lineNumber", + "lineTo", + "lineWidth", + "linearAcceleration", + "linearRampToValueAtTime", + "linearVelocity", + "lineno", + "lines", + "link", + "linkColor", + "linkProgram", + "links", + "list", + "list-style", + "list-style-image", + "list-style-position", + "list-style-type", + "listStyle", + "listStyleImage", + "listStylePosition", + "listStyleType", + "listener", + "load", + "loadEventEnd", + "loadEventStart", + "loadTime", + "loadTimes", + "loaded", + "loading", + "localDescription", + "localName", + "localService", + "localStorage", + "locale", + "localeCompare", + "location", + "locationbar", + "lock", + "locked", + "lockedFile", + "locks", + "log", + "log10", + "log1p", + "log2", + "logicalXDPI", + "logicalYDPI", + "longDesc", + "longitude", + "lookupNamespaceURI", + "lookupPrefix", + "loop", + "loopEnd", + "loopStart", + "looping", + "low", + "lower", + "lowerBound", + "lowerOpen", + "lowsrc", + "m11", + "m12", + "m13", + "m14", + "m21", + "m22", + "m23", + "m24", + "m31", + "m32", + "m33", + "m34", + "m41", + "m42", + "m43", + "m44", + "makeXRCompatible", + "manifest", + "manufacturer", + "manufacturerName", + "map", + "mapping", + "margin", + "margin-block", + "margin-block-end", + "margin-block-start", + "margin-bottom", + "margin-inline", + "margin-inline-end", + "margin-inline-start", + "margin-left", + "margin-right", + "margin-top", + "marginBlock", + "marginBlockEnd", + "marginBlockStart", + "marginBottom", + "marginHeight", + "marginInline", + "marginInlineEnd", + "marginInlineStart", + "marginLeft", + "marginRight", + "marginTop", + "marginWidth", + "mark", + "marker", + "marker-end", + "marker-mid", + "marker-offset", + "marker-start", + "markerEnd", + "markerHeight", + "markerMid", + "markerOffset", + "markerStart", + "markerUnits", + "markerWidth", + "marks", + "mask", + "mask-clip", + "mask-composite", + "mask-image", + "mask-mode", + "mask-origin", + "mask-position", + "mask-position-x", + "mask-position-y", + "mask-repeat", + "mask-size", + "mask-type", + "maskClip", + "maskComposite", + "maskContentUnits", + "maskImage", + "maskMode", + "maskOrigin", + "maskPosition", + "maskPositionX", + "maskPositionY", + "maskRepeat", + "maskSize", + "maskType", + "maskUnits", + "match", + "matchAll", + "matchMedia", + "matchMedium", + "matches", + "matrix", + "matrixTransform", + "max", + "max-block-size", + "max-height", + "max-inline-size", + "max-width", + "maxActions", + "maxAlternatives", + "maxBlockSize", + "maxChannelCount", + "maxChannels", + "maxConnectionsPerServer", + "maxDecibels", + "maxDistance", + "maxHeight", + "maxInlineSize", + "maxLayers", + "maxLength", + "maxMessageSize", + "maxPacketLifeTime", + "maxRetransmits", + "maxTouchPoints", + "maxValue", + "maxWidth", + "measure", + "measureText", + "media", + "mediaCapabilities", + "mediaDevices", + "mediaElement", + "mediaGroup", + "mediaKeys", + "mediaSession", + "mediaStream", + "mediaText", + "meetOrSlice", + "memory", + "menubar", + "mergeAttributes", + "message", + "messageClass", + "messageHandlers", + "messageType", + "metaKey", + "metadata", + "method", + "methodDetails", + "methodName", + "mid", + "mimeType", + "mimeTypes", + "min", + "min-block-size", + "min-height", + "min-inline-size", + "min-width", + "minBlockSize", + "minDecibels", + "minHeight", + "minInlineSize", + "minLength", + "minValue", + "minWidth", + "miterLimit", + "mix-blend-mode", + "mixBlendMode", + "mm", + "mode", + "modify", + "mount", + "move", + "moveBy", + "moveEnd", + "moveFirst", + "moveFocusDown", + "moveFocusLeft", + "moveFocusRight", + "moveFocusUp", + "moveNext", + "moveRow", + "moveStart", + "moveTo", + "moveToBookmark", + "moveToElementText", + "moveToPoint", + "movementX", + "movementY", + "mozAdd", + "mozAnimationStartTime", + "mozAnon", + "mozApps", + "mozAudioCaptured", + "mozAudioChannelType", + "mozAutoplayEnabled", + "mozCancelAnimationFrame", + "mozCancelFullScreen", + "mozCancelRequestAnimationFrame", + "mozCaptureStream", + "mozCaptureStreamUntilEnded", + "mozClearDataAt", + "mozContact", + "mozContacts", + "mozCreateFileHandle", + "mozCurrentTransform", + "mozCurrentTransformInverse", + "mozCursor", + "mozDash", + "mozDashOffset", + "mozDecodedFrames", + "mozExitPointerLock", + "mozFillRule", + "mozFragmentEnd", + "mozFrameDelay", + "mozFullScreen", + "mozFullScreenElement", + "mozFullScreenEnabled", + "mozGetAll", + "mozGetAllKeys", + "mozGetAsFile", + "mozGetDataAt", + "mozGetMetadata", + "mozGetUserMedia", + "mozHasAudio", + "mozHasItem", + "mozHidden", + "mozImageSmoothingEnabled", + "mozIndexedDB", + "mozInnerScreenX", + "mozInnerScreenY", + "mozInputSource", + "mozIsTextField", + "mozItem", + "mozItemCount", + "mozItems", + "mozLength", + "mozLockOrientation", + "mozMatchesSelector", + "mozMovementX", + "mozMovementY", + "mozOpaque", + "mozOrientation", + "mozPaintCount", + "mozPaintedFrames", + "mozParsedFrames", + "mozPay", + "mozPointerLockElement", + "mozPresentedFrames", + "mozPreservesPitch", + "mozPressure", + "mozPrintCallback", + "mozRTCIceCandidate", + "mozRTCPeerConnection", + "mozRTCSessionDescription", + "mozRemove", + "mozRequestAnimationFrame", + "mozRequestFullScreen", + "mozRequestPointerLock", + "mozSetDataAt", + "mozSetImageElement", + "mozSourceNode", + "mozSrcObject", + "mozSystem", + "mozTCPSocket", + "mozTextStyle", + "mozTypesAt", + "mozUnlockOrientation", + "mozUserCancelled", + "mozVisibilityState", + "ms", + "msAnimation", + "msAnimationDelay", + "msAnimationDirection", + "msAnimationDuration", + "msAnimationFillMode", + "msAnimationIterationCount", + "msAnimationName", + "msAnimationPlayState", + "msAnimationStartTime", + "msAnimationTimingFunction", + "msBackfaceVisibility", + "msBlockProgression", + "msCSSOMElementFloatMetrics", + "msCaching", + "msCachingEnabled", + "msCancelRequestAnimationFrame", + "msCapsLockWarningOff", + "msClearImmediate", + "msClose", + "msContentZoomChaining", + "msContentZoomFactor", + "msContentZoomLimit", + "msContentZoomLimitMax", + "msContentZoomLimitMin", + "msContentZoomSnap", + "msContentZoomSnapPoints", + "msContentZoomSnapType", + "msContentZooming", + "msConvertURL", + "msCrypto", + "msDoNotTrack", + "msElementsFromPoint", + "msElementsFromRect", + "msExitFullscreen", + "msExtendedCode", + "msFillRule", + "msFirstPaint", + "msFlex", + "msFlexAlign", + "msFlexDirection", + "msFlexFlow", + "msFlexItemAlign", + "msFlexLinePack", + "msFlexNegative", + "msFlexOrder", + "msFlexPack", + "msFlexPositive", + "msFlexPreferredSize", + "msFlexWrap", + "msFlowFrom", + "msFlowInto", + "msFontFeatureSettings", + "msFullscreenElement", + "msFullscreenEnabled", + "msGetInputContext", + "msGetRegionContent", + "msGetUntransformedBounds", + "msGraphicsTrustStatus", + "msGridColumn", + "msGridColumnAlign", + "msGridColumnSpan", + "msGridColumns", + "msGridRow", + "msGridRowAlign", + "msGridRowSpan", + "msGridRows", + "msHidden", + "msHighContrastAdjust", + "msHyphenateLimitChars", + "msHyphenateLimitLines", + "msHyphenateLimitZone", + "msHyphens", + "msImageSmoothingEnabled", + "msImeAlign", + "msIndexedDB", + "msInterpolationMode", + "msIsStaticHTML", + "msKeySystem", + "msKeys", + "msLaunchUri", + "msLockOrientation", + "msManipulationViewsEnabled", + "msMatchMedia", + "msMatchesSelector", + "msMaxTouchPoints", + "msOrientation", + "msOverflowStyle", + "msPerspective", + "msPerspectiveOrigin", + "msPlayToDisabled", + "msPlayToPreferredSourceUri", + "msPlayToPrimary", + "msPointerEnabled", + "msRegionOverflow", + "msReleasePointerCapture", + "msRequestAnimationFrame", + "msRequestFullscreen", + "msSaveBlob", + "msSaveOrOpenBlob", + "msScrollChaining", + "msScrollLimit", + "msScrollLimitXMax", + "msScrollLimitXMin", + "msScrollLimitYMax", + "msScrollLimitYMin", + "msScrollRails", + "msScrollSnapPointsX", + "msScrollSnapPointsY", + "msScrollSnapType", + "msScrollSnapX", + "msScrollSnapY", + "msScrollTranslation", + "msSetImmediate", + "msSetMediaKeys", + "msSetPointerCapture", + "msTextCombineHorizontal", + "msTextSizeAdjust", + "msToBlob", + "msTouchAction", + "msTouchSelect", + "msTraceAsyncCallbackCompleted", + "msTraceAsyncCallbackStarting", + "msTraceAsyncOperationCompleted", + "msTraceAsyncOperationStarting", + "msTransform", + "msTransformOrigin", + "msTransformStyle", + "msTransition", + "msTransitionDelay", + "msTransitionDuration", + "msTransitionProperty", + "msTransitionTimingFunction", + "msUnlockOrientation", + "msUpdateAsyncCallbackRelation", + "msUserSelect", + "msVisibilityState", + "msWrapFlow", + "msWrapMargin", + "msWrapThrough", + "msWriteProfilerMark", + "msZoom", + "msZoomTo", + "mt", + "mul", + "multiEntry", + "multiSelectionObj", + "multiline", + "multiple", + "multiply", + "multiplySelf", + "mutableFile", + "muted", + "n", + "name", + "nameProp", + "namedItem", + "namedRecordset", + "names", + "namespaceURI", + "namespaces", + "naturalHeight", + "naturalWidth", + "navigate", + "navigation", + "navigationMode", + "navigationPreload", + "navigationStart", + "navigator", + "near", + "nearestViewportElement", + "negative", + "negotiated", + "netscape", + "networkState", + "newScale", + "newTranslate", + "newURL", + "newValue", + "newValueSpecifiedUnits", + "newVersion", + "newhome", + "next", + "nextElementSibling", + "nextHopProtocol", + "nextNode", + "nextPage", + "nextSibling", + "nickname", + "noHref", + "noModule", + "noResize", + "noShade", + "noValidate", + "noWrap", + "node", + "nodeName", + "nodeType", + "nodeValue", + "nonce", + "normalize", + "normalizedPathSegList", + "notationName", + "notations", + "note", + "noteGrainOn", + "noteOff", + "noteOn", + "notify", + "now", + "numOctaves", + "number", + "numberOfChannels", + "numberOfInputs", + "numberOfItems", + "numberOfOutputs", + "numberValue", + "oMatchesSelector", + "object", + "object-fit", + "object-position", + "objectFit", + "objectPosition", + "objectStore", + "objectStoreNames", + "objectType", + "observe", + "of", + "offscreenBuffering", + "offset", + "offset-anchor", + "offset-distance", + "offset-path", + "offset-rotate", + "offsetAnchor", + "offsetDistance", + "offsetHeight", + "offsetLeft", + "offsetNode", + "offsetParent", + "offsetPath", + "offsetRotate", + "offsetTop", + "offsetWidth", + "offsetX", + "offsetY", + "ok", + "oldURL", + "oldValue", + "oldVersion", + "olderShadowRoot", + "onLine", + "onabort", + "onabsolutedeviceorientation", + "onactivate", + "onactive", + "onaddsourcebuffer", + "onaddstream", + "onaddtrack", + "onafterprint", + "onafterscriptexecute", + "onafterupdate", + "onanimationcancel", + "onanimationend", + "onanimationiteration", + "onanimationstart", + "onappinstalled", + "onaudioend", + "onaudioprocess", + "onaudiostart", + "onautocomplete", + "onautocompleteerror", + "onauxclick", + "onbeforeactivate", + "onbeforecopy", + "onbeforecut", + "onbeforedeactivate", + "onbeforeeditfocus", + "onbeforeinstallprompt", + "onbeforepaste", + "onbeforeprint", + "onbeforescriptexecute", + "onbeforeunload", + "onbeforeupdate", + "onbeforexrselect", + "onbegin", + "onblocked", + "onblur", + "onbounce", + "onboundary", + "onbufferedamountlow", + "oncached", + "oncancel", + "oncandidatewindowhide", + "oncandidatewindowshow", + "oncandidatewindowupdate", + "oncanplay", + "oncanplaythrough", + "once", + "oncellchange", + "onchange", + "oncharacteristicvaluechanged", + "onchargingchange", + "onchargingtimechange", + "onchecking", + "onclick", + "onclose", + "onclosing", + "oncompassneedscalibration", + "oncomplete", + "onconnect", + "onconnecting", + "onconnectionavailable", + "onconnectionstatechange", + "oncontextmenu", + "oncontrollerchange", + "oncontrolselect", + "oncopy", + "oncuechange", + "oncut", + "ondataavailable", + "ondatachannel", + "ondatasetchanged", + "ondatasetcomplete", + "ondblclick", + "ondeactivate", + "ondevicechange", + "ondevicelight", + "ondevicemotion", + "ondeviceorientation", + "ondeviceorientationabsolute", + "ondeviceproximity", + "ondischargingtimechange", + "ondisconnect", + "ondisplay", + "ondownloading", + "ondrag", + "ondragend", + "ondragenter", + "ondragexit", + "ondragleave", + "ondragover", + "ondragstart", + "ondrop", + "ondurationchange", + "onemptied", + "onencrypted", + "onend", + "onended", + "onenter", + "onenterpictureinpicture", + "onerror", + "onerrorupdate", + "onexit", + "onfilterchange", + "onfinish", + "onfocus", + "onfocusin", + "onfocusout", + "onformdata", + "onfreeze", + "onfullscreenchange", + "onfullscreenerror", + "ongatheringstatechange", + "ongattserverdisconnected", + "ongesturechange", + "ongestureend", + "ongesturestart", + "ongotpointercapture", + "onhashchange", + "onhelp", + "onicecandidate", + "onicecandidateerror", + "oniceconnectionstatechange", + "onicegatheringstatechange", + "oninactive", + "oninput", + "oninputsourceschange", + "oninvalid", + "onkeydown", + "onkeypress", + "onkeystatuseschange", + "onkeyup", + "onlanguagechange", + "onlayoutcomplete", + "onleavepictureinpicture", + "onlevelchange", + "onload", + "onloadeddata", + "onloadedmetadata", + "onloadend", + "onloading", + "onloadingdone", + "onloadingerror", + "onloadstart", + "onlosecapture", + "onlostpointercapture", + "only", + "onmark", + "onmessage", + "onmessageerror", + "onmidimessage", + "onmousedown", + "onmouseenter", + "onmouseleave", + "onmousemove", + "onmouseout", + "onmouseover", + "onmouseup", + "onmousewheel", + "onmove", + "onmoveend", + "onmovestart", + "onmozfullscreenchange", + "onmozfullscreenerror", + "onmozorientationchange", + "onmozpointerlockchange", + "onmozpointerlockerror", + "onmscontentzoom", + "onmsfullscreenchange", + "onmsfullscreenerror", + "onmsgesturechange", + "onmsgesturedoubletap", + "onmsgestureend", + "onmsgesturehold", + "onmsgesturestart", + "onmsgesturetap", + "onmsgotpointercapture", + "onmsinertiastart", + "onmslostpointercapture", + "onmsmanipulationstatechanged", + "onmsneedkey", + "onmsorientationchange", + "onmspointercancel", + "onmspointerdown", + "onmspointerenter", + "onmspointerhover", + "onmspointerleave", + "onmspointermove", + "onmspointerout", + "onmspointerover", + "onmspointerup", + "onmssitemodejumplistitemremoved", + "onmsthumbnailclick", + "onmute", + "onnegotiationneeded", + "onnomatch", + "onnoupdate", + "onobsolete", + "onoffline", + "ononline", + "onopen", + "onorientationchange", + "onpagechange", + "onpagehide", + "onpageshow", + "onpaste", + "onpause", + "onpayerdetailchange", + "onpaymentmethodchange", + "onplay", + "onplaying", + "onpluginstreamstart", + "onpointercancel", + "onpointerdown", + "onpointerenter", + "onpointerleave", + "onpointerlockchange", + "onpointerlockerror", + "onpointermove", + "onpointerout", + "onpointerover", + "onpointerrawupdate", + "onpointerup", + "onpopstate", + "onprocessorerror", + "onprogress", + "onpropertychange", + "onratechange", + "onreading", + "onreadystatechange", + "onrejectionhandled", + "onrelease", + "onremove", + "onremovesourcebuffer", + "onremovestream", + "onremovetrack", + "onrepeat", + "onreset", + "onresize", + "onresizeend", + "onresizestart", + "onresourcetimingbufferfull", + "onresult", + "onresume", + "onrowenter", + "onrowexit", + "onrowsdelete", + "onrowsinserted", + "onscroll", + "onsearch", + "onsecuritypolicyviolation", + "onseeked", + "onseeking", + "onselect", + "onselectedcandidatepairchange", + "onselectend", + "onselectionchange", + "onselectstart", + "onshippingaddresschange", + "onshippingoptionchange", + "onshow", + "onsignalingstatechange", + "onsoundend", + "onsoundstart", + "onsourceclose", + "onsourceclosed", + "onsourceended", + "onsourceopen", + "onspeechend", + "onspeechstart", + "onsqueeze", + "onsqueezeend", + "onsqueezestart", + "onstalled", + "onstart", + "onstatechange", + "onstop", + "onstorage", + "onstoragecommit", + "onsubmit", + "onsuccess", + "onsuspend", + "onterminate", + "ontextinput", + "ontimeout", + "ontimeupdate", + "ontoggle", + "ontonechange", + "ontouchcancel", + "ontouchend", + "ontouchmove", + "ontouchstart", + "ontrack", + "ontransitioncancel", + "ontransitionend", + "ontransitionrun", + "ontransitionstart", + "onunhandledrejection", + "onunload", + "onunmute", + "onupdate", + "onupdateend", + "onupdatefound", + "onupdateready", + "onupdatestart", + "onupgradeneeded", + "onuserproximity", + "onversionchange", + "onvisibilitychange", + "onvoiceschanged", + "onvolumechange", + "onvrdisplayactivate", + "onvrdisplayconnect", + "onvrdisplaydeactivate", + "onvrdisplaydisconnect", + "onvrdisplaypresentchange", + "onwaiting", + "onwaitingforkey", + "onwarning", + "onwebkitanimationend", + "onwebkitanimationiteration", + "onwebkitanimationstart", + "onwebkitcurrentplaybacktargetiswirelesschanged", + "onwebkitfullscreenchange", + "onwebkitfullscreenerror", + "onwebkitkeyadded", + "onwebkitkeyerror", + "onwebkitkeymessage", + "onwebkitneedkey", + "onwebkitorientationchange", + "onwebkitplaybacktargetavailabilitychanged", + "onwebkitpointerlockchange", + "onwebkitpointerlockerror", + "onwebkitresourcetimingbufferfull", + "onwebkittransitionend", + "onwheel", + "onzoom", + "opacity", + "open", + "openCursor", + "openDatabase", + "openKeyCursor", + "opened", + "opener", + "opera", + "operationType", + "operator", + "opr", + "optimum", + "options", + "or", + "order", + "orderX", + "orderY", + "ordered", + "org", + "organization", + "orient", + "orientAngle", + "orientType", + "orientation", + "orientationX", + "orientationY", + "orientationZ", + "origin", + "originalPolicy", + "originalTarget", + "orphans", + "oscpu", + "outerHTML", + "outerHeight", + "outerText", + "outerWidth", + "outline", + "outline-color", + "outline-offset", + "outline-style", + "outline-width", + "outlineColor", + "outlineOffset", + "outlineStyle", + "outlineWidth", + "outputBuffer", + "outputLatency", + "outputs", + "overflow", + "overflow-anchor", + "overflow-block", + "overflow-inline", + "overflow-wrap", + "overflow-x", + "overflow-y", + "overflowAnchor", + "overflowBlock", + "overflowInline", + "overflowWrap", + "overflowX", + "overflowY", + "overrideMimeType", + "oversample", + "overscroll-behavior", + "overscroll-behavior-block", + "overscroll-behavior-inline", + "overscroll-behavior-x", + "overscroll-behavior-y", + "overscrollBehavior", + "overscrollBehaviorBlock", + "overscrollBehaviorInline", + "overscrollBehaviorX", + "overscrollBehaviorY", + "ownKeys", + "ownerDocument", + "ownerElement", + "ownerNode", + "ownerRule", + "ownerSVGElement", + "owningElement", + "p1", + "p2", + "p3", + "p4", + "packetSize", + "packets", + "pad", + "padEnd", + "padStart", + "padding", + "padding-block", + "padding-block-end", + "padding-block-start", + "padding-bottom", + "padding-inline", + "padding-inline-end", + "padding-inline-start", + "padding-left", + "padding-right", + "padding-top", + "paddingBlock", + "paddingBlockEnd", + "paddingBlockStart", + "paddingBottom", + "paddingInline", + "paddingInlineEnd", + "paddingInlineStart", + "paddingLeft", + "paddingRight", + "paddingTop", + "page", + "page-break-after", + "page-break-before", + "page-break-inside", + "pageBreakAfter", + "pageBreakBefore", + "pageBreakInside", + "pageCount", + "pageLeft", + "pageTop", + "pageX", + "pageXOffset", + "pageY", + "pageYOffset", + "pages", + "paint-order", + "paintOrder", + "paintRequests", + "paintType", + "paintWorklet", + "palette", + "pan", + "panningModel", + "parameters", + "parent", + "parentElement", + "parentNode", + "parentRule", + "parentStyleSheet", + "parentTextEdit", + "parentWindow", + "parse", + "parseAll", + "parseFloat", + "parseFromString", + "parseInt", + "part", + "participants", + "passive", + "password", + "pasteHTML", + "path", + "pathLength", + "pathSegList", + "pathSegType", + "pathSegTypeAsLetter", + "pathname", + "pattern", + "patternContentUnits", + "patternMismatch", + "patternTransform", + "patternUnits", + "pause", + "pauseAnimations", + "pauseOnExit", + "pauseProfilers", + "pauseTransformFeedback", + "paused", + "payerEmail", + "payerName", + "payerPhone", + "paymentManager", + "pc", + "peerIdentity", + "pending", + "pendingLocalDescription", + "pendingRemoteDescription", + "percent", + "performance", + "periodicSync", + "permission", + "permissionState", + "permissions", + "persist", + "persisted", + "personalbar", + "perspective", + "perspective-origin", + "perspectiveOrigin", + "phone", + "phoneticFamilyName", + "phoneticGivenName", + "photo", + "pictureInPictureElement", + "pictureInPictureEnabled", + "pictureInPictureWindow", + "ping", + "pipeThrough", + "pipeTo", + "pitch", + "pixelBottom", + "pixelDepth", + "pixelHeight", + "pixelLeft", + "pixelRight", + "pixelStorei", + "pixelTop", + "pixelUnitToMillimeterX", + "pixelUnitToMillimeterY", + "pixelWidth", + "place-content", + "place-items", + "place-self", + "placeContent", + "placeItems", + "placeSelf", + "placeholder", + "platform", + "platforms", + "play", + "playEffect", + "playState", + "playbackRate", + "playbackState", + "playbackTime", + "played", + "playoutDelayHint", + "playsInline", + "plugins", + "pluginspage", + "pname", + "pointer-events", + "pointerBeforeReferenceNode", + "pointerEnabled", + "pointerEvents", + "pointerId", + "pointerLockElement", + "pointerType", + "points", + "pointsAtX", + "pointsAtY", + "pointsAtZ", + "polygonOffset", + "pop", + "populateMatrix", + "popupWindowFeatures", + "popupWindowName", + "popupWindowURI", + "port", + "port1", + "port2", + "ports", + "posBottom", + "posHeight", + "posLeft", + "posRight", + "posTop", + "posWidth", + "pose", + "position", + "positionAlign", + "positionX", + "positionY", + "positionZ", + "postError", + "postMessage", + "postalCode", + "poster", + "pow", + "powerEfficient", + "powerOff", + "preMultiplySelf", + "precision", + "preferredStyleSheetSet", + "preferredStylesheetSet", + "prefix", + "preload", + "prepend", + "presentation", + "preserveAlpha", + "preserveAspectRatio", + "preserveAspectRatioString", + "pressed", + "pressure", + "prevValue", + "preventDefault", + "preventExtensions", + "preventSilentAccess", + "previousElementSibling", + "previousNode", + "previousPage", + "previousRect", + "previousScale", + "previousSibling", + "previousTranslate", + "primaryKey", + "primitiveType", + "primitiveUnits", + "principals", + "print", + "priority", + "privateKey", + "probablySupportsContext", + "process", + "processIceMessage", + "processingEnd", + "processingStart", + "product", + "productId", + "productName", + "productSub", + "profile", + "profileEnd", + "profiles", + "projectionMatrix", + "promise", + "prompt", + "properties", + "propertyIsEnumerable", + "propertyName", + "protocol", + "protocolLong", + "prototype", + "provider", + "pseudoClass", + "pseudoElement", + "pt", + "publicId", + "publicKey", + "published", + "pulse", + "push", + "pushManager", + "pushNotification", + "pushState", + "put", + "putImageData", + "px", + "quadraticCurveTo", + "qualifier", + "quaternion", + "query", + "queryCommandEnabled", + "queryCommandIndeterm", + "queryCommandState", + "queryCommandSupported", + "queryCommandText", + "queryCommandValue", + "querySelector", + "querySelectorAll", + "queueMicrotask", + "quote", + "quotes", + "r", + "r1", + "r2", + "race", + "rad", + "radiogroup", + "radiusX", + "radiusY", + "random", + "range", + "rangeCount", + "rangeMax", + "rangeMin", + "rangeOffset", + "rangeOverflow", + "rangeParent", + "rangeUnderflow", + "rate", + "ratio", + "raw", + "rawId", + "read", + "readAsArrayBuffer", + "readAsBinaryString", + "readAsBlob", + "readAsDataURL", + "readAsText", + "readBuffer", + "readEntries", + "readOnly", + "readPixels", + "readReportRequested", + "readText", + "readValue", + "readable", + "ready", + "readyState", + "reason", + "reboot", + "receivedAlert", + "receiver", + "receivers", + "recipient", + "reconnect", + "recordNumber", + "recordsAvailable", + "recordset", + "rect", + "red", + "redEyeReduction", + "redirect", + "redirectCount", + "redirectEnd", + "redirectStart", + "redirected", + "reduce", + "reduceRight", + "reduction", + "refDistance", + "refX", + "refY", + "referenceNode", + "referenceSpace", + "referrer", + "referrerPolicy", + "refresh", + "region", + "regionAnchorX", + "regionAnchorY", + "regionId", + "regions", + "register", + "registerContentHandler", + "registerElement", + "registerProperty", + "registerProtocolHandler", + "reject", + "rel", + "relList", + "relatedAddress", + "relatedNode", + "relatedPort", + "relatedTarget", + "release", + "releaseCapture", + "releaseEvents", + "releaseInterface", + "releaseLock", + "releasePointerCapture", + "releaseShaderCompiler", + "reliable", + "reliableWrite", + "reload", + "rem", + "remainingSpace", + "remote", + "remoteDescription", + "remove", + "removeAllRanges", + "removeAttribute", + "removeAttributeNS", + "removeAttributeNode", + "removeBehavior", + "removeChild", + "removeCue", + "removeEventListener", + "removeFilter", + "removeImport", + "removeItem", + "removeListener", + "removeNamedItem", + "removeNamedItemNS", + "removeNode", + "removeParameter", + "removeProperty", + "removeRange", + "removeRegion", + "removeRule", + "removeSiteSpecificTrackingException", + "removeSourceBuffer", + "removeStream", + "removeTrack", + "removeVariable", + "removeWakeLockListener", + "removeWebWideTrackingException", + "removed", + "removedNodes", + "renderHeight", + "renderState", + "renderTime", + "renderWidth", + "renderbufferStorage", + "renderbufferStorageMultisample", + "renderedBuffer", + "renderingMode", + "renotify", + "repeat", + "replace", + "replaceAdjacentText", + "replaceAll", + "replaceChild", + "replaceChildren", + "replaceData", + "replaceId", + "replaceItem", + "replaceNode", + "replaceState", + "replaceSync", + "replaceTrack", + "replaceWholeText", + "replaceWith", + "reportValidity", + "request", + "requestAnimationFrame", + "requestAutocomplete", + "requestData", + "requestDevice", + "requestFrame", + "requestFullscreen", + "requestHitTestSource", + "requestHitTestSourceForTransientInput", + "requestId", + "requestIdleCallback", + "requestMIDIAccess", + "requestMediaKeySystemAccess", + "requestPermission", + "requestPictureInPicture", + "requestPointerLock", + "requestPresent", + "requestReferenceSpace", + "requestSession", + "requestStart", + "requestStorageAccess", + "requestSubmit", + "requestVideoFrameCallback", + "requestingWindow", + "requireInteraction", + "required", + "requiredExtensions", + "requiredFeatures", + "reset", + "resetPose", + "resetTransform", + "resize", + "resizeBy", + "resizeTo", + "resolve", + "response", + "responseBody", + "responseEnd", + "responseReady", + "responseStart", + "responseText", + "responseType", + "responseURL", + "responseXML", + "restartIce", + "restore", + "result", + "resultIndex", + "resultType", + "results", + "resume", + "resumeProfilers", + "resumeTransformFeedback", + "retry", + "returnValue", + "rev", + "reverse", + "reversed", + "revocable", + "revokeObjectURL", + "rgbColor", + "right", + "rightContext", + "rightDegrees", + "rightMargin", + "rightProjectionMatrix", + "rightViewMatrix", + "role", + "rolloffFactor", + "root", + "rootBounds", + "rootElement", + "rootMargin", + "rotate", + "rotateAxisAngle", + "rotateAxisAngleSelf", + "rotateFromVector", + "rotateFromVectorSelf", + "rotateSelf", + "rotation", + "rotationAngle", + "rotationRate", + "round", + "row-gap", + "rowGap", + "rowIndex", + "rowSpan", + "rows", + "rtcpTransport", + "rtt", + "ruby-align", + "ruby-position", + "rubyAlign", + "rubyOverhang", + "rubyPosition", + "rules", + "runtime", + "runtimeStyle", + "rx", + "ry", + "s", + "safari", + "sample", + "sampleCoverage", + "sampleRate", + "samplerParameterf", + "samplerParameteri", + "sandbox", + "save", + "saveData", + "scale", + "scale3d", + "scale3dSelf", + "scaleNonUniform", + "scaleNonUniformSelf", + "scaleSelf", + "scheme", + "scissor", + "scope", + "scopeName", + "scoped", + "screen", + "screenBrightness", + "screenEnabled", + "screenLeft", + "screenPixelToMillimeterX", + "screenPixelToMillimeterY", + "screenTop", + "screenX", + "screenY", + "scriptURL", + "scripts", + "scroll", + "scroll-behavior", + "scroll-margin", + "scroll-margin-block", + "scroll-margin-block-end", + "scroll-margin-block-start", + "scroll-margin-bottom", + "scroll-margin-inline", + "scroll-margin-inline-end", + "scroll-margin-inline-start", + "scroll-margin-left", + "scroll-margin-right", + "scroll-margin-top", + "scroll-padding", + "scroll-padding-block", + "scroll-padding-block-end", + "scroll-padding-block-start", + "scroll-padding-bottom", + "scroll-padding-inline", + "scroll-padding-inline-end", + "scroll-padding-inline-start", + "scroll-padding-left", + "scroll-padding-right", + "scroll-padding-top", + "scroll-snap-align", + "scroll-snap-type", + "scrollAmount", + "scrollBehavior", + "scrollBy", + "scrollByLines", + "scrollByPages", + "scrollDelay", + "scrollHeight", + "scrollIntoView", + "scrollIntoViewIfNeeded", + "scrollLeft", + "scrollLeftMax", + "scrollMargin", + "scrollMarginBlock", + "scrollMarginBlockEnd", + "scrollMarginBlockStart", + "scrollMarginBottom", + "scrollMarginInline", + "scrollMarginInlineEnd", + "scrollMarginInlineStart", + "scrollMarginLeft", + "scrollMarginRight", + "scrollMarginTop", + "scrollMaxX", + "scrollMaxY", + "scrollPadding", + "scrollPaddingBlock", + "scrollPaddingBlockEnd", + "scrollPaddingBlockStart", + "scrollPaddingBottom", + "scrollPaddingInline", + "scrollPaddingInlineEnd", + "scrollPaddingInlineStart", + "scrollPaddingLeft", + "scrollPaddingRight", + "scrollPaddingTop", + "scrollRestoration", + "scrollSnapAlign", + "scrollSnapType", + "scrollTo", + "scrollTop", + "scrollTopMax", + "scrollWidth", + "scrollX", + "scrollY", + "scrollbar-color", + "scrollbar-width", + "scrollbar3dLightColor", + "scrollbarArrowColor", + "scrollbarBaseColor", + "scrollbarColor", + "scrollbarDarkShadowColor", + "scrollbarFaceColor", + "scrollbarHighlightColor", + "scrollbarShadowColor", + "scrollbarTrackColor", + "scrollbarWidth", + "scrollbars", + "scrolling", + "scrollingElement", + "sctp", + "sctpCauseCode", + "sdp", + "sdpLineNumber", + "sdpMLineIndex", + "sdpMid", + "seal", + "search", + "searchBox", + "searchBoxJavaBridge_", + "searchParams", + "sectionRowIndex", + "secureConnectionStart", + "security", + "seed", + "seekToNextFrame", + "seekable", + "seeking", + "select", + "selectAllChildren", + "selectAlternateInterface", + "selectConfiguration", + "selectNode", + "selectNodeContents", + "selectNodes", + "selectSingleNode", + "selectSubString", + "selected", + "selectedIndex", + "selectedOptions", + "selectedStyleSheetSet", + "selectedStylesheetSet", + "selection", + "selectionDirection", + "selectionEnd", + "selectionStart", + "selector", + "selectorText", + "self", + "send", + "sendAsBinary", + "sendBeacon", + "sender", + "sentAlert", + "sentTimestamp", + "separator", + "serialNumber", + "serializeToString", + "serverTiming", + "service", + "serviceWorker", + "session", + "sessionId", + "sessionStorage", + "set", + "setActionHandler", + "setActive", + "setAlpha", + "setAppBadge", + "setAttribute", + "setAttributeNS", + "setAttributeNode", + "setAttributeNodeNS", + "setBaseAndExtent", + "setBigInt64", + "setBigUint64", + "setBingCurrentSearchDefault", + "setCapture", + "setCodecPreferences", + "setColor", + "setCompositeOperation", + "setConfiguration", + "setCurrentTime", + "setCustomValidity", + "setData", + "setDate", + "setDragImage", + "setEnd", + "setEndAfter", + "setEndBefore", + "setEndPoint", + "setFillColor", + "setFilterRes", + "setFloat32", + "setFloat64", + "setFloatValue", + "setFormValue", + "setFullYear", + "setHeaderValue", + "setHours", + "setIdentityProvider", + "setImmediate", + "setInt16", + "setInt32", + "setInt8", + "setInterval", + "setItem", + "setKeyframes", + "setLineCap", + "setLineDash", + "setLineJoin", + "setLineWidth", + "setLiveSeekableRange", + "setLocalDescription", + "setMatrix", + "setMatrixValue", + "setMediaKeys", + "setMilliseconds", + "setMinutes", + "setMiterLimit", + "setMonth", + "setNamedItem", + "setNamedItemNS", + "setNonUserCodeExceptions", + "setOrientToAngle", + "setOrientToAuto", + "setOrientation", + "setOverrideHistoryNavigationMode", + "setPaint", + "setParameter", + "setParameters", + "setPeriodicWave", + "setPointerCapture", + "setPosition", + "setPositionState", + "setPreference", + "setProperty", + "setPrototypeOf", + "setRGBColor", + "setRGBColorICCColor", + "setRadius", + "setRangeText", + "setRemoteDescription", + "setRequestHeader", + "setResizable", + "setResourceTimingBufferSize", + "setRotate", + "setScale", + "setSeconds", + "setSelectionRange", + "setServerCertificate", + "setShadow", + "setSinkId", + "setSkewX", + "setSkewY", + "setStart", + "setStartAfter", + "setStartBefore", + "setStdDeviation", + "setStreams", + "setStringValue", + "setStrokeColor", + "setSuggestResult", + "setTargetAtTime", + "setTargetValueAtTime", + "setTime", + "setTimeout", + "setTransform", + "setTranslate", + "setUTCDate", + "setUTCFullYear", + "setUTCHours", + "setUTCMilliseconds", + "setUTCMinutes", + "setUTCMonth", + "setUTCSeconds", + "setUint16", + "setUint32", + "setUint8", + "setUri", + "setValidity", + "setValueAtTime", + "setValueCurveAtTime", + "setVariable", + "setVelocity", + "setVersion", + "setYear", + "settingName", + "settingValue", + "sex", + "shaderSource", + "shadowBlur", + "shadowColor", + "shadowOffsetX", + "shadowOffsetY", + "shadowRoot", + "shape", + "shape-image-threshold", + "shape-margin", + "shape-outside", + "shape-rendering", + "shapeImageThreshold", + "shapeMargin", + "shapeOutside", + "shapeRendering", + "sheet", + "shift", + "shiftKey", + "shiftLeft", + "shippingAddress", + "shippingOption", + "shippingType", + "show", + "showHelp", + "showModal", + "showModalDialog", + "showModelessDialog", + "showNotification", + "sidebar", + "sign", + "signal", + "signalingState", + "signature", + "silent", + "sin", + "singleNodeValue", + "sinh", + "sinkId", + "sittingToStandingTransform", + "size", + "sizeToContent", + "sizeX", + "sizeZ", + "sizes", + "skewX", + "skewXSelf", + "skewY", + "skewYSelf", + "slice", + "slope", + "slot", + "small", + "smil", + "smooth", + "smoothingTimeConstant", + "snapToLines", + "snapshotItem", + "snapshotLength", + "some", + "sort", + "sortingCode", + "source", + "sourceBuffer", + "sourceBuffers", + "sourceCapabilities", + "sourceFile", + "sourceIndex", + "sources", + "spacing", + "span", + "speak", + "speakAs", + "speaking", + "species", + "specified", + "specularConstant", + "specularExponent", + "speechSynthesis", + "speed", + "speedOfSound", + "spellcheck", + "splice", + "split", + "splitText", + "spreadMethod", + "sqrt", + "src", + "srcElement", + "srcFilter", + "srcObject", + "srcUrn", + "srcdoc", + "srclang", + "srcset", + "stack", + "stackTraceLimit", + "stacktrace", + "stageParameters", + "standalone", + "standby", + "start", + "startContainer", + "startIce", + "startMessages", + "startNotifications", + "startOffset", + "startProfiling", + "startRendering", + "startShark", + "startTime", + "startsWith", + "state", + "status", + "statusCode", + "statusMessage", + "statusText", + "statusbar", + "stdDeviationX", + "stdDeviationY", + "stencilFunc", + "stencilFuncSeparate", + "stencilMask", + "stencilMaskSeparate", + "stencilOp", + "stencilOpSeparate", + "step", + "stepDown", + "stepMismatch", + "stepUp", + "sticky", + "stitchTiles", + "stop", + "stop-color", + "stop-opacity", + "stopColor", + "stopImmediatePropagation", + "stopNotifications", + "stopOpacity", + "stopProfiling", + "stopPropagation", + "stopShark", + "stopped", + "storage", + "storageArea", + "storageName", + "storageStatus", + "store", + "storeSiteSpecificTrackingException", + "storeWebWideTrackingException", + "stpVersion", + "stream", + "streams", + "stretch", + "strike", + "string", + "stringValue", + "stringify", + "stroke", + "stroke-dasharray", + "stroke-dashoffset", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-opacity", + "stroke-width", + "strokeDasharray", + "strokeDashoffset", + "strokeLinecap", + "strokeLinejoin", + "strokeMiterlimit", + "strokeOpacity", + "strokeRect", + "strokeStyle", + "strokeText", + "strokeWidth", + "style", + "styleFloat", + "styleMap", + "styleMedia", + "styleSheet", + "styleSheetSets", + "styleSheets", + "sub", + "subarray", + "subject", + "submit", + "submitFrame", + "submitter", + "subscribe", + "substr", + "substring", + "substringData", + "subtle", + "subtree", + "suffix", + "suffixes", + "summary", + "sup", + "supported", + "supportedContentEncodings", + "supportedEntryTypes", + "supports", + "supportsSession", + "surfaceScale", + "surroundContents", + "suspend", + "suspendRedraw", + "swapCache", + "swapNode", + "sweepFlag", + "symbols", + "sync", + "sysexEnabled", + "system", + "systemCode", + "systemId", + "systemLanguage", + "systemXDPI", + "systemYDPI", + "tBodies", + "tFoot", + "tHead", + "tabIndex", + "table", + "table-layout", + "tableLayout", + "tableValues", + "tag", + "tagName", + "tagUrn", + "tags", + "taintEnabled", + "takePhoto", + "takeRecords", + "tan", + "tangentialPressure", + "tanh", + "target", + "targetElement", + "targetRayMode", + "targetRaySpace", + "targetTouches", + "targetX", + "targetY", + "tcpType", + "tee", + "tel", + "terminate", + "test", + "texImage2D", + "texImage3D", + "texParameterf", + "texParameteri", + "texStorage2D", + "texStorage3D", + "texSubImage2D", + "texSubImage3D", + "text", + "text-align", + "text-align-last", + "text-anchor", + "text-combine-upright", + "text-decoration", + "text-decoration-color", + "text-decoration-line", + "text-decoration-skip-ink", + "text-decoration-style", + "text-decoration-thickness", + "text-emphasis", + "text-emphasis-color", + "text-emphasis-position", + "text-emphasis-style", + "text-indent", + "text-justify", + "text-orientation", + "text-overflow", + "text-rendering", + "text-shadow", + "text-transform", + "text-underline-offset", + "text-underline-position", + "textAlign", + "textAlignLast", + "textAnchor", + "textAutospace", + "textBaseline", + "textCombineUpright", + "textContent", + "textDecoration", + "textDecorationBlink", + "textDecorationColor", + "textDecorationLine", + "textDecorationLineThrough", + "textDecorationNone", + "textDecorationOverline", + "textDecorationSkipInk", + "textDecorationStyle", + "textDecorationThickness", + "textDecorationUnderline", + "textEmphasis", + "textEmphasisColor", + "textEmphasisPosition", + "textEmphasisStyle", + "textIndent", + "textJustify", + "textJustifyTrim", + "textKashida", + "textKashidaSpace", + "textLength", + "textOrientation", + "textOverflow", + "textRendering", + "textShadow", + "textTracks", + "textTransform", + "textUnderlineOffset", + "textUnderlinePosition", + "then", + "threadId", + "threshold", + "thresholds", + "tiltX", + "tiltY", + "time", + "timeEnd", + "timeLog", + "timeOrigin", + "timeRemaining", + "timeStamp", + "timecode", + "timeline", + "timelineTime", + "timeout", + "timestamp", + "timestampOffset", + "timing", + "title", + "to", + "toArray", + "toBlob", + "toDataURL", + "toDateString", + "toElement", + "toExponential", + "toFixed", + "toFloat32Array", + "toFloat64Array", + "toGMTString", + "toISOString", + "toJSON", + "toLocaleDateString", + "toLocaleFormat", + "toLocaleLowerCase", + "toLocaleString", + "toLocaleTimeString", + "toLocaleUpperCase", + "toLowerCase", + "toMatrix", + "toMethod", + "toPrecision", + "toPrimitive", + "toSdp", + "toSource", + "toStaticHTML", + "toString", + "toStringTag", + "toSum", + "toTimeString", + "toUTCString", + "toUpperCase", + "toggle", + "toggleAttribute", + "toggleLongPressEnabled", + "tone", + "toneBuffer", + "tooLong", + "tooShort", + "toolbar", + "top", + "topMargin", + "total", + "totalFrameDelay", + "totalVideoFrames", + "touch-action", + "touchAction", + "touched", + "touches", + "trace", + "track", + "trackVisibility", + "transaction", + "transactions", + "transceiver", + "transferControlToOffscreen", + "transferFromImageBitmap", + "transferImageBitmap", + "transferIn", + "transferOut", + "transferSize", + "transferToImageBitmap", + "transform", + "transform-box", + "transform-origin", + "transform-style", + "transformBox", + "transformFeedbackVaryings", + "transformOrigin", + "transformPoint", + "transformString", + "transformStyle", + "transformToDocument", + "transformToFragment", + "transition", + "transition-delay", + "transition-duration", + "transition-property", + "transition-timing-function", + "transitionDelay", + "transitionDuration", + "transitionProperty", + "transitionTimingFunction", + "translate", + "translateSelf", + "translationX", + "translationY", + "transport", + "trim", + "trimEnd", + "trimLeft", + "trimRight", + "trimStart", + "trueSpeed", + "trunc", + "truncate", + "trustedTypes", + "turn", + "twist", + "type", + "typeDetail", + "typeMismatch", + "typeMustMatch", + "types", + "u2f", + "ubound", + "uint16", + "uint32", + "uint8", + "uint8Clamped", + "undefined", + "unescape", + "uneval", + "unicode", + "unicode-bidi", + "unicodeBidi", + "unicodeRange", + "uniform1f", + "uniform1fv", + "uniform1i", + "uniform1iv", + "uniform1ui", + "uniform1uiv", + "uniform2f", + "uniform2fv", + "uniform2i", + "uniform2iv", + "uniform2ui", + "uniform2uiv", + "uniform3f", + "uniform3fv", + "uniform3i", + "uniform3iv", + "uniform3ui", + "uniform3uiv", + "uniform4f", + "uniform4fv", + "uniform4i", + "uniform4iv", + "uniform4ui", + "uniform4uiv", + "uniformBlockBinding", + "uniformMatrix2fv", + "uniformMatrix2x3fv", + "uniformMatrix2x4fv", + "uniformMatrix3fv", + "uniformMatrix3x2fv", + "uniformMatrix3x4fv", + "uniformMatrix4fv", + "uniformMatrix4x2fv", + "uniformMatrix4x3fv", + "unique", + "uniqueID", + "uniqueNumber", + "unit", + "unitType", + "units", + "unloadEventEnd", + "unloadEventStart", + "unlock", + "unmount", + "unobserve", + "unpause", + "unpauseAnimations", + "unreadCount", + "unregister", + "unregisterContentHandler", + "unregisterProtocolHandler", + "unscopables", + "unselectable", + "unshift", + "unsubscribe", + "unsuspendRedraw", + "unsuspendRedrawAll", + "unwatch", + "unwrapKey", + "upDegrees", + "upX", + "upY", + "upZ", + "update", + "updateCommands", + "updateIce", + "updateInterval", + "updatePlaybackRate", + "updateRenderState", + "updateSettings", + "updateTiming", + "updateViaCache", + "updateWith", + "updated", + "updating", + "upgrade", + "upload", + "uploadTotal", + "uploaded", + "upper", + "upperBound", + "upperOpen", + "uri", + "url", + "urn", + "urns", + "usages", + "usb", + "usbVersionMajor", + "usbVersionMinor", + "usbVersionSubminor", + "useCurrentView", + "useMap", + "useProgram", + "usedSpace", + "user-select", + "userActivation", + "userAgent", + "userChoice", + "userHandle", + "userHint", + "userLanguage", + "userSelect", + "userVisibleOnly", + "username", + "usernameFragment", + "utterance", + "uuid", + "v8BreakIterator", + "vAlign", + "vLink", + "valid", + "validate", + "validateProgram", + "validationMessage", + "validity", + "value", + "valueAsDate", + "valueAsNumber", + "valueAsString", + "valueInSpecifiedUnits", + "valueMissing", + "valueOf", + "valueText", + "valueType", + "values", + "variable", + "variant", + "variationSettings", + "vector-effect", + "vectorEffect", + "velocityAngular", + "velocityExpansion", + "velocityX", + "velocityY", + "vendor", + "vendorId", + "vendorSub", + "verify", + "version", + "vertexAttrib1f", + "vertexAttrib1fv", + "vertexAttrib2f", + "vertexAttrib2fv", + "vertexAttrib3f", + "vertexAttrib3fv", + "vertexAttrib4f", + "vertexAttrib4fv", + "vertexAttribDivisor", + "vertexAttribDivisorANGLE", + "vertexAttribI4i", + "vertexAttribI4iv", + "vertexAttribI4ui", + "vertexAttribI4uiv", + "vertexAttribIPointer", + "vertexAttribPointer", + "vertical", + "vertical-align", + "verticalAlign", + "verticalOverflow", + "vh", + "vibrate", + "vibrationActuator", + "videoBitsPerSecond", + "videoHeight", + "videoTracks", + "videoWidth", + "view", + "viewBox", + "viewBoxString", + "viewTarget", + "viewTargetString", + "viewport", + "viewportAnchorX", + "viewportAnchorY", + "viewportElement", + "views", + "violatedDirective", + "visibility", + "visibilityState", + "visible", + "visualViewport", + "vlinkColor", + "vmax", + "vmin", + "voice", + "voiceURI", + "volume", + "vrml", + "vspace", + "vw", + "w", + "wait", + "waitSync", + "waiting", + "wake", + "wakeLock", + "wand", + "warn", + "wasClean", + "wasDiscarded", + "watch", + "watchAvailability", + "watchPosition", + "webdriver", + "webkitAddKey", + "webkitAlignContent", + "webkitAlignItems", + "webkitAlignSelf", + "webkitAnimation", + "webkitAnimationDelay", + "webkitAnimationDirection", + "webkitAnimationDuration", + "webkitAnimationFillMode", + "webkitAnimationIterationCount", + "webkitAnimationName", + "webkitAnimationPlayState", + "webkitAnimationTimingFunction", + "webkitAppearance", + "webkitAudioContext", + "webkitAudioDecodedByteCount", + "webkitAudioPannerNode", + "webkitBackfaceVisibility", + "webkitBackground", + "webkitBackgroundAttachment", + "webkitBackgroundClip", + "webkitBackgroundColor", + "webkitBackgroundImage", + "webkitBackgroundOrigin", + "webkitBackgroundPosition", + "webkitBackgroundPositionX", + "webkitBackgroundPositionY", + "webkitBackgroundRepeat", + "webkitBackgroundSize", + "webkitBackingStorePixelRatio", + "webkitBorderBottomLeftRadius", + "webkitBorderBottomRightRadius", + "webkitBorderImage", + "webkitBorderImageOutset", + "webkitBorderImageRepeat", + "webkitBorderImageSlice", + "webkitBorderImageSource", + "webkitBorderImageWidth", + "webkitBorderRadius", + "webkitBorderTopLeftRadius", + "webkitBorderTopRightRadius", + "webkitBoxAlign", + "webkitBoxDirection", + "webkitBoxFlex", + "webkitBoxOrdinalGroup", + "webkitBoxOrient", + "webkitBoxPack", + "webkitBoxShadow", + "webkitBoxSizing", + "webkitCancelAnimationFrame", + "webkitCancelFullScreen", + "webkitCancelKeyRequest", + "webkitCancelRequestAnimationFrame", + "webkitClearResourceTimings", + "webkitClosedCaptionsVisible", + "webkitConvertPointFromNodeToPage", + "webkitConvertPointFromPageToNode", + "webkitCreateShadowRoot", + "webkitCurrentFullScreenElement", + "webkitCurrentPlaybackTargetIsWireless", + "webkitDecodedFrameCount", + "webkitDirectionInvertedFromDevice", + "webkitDisplayingFullscreen", + "webkitDroppedFrameCount", + "webkitEnterFullScreen", + "webkitEnterFullscreen", + "webkitEntries", + "webkitExitFullScreen", + "webkitExitFullscreen", + "webkitExitPointerLock", + "webkitFilter", + "webkitFlex", + "webkitFlexBasis", + "webkitFlexDirection", + "webkitFlexFlow", + "webkitFlexGrow", + "webkitFlexShrink", + "webkitFlexWrap", + "webkitFullScreenKeyboardInputAllowed", + "webkitFullscreenElement", + "webkitFullscreenEnabled", + "webkitGenerateKeyRequest", + "webkitGetAsEntry", + "webkitGetDatabaseNames", + "webkitGetEntries", + "webkitGetEntriesByName", + "webkitGetEntriesByType", + "webkitGetFlowByName", + "webkitGetGamepads", + "webkitGetImageDataHD", + "webkitGetNamedFlows", + "webkitGetRegionFlowRanges", + "webkitGetUserMedia", + "webkitHasClosedCaptions", + "webkitHidden", + "webkitIDBCursor", + "webkitIDBDatabase", + "webkitIDBDatabaseError", + "webkitIDBDatabaseException", + "webkitIDBFactory", + "webkitIDBIndex", + "webkitIDBKeyRange", + "webkitIDBObjectStore", + "webkitIDBRequest", + "webkitIDBTransaction", + "webkitImageSmoothingEnabled", + "webkitIndexedDB", + "webkitInitMessageEvent", + "webkitIsFullScreen", + "webkitJustifyContent", + "webkitKeys", + "webkitLineClamp", + "webkitLineDashOffset", + "webkitLockOrientation", + "webkitMask", + "webkitMaskClip", + "webkitMaskComposite", + "webkitMaskImage", + "webkitMaskOrigin", + "webkitMaskPosition", + "webkitMaskPositionX", + "webkitMaskPositionY", + "webkitMaskRepeat", + "webkitMaskSize", + "webkitMatchesSelector", + "webkitMediaStream", + "webkitNotifications", + "webkitOfflineAudioContext", + "webkitOrder", + "webkitOrientation", + "webkitPeerConnection00", + "webkitPersistentStorage", + "webkitPerspective", + "webkitPerspectiveOrigin", + "webkitPointerLockElement", + "webkitPostMessage", + "webkitPreservesPitch", + "webkitPutImageDataHD", + "webkitRTCPeerConnection", + "webkitRegionOverset", + "webkitRelativePath", + "webkitRequestAnimationFrame", + "webkitRequestFileSystem", + "webkitRequestFullScreen", + "webkitRequestFullscreen", + "webkitRequestPointerLock", + "webkitResolveLocalFileSystemURL", + "webkitSetMediaKeys", + "webkitSetResourceTimingBufferSize", + "webkitShadowRoot", + "webkitShowPlaybackTargetPicker", + "webkitSlice", + "webkitSpeechGrammar", + "webkitSpeechGrammarList", + "webkitSpeechRecognition", + "webkitSpeechRecognitionError", + "webkitSpeechRecognitionEvent", + "webkitStorageInfo", + "webkitSupportsFullscreen", + "webkitTemporaryStorage", + "webkitTextFillColor", + "webkitTextSizeAdjust", + "webkitTextStroke", + "webkitTextStrokeColor", + "webkitTextStrokeWidth", + "webkitTransform", + "webkitTransformOrigin", + "webkitTransformStyle", + "webkitTransition", + "webkitTransitionDelay", + "webkitTransitionDuration", + "webkitTransitionProperty", + "webkitTransitionTimingFunction", + "webkitURL", + "webkitUnlockOrientation", + "webkitUserSelect", + "webkitVideoDecodedByteCount", + "webkitVisibilityState", + "webkitWirelessVideoPlaybackDisabled", + "webkitdirectory", + "webkitdropzone", + "webstore", + "weight", + "whatToShow", + "wheelDelta", + "wheelDeltaX", + "wheelDeltaY", + "whenDefined", + "which", + "white-space", + "whiteSpace", + "wholeText", + "widows", + "width", + "will-change", + "willChange", + "willValidate", + "window", + "withCredentials", + "word-break", + "word-spacing", + "word-wrap", + "wordBreak", + "wordSpacing", + "wordWrap", + "workerStart", + "wrap", + "wrapKey", + "writable", + "writableAuxiliaries", + "write", + "writeText", + "writeValue", + "writeWithoutResponse", + "writeln", + "writing-mode", + "writingMode", + "x", + "x1", + "x2", + "xChannelSelector", + "xmlEncoding", + "xmlStandalone", + "xmlVersion", + "xmlbase", + "xmllang", + "xmlspace", + "xor", + "xr", + "y", + "y1", + "y2", + "yChannelSelector", + "yandex", + "z", + "z-index", + "zIndex", + "zoom", + "zoomAndPan", + "zoomRectScreen", +]; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +function find_builtins(reserved) { + domprops.forEach(add); + + // Compatibility fix for some standard defined globals not defined on every js environment + var new_globals = ["Symbol", "Map", "Promise", "Proxy", "Reflect", "Set", "WeakMap", "WeakSet"]; + var objects = {}; + var global_ref = typeof global === "object" ? global : self; + + new_globals.forEach(function (new_global) { + objects[new_global] = global_ref[new_global] || new Function(); + }); + + [ + "null", + "true", + "false", + "NaN", + "Infinity", + "-Infinity", + "undefined", + ].forEach(add); + [ Object, Array, Function, Number, + String, Boolean, Error, Math, + Date, RegExp, objects.Symbol, ArrayBuffer, + DataView, decodeURI, decodeURIComponent, + encodeURI, encodeURIComponent, eval, EvalError, + Float32Array, Float64Array, Int8Array, Int16Array, + Int32Array, isFinite, isNaN, JSON, objects.Map, parseFloat, + parseInt, objects.Promise, objects.Proxy, RangeError, ReferenceError, + objects.Reflect, objects.Set, SyntaxError, TypeError, Uint8Array, + Uint8ClampedArray, Uint16Array, Uint32Array, URIError, + objects.WeakMap, objects.WeakSet + ].forEach(function(ctor) { + Object.getOwnPropertyNames(ctor).map(add); + if (ctor.prototype) { + Object.getOwnPropertyNames(ctor.prototype).map(add); + } + }); + function add(name) { + reserved.add(name); + } +} + +function reserve_quoted_keys(ast, reserved) { + function add(name) { + push_uniq(reserved, name); + } + + ast.walk(new TreeWalker(function(node) { + if (node instanceof AST_ObjectKeyVal && node.quote) { + add(node.key); + } else if (node instanceof AST_ObjectProperty && node.quote) { + add(node.key.name); + } else if (node instanceof AST_Sub) { + addStrings(node.property, add); + } + })); +} + +function addStrings(node, add) { + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_Sequence) { + addStrings(node.tail_node(), add); + } else if (node instanceof AST_String) { + add(node.value); + } else if (node instanceof AST_Conditional) { + addStrings(node.consequent, add); + addStrings(node.alternative, add); + } + return true; + })); +} + +function mangle_private_properties(ast, options) { + var cprivate = -1; + var private_cache = new Map(); + var nth_identifier = options.nth_identifier || base54; + + ast = ast.transform(new TreeTransformer(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + ) { + node.key.name = mangle_private(node.key.name); + } else if (node instanceof AST_DotHash) { + node.property = mangle_private(node.property); + } + })); + return ast; + + function mangle_private(name) { + let mangled = private_cache.get(name); + if (!mangled) { + mangled = nth_identifier.get(++cprivate); + private_cache.set(name, mangled); + } + + return mangled; + } +} + +function mangle_properties(ast, options) { + options = defaults(options, { + builtins: false, + cache: null, + debug: false, + keep_quoted: false, + nth_identifier: base54, + only_cache: false, + regex: null, + reserved: null, + undeclared: false, + }, true); + + var nth_identifier = options.nth_identifier; + + var reserved_option = options.reserved; + if (!Array.isArray(reserved_option)) reserved_option = [reserved_option]; + var reserved = new Set(reserved_option); + if (!options.builtins) find_builtins(reserved); + + var cname = -1; + + var cache; + if (options.cache) { + cache = options.cache.props; + } else { + cache = new Map(); + } + + var regex = options.regex && new RegExp(options.regex); + + // note debug is either false (disabled), or a string of the debug suffix to use (enabled). + // note debug may be enabled as an empty string, which is falsey. Also treat passing 'true' + // the same as passing an empty string. + var debug = options.debug !== false; + var debug_name_suffix; + if (debug) { + debug_name_suffix = (options.debug === true ? "" : options.debug); + } + + var names_to_mangle = new Set(); + var unmangleable = new Set(); + // Track each already-mangled name to prevent nth_identifier from generating + // the same name. + cache.forEach((mangled_name) => unmangleable.add(mangled_name)); + + var keep_quoted = !!options.keep_quoted; + + // step 1: find candidates to mangle + ast.walk(new TreeWalker(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_DotHash + ) ; else if (node instanceof AST_ObjectKeyVal) { + if (typeof node.key == "string" && (!keep_quoted || !node.quote)) { + add(node.key); + } + } else if (node instanceof AST_ObjectProperty) { + // setter or getter, since KeyVal is handled above + if (!keep_quoted || !node.quote) { + add(node.key.name); + } + } else if (node instanceof AST_Dot) { + var declared = !!options.undeclared; + if (!declared) { + var root = node; + while (root.expression) { + root = root.expression; + } + declared = !(root.thedef && root.thedef.undeclared); + } + if (declared && + (!keep_quoted || !node.quote)) { + add(node.property); + } + } else if (node instanceof AST_Sub) { + if (!keep_quoted) { + addStrings(node.property, add); + } + } else if (node instanceof AST_Call + && node.expression.print_to_string() == "Object.defineProperty") { + addStrings(node.args[1], add); + } else if (node instanceof AST_Binary && node.operator === "in") { + addStrings(node.left, add); + } + })); + + // step 2: transform the tree, renaming properties + return ast.transform(new TreeTransformer(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_DotHash + ) ; else if (node instanceof AST_ObjectKeyVal) { + if (typeof node.key == "string" && (!keep_quoted || !node.quote)) { + node.key = mangle(node.key); + } + } else if (node instanceof AST_ObjectProperty) { + // setter, getter, method or class field + if (!keep_quoted || !node.quote) { + node.key.name = mangle(node.key.name); + } + } else if (node instanceof AST_Dot) { + if (!keep_quoted || !node.quote) { + node.property = mangle(node.property); + } + } else if (!keep_quoted && node instanceof AST_Sub) { + node.property = mangleStrings(node.property); + } else if (node instanceof AST_Call + && node.expression.print_to_string() == "Object.defineProperty") { + node.args[1] = mangleStrings(node.args[1]); + } else if (node instanceof AST_Binary && node.operator === "in") { + node.left = mangleStrings(node.left); + } + })); + + // only function declarations after this line + + function can_mangle(name) { + if (unmangleable.has(name)) return false; + if (reserved.has(name)) return false; + if (options.only_cache) { + return cache.has(name); + } + if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false; + return true; + } + + function should_mangle(name) { + if (regex && !regex.test(name)) return false; + if (reserved.has(name)) return false; + return cache.has(name) + || names_to_mangle.has(name); + } + + function add(name) { + if (can_mangle(name)) + names_to_mangle.add(name); + + if (!should_mangle(name)) { + unmangleable.add(name); + } + } + + function mangle(name) { + if (!should_mangle(name)) { + return name; + } + + var mangled = cache.get(name); + if (!mangled) { + if (debug) { + // debug mode: use a prefix and suffix to preserve readability, e.g. o.foo -> o._$foo$NNN_. + var debug_mangled = "_$" + name + "$" + debug_name_suffix + "_"; + + if (can_mangle(debug_mangled)) { + mangled = debug_mangled; + } + } + + // either debug mode is off, or it is on and we could not use the mangled name + if (!mangled) { + do { + mangled = nth_identifier.get(++cname); + } while (!can_mangle(mangled)); + } + + cache.set(name, mangled); + } + return mangled; + } + + function mangleStrings(node) { + return node.transform(new TreeTransformer(function(node) { + if (node instanceof AST_Sequence) { + var last = node.expressions.length - 1; + node.expressions[last] = mangleStrings(node.expressions[last]); + } else if (node instanceof AST_String) { + node.value = mangle(node.value); + } else if (node instanceof AST_Conditional) { + node.consequent = mangleStrings(node.consequent); + node.alternative = mangleStrings(node.alternative); + } + return node; + })); + } +} + +var to_ascii = typeof atob == "undefined" ? function(b64) { + return Buffer.from(b64, "base64").toString(); +} : atob; +var to_base64 = typeof btoa == "undefined" ? function(str) { + return Buffer.from(str).toString("base64"); +} : btoa; + +function read_source_map(code) { + var match = /(?:^|[^.])\/\/# sourceMappingURL=data:application\/json(;[\w=-]*)?;base64,([+/0-9A-Za-z]*=*)\s*$/.exec(code); + if (!match) { + console.warn("inline source map not found"); + return null; + } + return to_ascii(match[2]); +} + +function set_shorthand(name, options, keys) { + if (options[name]) { + keys.forEach(function(key) { + if (options[key]) { + if (typeof options[key] != "object") options[key] = {}; + if (!(name in options[key])) options[key][name] = options[name]; + } + }); + } +} + +function init_cache(cache) { + if (!cache) return; + if (!("props" in cache)) { + cache.props = new Map(); + } else if (!(cache.props instanceof Map)) { + cache.props = map_from_object(cache.props); + } +} + +function cache_to_json(cache) { + return { + props: map_to_object(cache.props) + }; +} + +function log_input(files, options, fs, debug_folder) { + if (!(fs && fs.writeFileSync && fs.mkdirSync)) { + return; + } + + try { + fs.mkdirSync(debug_folder); + } catch (e) { + if (e.code !== "EEXIST") throw e; + } + + const log_path = `${debug_folder}/terser-debug-${(Math.random() * 9999999) | 0}.log`; + + options = options || {}; + + const options_str = JSON.stringify(options, (_key, thing) => { + if (typeof thing === "function") return "[Function " + thing.toString() + "]"; + if (thing instanceof RegExp) return "[RegExp " + thing.toString() + "]"; + return thing; + }, 4); + + const files_str = (file) => { + if (typeof file === "object" && options.parse && options.parse.spidermonkey) { + return JSON.stringify(file, null, 2); + } else if (typeof file === "object") { + return Object.keys(file) + .map((key) => key + ": " + files_str(file[key])) + .join("\n\n"); + } else if (typeof file === "string") { + return "```\n" + file + "\n```"; + } else { + return file; // What do? + } + }; + + fs.writeFileSync(log_path, "Options: \n" + options_str + "\n\nInput files:\n\n" + files_str(files) + "\n"); +} + +async function minify(files, options, _fs_module) { + if ( + _fs_module + && typeof process === "object" + && process.env + && typeof process.env.TERSER_DEBUG_DIR === "string" + ) { + log_input(files, options, _fs_module, process.env.TERSER_DEBUG_DIR); + } + + options = defaults(options, { + compress: {}, + ecma: undefined, + enclose: false, + ie8: false, + keep_classnames: undefined, + keep_fnames: false, + mangle: {}, + module: false, + nameCache: null, + output: null, + format: null, + parse: {}, + rename: undefined, + safari10: false, + sourceMap: false, + spidermonkey: false, + timings: false, + toplevel: false, + warnings: false, + wrap: false, + }, true); + + var timings = options.timings && { + start: Date.now() + }; + if (options.keep_classnames === undefined) { + options.keep_classnames = options.keep_fnames; + } + if (options.rename === undefined) { + options.rename = options.compress && options.mangle; + } + if (options.output && options.format) { + throw new Error("Please only specify either output or format option, preferrably format."); + } + options.format = options.format || options.output || {}; + set_shorthand("ecma", options, [ "parse", "compress", "format" ]); + set_shorthand("ie8", options, [ "compress", "mangle", "format" ]); + set_shorthand("keep_classnames", options, [ "compress", "mangle" ]); + set_shorthand("keep_fnames", options, [ "compress", "mangle" ]); + set_shorthand("module", options, [ "parse", "compress", "mangle" ]); + set_shorthand("safari10", options, [ "mangle", "format" ]); + set_shorthand("toplevel", options, [ "compress", "mangle" ]); + set_shorthand("warnings", options, [ "compress" ]); // legacy + var quoted_props; + if (options.mangle) { + options.mangle = defaults(options.mangle, { + cache: options.nameCache && (options.nameCache.vars || {}), + eval: false, + ie8: false, + keep_classnames: false, + keep_fnames: false, + module: false, + nth_identifier: base54, + properties: false, + reserved: [], + safari10: false, + toplevel: false, + }, true); + if (options.mangle.properties) { + if (typeof options.mangle.properties != "object") { + options.mangle.properties = {}; + } + if (options.mangle.properties.keep_quoted) { + quoted_props = options.mangle.properties.reserved; + if (!Array.isArray(quoted_props)) quoted_props = []; + options.mangle.properties.reserved = quoted_props; + } + if (options.nameCache && !("cache" in options.mangle.properties)) { + options.mangle.properties.cache = options.nameCache.props || {}; + } + } + init_cache(options.mangle.cache); + init_cache(options.mangle.properties.cache); + } + if (options.sourceMap) { + options.sourceMap = defaults(options.sourceMap, { + asObject: false, + content: null, + filename: null, + includeSources: false, + root: null, + url: null, + }, true); + } + if (timings) timings.parse = Date.now(); + var toplevel; + if (files instanceof AST_Toplevel) { + toplevel = files; + } else { + if (typeof files == "string" || (options.parse.spidermonkey && !Array.isArray(files))) { + files = [ files ]; + } + options.parse = options.parse || {}; + options.parse.toplevel = null; + + if (options.parse.spidermonkey) { + options.parse.toplevel = AST_Node.from_mozilla_ast(Object.keys(files).reduce(function(toplevel, name) { + if (!toplevel) return files[name]; + toplevel.body = toplevel.body.concat(files[name].body); + return toplevel; + }, null)); + } else { + delete options.parse.spidermonkey; + + for (var name in files) if (HOP(files, name)) { + options.parse.filename = name; + options.parse.toplevel = parse(files[name], options.parse); + if (options.sourceMap && options.sourceMap.content == "inline") { + if (Object.keys(files).length > 1) + throw new Error("inline source map only works with singular input"); + options.sourceMap.content = read_source_map(files[name]); + } + } + } + + toplevel = options.parse.toplevel; + } + if (quoted_props && options.mangle.properties.keep_quoted !== "strict") { + reserve_quoted_keys(toplevel, quoted_props); + } + if (options.wrap) { + toplevel = toplevel.wrap_commonjs(options.wrap); + } + if (options.enclose) { + toplevel = toplevel.wrap_enclose(options.enclose); + } + if (timings) timings.rename = Date.now(); + if (timings) timings.compress = Date.now(); + if (options.compress) { + toplevel = new Compressor(options.compress, { + mangle_options: options.mangle + }).compress(toplevel); + } + if (timings) timings.scope = Date.now(); + if (options.mangle) toplevel.figure_out_scope(options.mangle); + if (timings) timings.mangle = Date.now(); + if (options.mangle) { + toplevel.compute_char_frequency(options.mangle); + toplevel.mangle_names(options.mangle); + toplevel = mangle_private_properties(toplevel, options.mangle); + } + if (timings) timings.properties = Date.now(); + if (options.mangle && options.mangle.properties) { + toplevel = mangle_properties(toplevel, options.mangle.properties); + } + if (timings) timings.format = Date.now(); + var result = {}; + if (options.format.ast) { + result.ast = toplevel; + } + if (options.format.spidermonkey) { + result.ast = toplevel.to_mozilla_ast(); + } + if (!HOP(options.format, "code") || options.format.code) { + if (options.sourceMap) { + options.format.source_map = await SourceMap({ + file: options.sourceMap.filename, + orig: options.sourceMap.content, + root: options.sourceMap.root + }); + if (options.sourceMap.includeSources) { + if (files instanceof AST_Toplevel) { + throw new Error("original source content unavailable"); + } else for (var name in files) if (HOP(files, name)) { + options.format.source_map.get().setSourceContent(name, files[name]); + } + } + } + delete options.format.ast; + delete options.format.code; + delete options.format.spidermonkey; + var stream = OutputStream(options.format); + toplevel.print(stream); + result.code = stream.get(); + if (options.sourceMap) { + if(options.sourceMap.asObject) { + result.map = options.format.source_map.get().toJSON(); + } else { + result.map = options.format.source_map.toString(); + } + if (options.sourceMap.url == "inline") { + var sourceMap = typeof result.map === "object" ? JSON.stringify(result.map) : result.map; + result.code += "\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + to_base64(sourceMap); + } else if (options.sourceMap.url) { + result.code += "\n//# sourceMappingURL=" + options.sourceMap.url; + } + } + } + if (options.nameCache && options.mangle) { + if (options.mangle.cache) options.nameCache.vars = cache_to_json(options.mangle.cache); + if (options.mangle.properties && options.mangle.properties.cache) { + options.nameCache.props = cache_to_json(options.mangle.properties.cache); + } + } + if (options.format && options.format.source_map) { + options.format.source_map.destroy(); + } + if (timings) { + timings.end = Date.now(); + result.timings = { + parse: 1e-3 * (timings.rename - timings.parse), + rename: 1e-3 * (timings.compress - timings.rename), + compress: 1e-3 * (timings.scope - timings.compress), + scope: 1e-3 * (timings.mangle - timings.scope), + mangle: 1e-3 * (timings.properties - timings.mangle), + properties: 1e-3 * (timings.format - timings.properties), + format: 1e-3 * (timings.end - timings.format), + total: 1e-3 * (timings.end - timings.start) + }; + } + return result; +} + +async function run_cli({ program, packageJson, fs, path }) { + const skip_keys = new Set([ "cname", "parent_scope", "scope", "uses_eval", "uses_with" ]); + var files = {}; + var options = { + compress: false, + mangle: false + }; + const default_options = await _default_options(); + program.version(packageJson.name + " " + packageJson.version); + program.parseArgv = program.parse; + program.parse = undefined; + + if (process.argv.includes("ast")) program.helpInformation = describe_ast; + else if (process.argv.includes("options")) program.helpInformation = function() { + var text = []; + for (var option in default_options) { + text.push("--" + (option === "sourceMap" ? "source-map" : option) + " options:"); + text.push(format_object(default_options[option])); + text.push(""); + } + return text.join("\n"); + }; + + program.option("-p, --parse ", "Specify parser options.", parse_js()); + program.option("-c, --compress [options]", "Enable compressor/specify compressor options.", parse_js()); + program.option("-m, --mangle [options]", "Mangle names/specify mangler options.", parse_js()); + program.option("--mangle-props [options]", "Mangle properties/specify mangler options.", parse_js()); + program.option("-f, --format [options]", "Format options.", parse_js()); + program.option("-b, --beautify [options]", "Alias for --format.", parse_js()); + program.option("-o, --output ", "Output file (default STDOUT)."); + program.option("--comments [filter]", "Preserve copyright comments in the output."); + program.option("--config-file ", "Read minify() options from JSON file."); + program.option("-d, --define [=value]", "Global definitions.", parse_js("define")); + program.option("--ecma ", "Specify ECMAScript release: 5, 2015, 2016 or 2017..."); + program.option("-e, --enclose [arg[,...][:value[,...]]]", "Embed output in a big function with configurable arguments and values."); + program.option("--ie8", "Support non-standard Internet Explorer 8."); + program.option("--keep-classnames", "Do not mangle/drop class names."); + program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name."); + program.option("--module", "Input is an ES6 module"); + program.option("--name-cache ", "File to hold mangled name mappings."); + program.option("--rename", "Force symbol expansion."); + program.option("--no-rename", "Disable symbol expansion."); + program.option("--safari10", "Support non-standard Safari 10."); + program.option("--source-map [options]", "Enable source map/specify source map options.", parse_js()); + program.option("--timings", "Display operations run time on STDERR."); + program.option("--toplevel", "Compress and/or mangle variables in toplevel scope."); + program.option("--wrap ", "Embed everything as a function with “exports” corresponding to “name” globally."); + program.arguments("[files...]").parseArgv(process.argv); + if (program.configFile) { + options = JSON.parse(read_file(program.configFile)); + } + if (!program.output && program.sourceMap && program.sourceMap.url != "inline") { + fatal("ERROR: cannot write source map to STDOUT"); + } + + [ + "compress", + "enclose", + "ie8", + "mangle", + "module", + "safari10", + "sourceMap", + "toplevel", + "wrap" + ].forEach(function(name) { + if (name in program) { + options[name] = program[name]; + } + }); + + if ("ecma" in program) { + if (program.ecma != (program.ecma | 0)) fatal("ERROR: ecma must be an integer"); + const ecma = program.ecma | 0; + if (ecma > 5 && ecma < 2015) + options.ecma = ecma + 2009; + else + options.ecma = ecma; + } + if (program.format || program.beautify) { + const chosenOption = program.format || program.beautify; + options.format = typeof chosenOption === "object" ? chosenOption : {}; + } + if (program.comments) { + if (typeof options.format != "object") options.format = {}; + options.format.comments = typeof program.comments == "string" ? (program.comments == "false" ? false : program.comments) : "some"; + } + if (program.define) { + if (typeof options.compress != "object") options.compress = {}; + if (typeof options.compress.global_defs != "object") options.compress.global_defs = {}; + for (var expr in program.define) { + options.compress.global_defs[expr] = program.define[expr]; + } + } + if (program.keepClassnames) { + options.keep_classnames = true; + } + if (program.keepFnames) { + options.keep_fnames = true; + } + if (program.mangleProps) { + if (program.mangleProps.domprops) { + delete program.mangleProps.domprops; + } else { + if (typeof program.mangleProps != "object") program.mangleProps = {}; + if (!Array.isArray(program.mangleProps.reserved)) program.mangleProps.reserved = []; + } + if (typeof options.mangle != "object") options.mangle = {}; + options.mangle.properties = program.mangleProps; + } + if (program.nameCache) { + options.nameCache = JSON.parse(read_file(program.nameCache, "{}")); + } + if (program.output == "ast") { + options.format = { + ast: true, + code: false + }; + } + if (program.parse) { + if (!program.parse.acorn && !program.parse.spidermonkey) { + options.parse = program.parse; + } else if (program.sourceMap && program.sourceMap.content == "inline") { + fatal("ERROR: inline source map only works with built-in parser"); + } + } + if (~program.rawArgs.indexOf("--rename")) { + options.rename = true; + } else if (!program.rename) { + options.rename = false; + } + + let convert_path = name => name; + if (typeof program.sourceMap == "object" && "base" in program.sourceMap) { + convert_path = function() { + var base = program.sourceMap.base; + delete options.sourceMap.base; + return function(name) { + return path.relative(base, name); + }; + }(); + } + + let filesList; + if (options.files && options.files.length) { + filesList = options.files; + + delete options.files; + } else if (program.args.length) { + filesList = program.args; + } + + if (filesList) { + simple_glob(filesList).forEach(function(name) { + files[convert_path(name)] = read_file(name); + }); + } else { + await new Promise((resolve) => { + var chunks = []; + process.stdin.setEncoding("utf8"); + process.stdin.on("data", function(chunk) { + chunks.push(chunk); + }).on("end", function() { + files = [ chunks.join("") ]; + resolve(); + }); + process.stdin.resume(); + }); + } + + await run_cli(); + + function convert_ast(fn) { + return AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null)); + } + + async function run_cli() { + var content = program.sourceMap && program.sourceMap.content; + if (content && content !== "inline") { + options.sourceMap.content = read_file(content, content); + } + if (program.timings) options.timings = true; + + try { + if (program.parse) { + if (program.parse.acorn) { + files = convert_ast(function(toplevel, name) { + return require("acorn").parse(files[name], { + ecmaVersion: 2018, + locations: true, + program: toplevel, + sourceFile: name, + sourceType: options.module || program.parse.module ? "module" : "script" + }); + }); + } else if (program.parse.spidermonkey) { + files = convert_ast(function(toplevel, name) { + var obj = JSON.parse(files[name]); + if (!toplevel) return obj; + toplevel.body = toplevel.body.concat(obj.body); + return toplevel; + }); + } + } + } catch (ex) { + fatal(ex); + } + + let result; + try { + result = await minify(files, options, fs); + } catch (ex) { + if (ex.name == "SyntaxError") { + print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col); + var col = ex.col; + var lines = files[ex.filename].split(/\r?\n/); + var line = lines[ex.line - 1]; + if (!line && !col) { + line = lines[ex.line - 2]; + col = line.length; + } + if (line) { + var limit = 70; + if (col > limit) { + line = line.slice(col - limit); + col = limit; + } + print_error(line.slice(0, 80)); + print_error(line.slice(0, col).replace(/\S/g, " ") + "^"); + } + } + if (ex.defs) { + print_error("Supported options:"); + print_error(format_object(ex.defs)); + } + fatal(ex); + return; + } + + if (program.output == "ast") { + if (!options.compress && !options.mangle) { + result.ast.figure_out_scope({}); + } + console.log(JSON.stringify(result.ast, function(key, value) { + if (value) switch (key) { + case "thedef": + return symdef(value); + case "enclosed": + return value.length ? value.map(symdef) : undefined; + case "variables": + case "globals": + return value.size ? collect_from_map(value, symdef) : undefined; + } + if (skip_keys.has(key)) return; + if (value instanceof AST_Token) return; + if (value instanceof Map) return; + if (value instanceof AST_Node) { + var result = { + _class: "AST_" + value.TYPE + }; + if (value.block_scope) { + result.variables = value.block_scope.variables; + result.enclosed = value.block_scope.enclosed; + } + value.CTOR.PROPS.forEach(function(prop) { + result[prop] = value[prop]; + }); + return result; + } + return value; + }, 2)); + } else if (program.output == "spidermonkey") { + try { + const minified = await minify( + result.code, + { + compress: false, + mangle: false, + format: { + ast: true, + code: false + } + }, + fs + ); + console.log(JSON.stringify(minified.ast.to_mozilla_ast(), null, 2)); + } catch (ex) { + fatal(ex); + return; + } + } else if (program.output) { + fs.writeFileSync(program.output, result.code); + if (options.sourceMap && options.sourceMap.url !== "inline" && result.map) { + fs.writeFileSync(program.output + ".map", result.map); + } + } else { + console.log(result.code); + } + if (program.nameCache) { + fs.writeFileSync(program.nameCache, JSON.stringify(options.nameCache)); + } + if (result.timings) for (var phase in result.timings) { + print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s"); + } + } + + function fatal(message) { + if (message instanceof Error) message = message.stack.replace(/^\S*?Error:/, "ERROR:"); + print_error(message); + process.exit(1); + } + + // A file glob function that only supports "*" and "?" wildcards in the basename. + // Example: "foo/bar/*baz??.*.js" + // Argument `glob` may be a string or an array of strings. + // Returns an array of strings. Garbage in, garbage out. + function simple_glob(glob) { + if (Array.isArray(glob)) { + return [].concat.apply([], glob.map(simple_glob)); + } + if (glob && glob.match(/[*?]/)) { + var dir = path.dirname(glob); + try { + var entries = fs.readdirSync(dir); + } catch (ex) {} + if (entries) { + var pattern = "^" + path.basename(glob) + .replace(/[.+^$[\]\\(){}]/g, "\\$&") + .replace(/\*/g, "[^/\\\\]*") + .replace(/\?/g, "[^/\\\\]") + "$"; + var mod = process.platform === "win32" ? "i" : ""; + var rx = new RegExp(pattern, mod); + var results = entries.filter(function(name) { + return rx.test(name); + }).map(function(name) { + return path.join(dir, name); + }); + if (results.length) return results; + } + } + return [ glob ]; + } + + function read_file(path, default_value) { + try { + return fs.readFileSync(path, "utf8"); + } catch (ex) { + if ((ex.code == "ENOENT" || ex.code == "ENAMETOOLONG") && default_value != null) return default_value; + fatal(ex); + } + } + + function parse_js(flag) { + return function(value, options) { + options = options || {}; + try { + walk(parse(value, { expression: true }), node => { + if (node instanceof AST_Assign) { + var name = node.left.print_to_string(); + var value = node.right; + if (flag) { + options[name] = value; + } else if (value instanceof AST_Array) { + options[name] = value.elements.map(to_string); + } else if (value instanceof AST_RegExp) { + value = value.value; + options[name] = new RegExp(value.source, value.flags); + } else { + options[name] = to_string(value); + } + return true; + } + if (node instanceof AST_Symbol || node instanceof AST_PropAccess) { + var name = node.print_to_string(); + options[name] = true; + return true; + } + if (!(node instanceof AST_Sequence)) throw node; + + function to_string(value) { + return value instanceof AST_Constant ? value.getValue() : value.print_to_string({ + quote_keys: true + }); + } + }); + } catch(ex) { + if (flag) { + fatal("Error parsing arguments for '" + flag + "': " + value); + } else { + options[value] = null; + } + } + return options; + }; + } + + function symdef(def) { + var ret = (1e6 + def.id) + " " + def.name; + if (def.mangled_name) ret += " " + def.mangled_name; + return ret; + } + + function collect_from_map(map, callback) { + var result = []; + map.forEach(function (def) { + result.push(callback(def)); + }); + return result; + } + + function format_object(obj) { + var lines = []; + var padding = ""; + Object.keys(obj).map(function(name) { + if (padding.length < name.length) padding = Array(name.length + 1).join(" "); + return [ name, JSON.stringify(obj[name]) ]; + }).forEach(function(tokens) { + lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]); + }); + return lines.join("\n"); + } + + function print_error(msg) { + process.stderr.write(msg); + process.stderr.write("\n"); + } + + function describe_ast() { + var out = OutputStream({ beautify: true }); + function doitem(ctor) { + out.print("AST_" + ctor.TYPE); + const props = ctor.SELF_PROPS.filter(prop => !/^\$/.test(prop)); + + if (props.length > 0) { + out.space(); + out.with_parens(function() { + props.forEach(function(prop, i) { + if (i) out.space(); + out.print(prop); + }); + }); + } + + if (ctor.documentation) { + out.space(); + out.print_string(ctor.documentation); + } + + if (ctor.SUBCLASSES.length > 0) { + out.space(); + out.with_block(function() { + ctor.SUBCLASSES.forEach(function(ctor) { + out.indent(); + doitem(ctor); + out.newline(); + }); + }); + } + } + doitem(AST_Node); + return out + "\n"; + } +} + +async function _default_options() { + const defs = {}; + + Object.keys(infer_options({ 0: 0 })).forEach((component) => { + const options = infer_options({ + [component]: {0: 0} + }); + + if (options) defs[component] = options; + }); + return defs; +} + +async function infer_options(options) { + try { + await minify("", options); + } catch (error) { + return error.defs; + } +} + +exports._default_options = _default_options; +exports._run_cli = run_cli; +exports.minify = minify; + +}))); diff --git a/node_modules/mathjs/examples/node_modules/terser/dist/package.json b/node_modules/mathjs/examples/node_modules/terser/dist/package.json new file mode 100644 index 0000000..a4cb7d1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/dist/package.json @@ -0,0 +1,10 @@ +{ + "name": "dist", + "private": true, + "version": "1.0.0", + "main": "bundle.min.js", + "type": "commonjs", + "author": "", + "license": "BSD-2-Clause", + "description": "A package to hold the Terser dist bundle as commonjs while keeping the rest of it ESM. Nothing to see here." +} diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/ast.js b/node_modules/mathjs/examples/node_modules/terser/lib/ast.js new file mode 100644 index 0000000..07f2b50 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/ast.js @@ -0,0 +1,1858 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + HOP, + MAP, + noop +} from "./utils/index.js"; +import { parse } from "./parse.js"; + +function DEFNODE(type, props, methods, base = AST_Node) { + if (!props) props = []; + else props = props.split(/\s+/); + var self_props = props; + if (base && base.PROPS) + props = props.concat(base.PROPS); + var code = "return function AST_" + type + "(props){ if (props) { "; + for (var i = props.length; --i >= 0;) { + code += "this." + props[i] + " = props." + props[i] + ";"; + } + const proto = base && Object.create(base.prototype); + if (proto && proto.initialize || (methods && methods.initialize)) + code += "this.initialize();"; + code += "}"; + code += "this.flags = 0;"; + code += "}"; + var ctor = new Function(code)(); + if (proto) { + ctor.prototype = proto; + ctor.BASE = base; + } + if (base) base.SUBCLASSES.push(ctor); + ctor.prototype.CTOR = ctor; + ctor.prototype.constructor = ctor; + ctor.PROPS = props || null; + ctor.SELF_PROPS = self_props; + ctor.SUBCLASSES = []; + if (type) { + ctor.prototype.TYPE = ctor.TYPE = type; + } + if (methods) for (i in methods) if (HOP(methods, i)) { + if (i[0] === "$") { + ctor[i.substr(1)] = methods[i]; + } else { + ctor.prototype[i] = methods[i]; + } + } + ctor.DEFMETHOD = function(name, method) { + this.prototype[name] = method; + }; + return ctor; +} + +const has_tok_flag = (tok, flag) => Boolean(tok.flags & flag); +const set_tok_flag = (tok, flag, truth) => { + if (truth) { + tok.flags |= flag; + } else { + tok.flags &= ~flag; + } +}; + +const TOK_FLAG_NLB = 0b0001; +const TOK_FLAG_QUOTE_SINGLE = 0b0010; +const TOK_FLAG_QUOTE_EXISTS = 0b0100; + +class AST_Token { + constructor(type, value, line, col, pos, nlb, comments_before, comments_after, file) { + this.flags = (nlb ? 1 : 0); + + this.type = type; + this.value = value; + this.line = line; + this.col = col; + this.pos = pos; + this.comments_before = comments_before; + this.comments_after = comments_after; + this.file = file; + + Object.seal(this); + } + + get nlb() { + return has_tok_flag(this, TOK_FLAG_NLB); + } + + set nlb(new_nlb) { + set_tok_flag(this, TOK_FLAG_NLB, new_nlb); + } + + get quote() { + return !has_tok_flag(this, TOK_FLAG_QUOTE_EXISTS) + ? "" + : (has_tok_flag(this, TOK_FLAG_QUOTE_SINGLE) ? "'" : '"'); + } + + set quote(quote_type) { + set_tok_flag(this, TOK_FLAG_QUOTE_SINGLE, quote_type === "'"); + set_tok_flag(this, TOK_FLAG_QUOTE_EXISTS, !!quote_type); + } +} + +var AST_Node = DEFNODE("Node", "start end", { + _clone: function(deep) { + if (deep) { + var self = this.clone(); + return self.transform(new TreeTransformer(function(node) { + if (node !== self) { + return node.clone(true); + } + })); + } + return new this.CTOR(this); + }, + clone: function(deep) { + return this._clone(deep); + }, + $documentation: "Base class of all AST nodes", + $propdoc: { + start: "[AST_Token] The first token of this node", + end: "[AST_Token] The last token of this node" + }, + _walk: function(visitor) { + return visitor._visit(this); + }, + walk: function(visitor) { + return this._walk(visitor); // not sure the indirection will be any help + }, + _children_backwards: () => {} +}, null); + +/* -----[ statements ]----- */ + +var AST_Statement = DEFNODE("Statement", null, { + $documentation: "Base class of all statements", +}); + +var AST_Debugger = DEFNODE("Debugger", null, { + $documentation: "Represents a debugger statement", +}, AST_Statement); + +var AST_Directive = DEFNODE("Directive", "value quote", { + $documentation: "Represents a directive, like \"use strict\";", + $propdoc: { + value: "[string] The value of this directive as a plain string (it's not an AST_String!)", + quote: "[string] the original quote character" + }, +}, AST_Statement); + +var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", { + $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", + $propdoc: { + body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + } +}, AST_Statement); + +function walk_body(node, visitor) { + const body = node.body; + for (var i = 0, len = body.length; i < len; i++) { + body[i]._walk(visitor); + } +} + +function clone_block_scope(deep) { + var clone = this._clone(deep); + if (this.block_scope) { + clone.block_scope = this.block_scope.clone(); + } + return clone; +} + +var AST_Block = DEFNODE("Block", "body block_scope", { + $documentation: "A body of statements (usually braced)", + $propdoc: { + body: "[AST_Statement*] an array of statements", + block_scope: "[AST_Scope] the block scope" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + }, + clone: clone_block_scope +}, AST_Statement); + +var AST_BlockStatement = DEFNODE("BlockStatement", null, { + $documentation: "A block statement", +}, AST_Block); + +var AST_EmptyStatement = DEFNODE("EmptyStatement", null, { + $documentation: "The empty statement (empty block or simply a semicolon)" +}, AST_Statement); + +var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { + $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", + $propdoc: { + body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" + } +}, AST_Statement); + +var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { + $documentation: "Statement with a label", + $propdoc: { + label: "[AST_Label] a label definition" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.label._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.label); + }, + clone: function(deep) { + var node = this._clone(deep); + if (deep) { + var label = node.label; + var def = this.label; + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_LoopControl + && node.label && node.label.thedef === def) { + node.label.thedef = label; + label.references.push(node); + } + })); + } + return node; + } +}, AST_StatementWithBody); + +var AST_IterationStatement = DEFNODE("IterationStatement", "block_scope", { + $documentation: "Internal class. All loops inherit from it.", + $propdoc: { + block_scope: "[AST_Scope] the block scope for this iteration statement." + }, + clone: clone_block_scope +}, AST_StatementWithBody); + +var AST_DWLoop = DEFNODE("DWLoop", "condition", { + $documentation: "Base class for do/while statements", + $propdoc: { + condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" + } +}, AST_IterationStatement); + +var AST_Do = DEFNODE("Do", null, { + $documentation: "A `do` statement", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.body._walk(visitor); + this.condition._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.condition); + push(this.body); + } +}, AST_DWLoop); + +var AST_While = DEFNODE("While", null, { + $documentation: "A `while` statement", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.condition); + }, +}, AST_DWLoop); + +var AST_For = DEFNODE("For", "init condition step", { + $documentation: "A `for` statement", + $propdoc: { + init: "[AST_Node?] the `for` initialization code, or null if empty", + condition: "[AST_Node?] the `for` termination clause, or null if empty", + step: "[AST_Node?] the `for` update clause, or null if empty" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.init) this.init._walk(visitor); + if (this.condition) this.condition._walk(visitor); + if (this.step) this.step._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + if (this.step) push(this.step); + if (this.condition) push(this.condition); + if (this.init) push(this.init); + }, +}, AST_IterationStatement); + +var AST_ForIn = DEFNODE("ForIn", "init object", { + $documentation: "A `for ... in` statement", + $propdoc: { + init: "[AST_Node] the `for/in` initialization code", + object: "[AST_Node] the object that we're looping through" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.init._walk(visitor); + this.object._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + if (this.object) push(this.object); + if (this.init) push(this.init); + }, +}, AST_IterationStatement); + +var AST_ForOf = DEFNODE("ForOf", "await", { + $documentation: "A `for ... of` statement", +}, AST_ForIn); + +var AST_With = DEFNODE("With", "expression", { + $documentation: "A `with` statement", + $propdoc: { + expression: "[AST_Node] the `with` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.expression); + }, +}, AST_StatementWithBody); + +/* -----[ scope and functions ]----- */ + +var AST_Scope = DEFNODE("Scope", "variables functions uses_with uses_eval parent_scope enclosed cname", { + $documentation: "Base class for all statements introducing a lexical scope", + $propdoc: { + variables: "[Map/S] a map of name -> SymbolDef for all variables/functions defined in this scope", + uses_with: "[boolean/S] tells whether this scope uses the `with` statement", + uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", + parent_scope: "[AST_Scope?/S] link to the parent scope", + enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", + cname: "[integer/S] current index for mangling variables (used internally by the mangler)", + }, + get_defun_scope: function() { + var self = this; + while (self.is_block_scope()) { + self = self.parent_scope; + } + return self; + }, + clone: function(deep, toplevel) { + var node = this._clone(deep); + if (deep && this.variables && toplevel && !this._block_scope) { + node.figure_out_scope({}, { + toplevel: toplevel, + parent_scope: this.parent_scope + }); + } else { + if (this.variables) node.variables = new Map(this.variables); + if (this.enclosed) node.enclosed = this.enclosed.slice(); + if (this._block_scope) node._block_scope = this._block_scope; + } + return node; + }, + pinned: function() { + return this.uses_eval || this.uses_with; + } +}, AST_Block); + +var AST_Toplevel = DEFNODE("Toplevel", "globals", { + $documentation: "The toplevel scope", + $propdoc: { + globals: "[Map/S] a map of name -> SymbolDef for all undeclared names", + }, + wrap_commonjs: function(name) { + var body = this.body; + var wrapped_tl = "(function(exports){'$ORIG';})(typeof " + name + "=='undefined'?(" + name + "={}):" + name + ");"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function(node) { + if (node instanceof AST_Directive && node.value == "$ORIG") { + return MAP.splice(body); + } + })); + return wrapped_tl; + }, + wrap_enclose: function(args_values) { + if (typeof args_values != "string") args_values = ""; + var index = args_values.indexOf(":"); + if (index < 0) index = args_values.length; + var body = this.body; + return parse([ + "(function(", + args_values.slice(0, index), + '){"$ORIG"})(', + args_values.slice(index + 1), + ")" + ].join("")).transform(new TreeTransformer(function(node) { + if (node instanceof AST_Directive && node.value == "$ORIG") { + return MAP.splice(body); + } + })); + } +}, AST_Scope); + +var AST_Expansion = DEFNODE("Expansion", "expression", { + $documentation: "An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list", + $propdoc: { + expression: "[AST_Node] the thing to be expanded" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression.walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments is_generator async", { + $documentation: "Base class for functions", + $propdoc: { + name: "[AST_SymbolDeclaration?] the name of this function", + argnames: "[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments", + uses_arguments: "[boolean/S] tells whether this function accesses the arguments array", + is_generator: "[boolean] is this a generator method", + async: "[boolean] is this method async", + }, + args_as_names: function () { + var out = []; + for (var i = 0; i < this.argnames.length; i++) { + if (this.argnames[i] instanceof AST_Destructuring) { + out.push(...this.argnames[i].all_symbols()); + } else { + out.push(this.argnames[i]); + } + } + return out; + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.name) this.name._walk(visitor); + var argnames = this.argnames; + for (var i = 0, len = argnames.length; i < len; i++) { + argnames[i]._walk(visitor); + } + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + + i = this.argnames.length; + while (i--) push(this.argnames[i]); + + if (this.name) push(this.name); + }, + is_braceless() { + return this.body[0] instanceof AST_Return && this.body[0].value; + }, + // Default args and expansion don't count, so .argnames.length doesn't cut it + length_property() { + let length = 0; + + for (const arg of this.argnames) { + if (arg instanceof AST_SymbolFunarg || arg instanceof AST_Destructuring) { + length++; + } + } + + return length; + } +}, AST_Scope); + +var AST_Accessor = DEFNODE("Accessor", null, { + $documentation: "A setter/getter function. The `name` property is always null." +}, AST_Lambda); + +var AST_Function = DEFNODE("Function", null, { + $documentation: "A function expression" +}, AST_Lambda); + +var AST_Arrow = DEFNODE("Arrow", null, { + $documentation: "An ES6 Arrow function ((a) => b)" +}, AST_Lambda); + +var AST_Defun = DEFNODE("Defun", null, { + $documentation: "A function definition" +}, AST_Lambda); + +/* -----[ DESTRUCTURING ]----- */ +var AST_Destructuring = DEFNODE("Destructuring", "names is_array", { + $documentation: "A destructuring of several names. Used in destructuring assignment and with destructuring function argument names", + $propdoc: { + "names": "[AST_Node*] Array of properties or elements", + "is_array": "[Boolean] Whether the destructuring represents an object or array" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.names.forEach(function(name) { + name._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.names.length; + while (i--) push(this.names[i]); + }, + all_symbols: function() { + var out = []; + this.walk(new TreeWalker(function (node) { + if (node instanceof AST_Symbol) { + out.push(node); + } + })); + return out; + } +}); + +var AST_PrefixedTemplateString = DEFNODE("PrefixedTemplateString", "template_string prefix", { + $documentation: "A templatestring with a prefix, such as String.raw`foobarbaz`", + $propdoc: { + template_string: "[AST_TemplateString] The template string", + prefix: "[AST_Node] The prefix, which will get called." + }, + _walk: function(visitor) { + return visitor._visit(this, function () { + this.prefix._walk(visitor); + this.template_string._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.template_string); + push(this.prefix); + }, +}); + +var AST_TemplateString = DEFNODE("TemplateString", "segments", { + $documentation: "A template string literal", + $propdoc: { + segments: "[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment." + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.segments.forEach(function(seg) { + seg._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.segments.length; + while (i--) push(this.segments[i]); + } +}); + +var AST_TemplateSegment = DEFNODE("TemplateSegment", "value raw", { + $documentation: "A segment of a template string literal", + $propdoc: { + value: "Content of the segment", + raw: "Raw source of the segment", + } +}); + +/* -----[ JUMPS ]----- */ + +var AST_Jump = DEFNODE("Jump", null, { + $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)" +}, AST_Statement); + +var AST_Exit = DEFNODE("Exit", "value", { + $documentation: "Base class for “exits” (`return` and `throw`)", + $propdoc: { + value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" + }, + _walk: function(visitor) { + return visitor._visit(this, this.value && function() { + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value) push(this.value); + }, +}, AST_Jump); + +var AST_Return = DEFNODE("Return", null, { + $documentation: "A `return` statement" +}, AST_Exit); + +var AST_Throw = DEFNODE("Throw", null, { + $documentation: "A `throw` statement" +}, AST_Exit); + +var AST_LoopControl = DEFNODE("LoopControl", "label", { + $documentation: "Base class for loop control statements (`break` and `continue`)", + $propdoc: { + label: "[AST_LabelRef?] the label, or null if none", + }, + _walk: function(visitor) { + return visitor._visit(this, this.label && function() { + this.label._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.label) push(this.label); + }, +}, AST_Jump); + +var AST_Break = DEFNODE("Break", null, { + $documentation: "A `break` statement" +}, AST_LoopControl); + +var AST_Continue = DEFNODE("Continue", null, { + $documentation: "A `continue` statement" +}, AST_LoopControl); + +var AST_Await = DEFNODE("Await", "expression", { + $documentation: "An `await` statement", + $propdoc: { + expression: "[AST_Node] the mandatory expression being awaited", + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Yield = DEFNODE("Yield", "expression is_star", { + $documentation: "A `yield` statement", + $propdoc: { + expression: "[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false", + is_star: "[Boolean] Whether this is a yield or yield* statement" + }, + _walk: function(visitor) { + return visitor._visit(this, this.expression && function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.expression) push(this.expression); + } +}); + +/* -----[ IF ]----- */ + +var AST_If = DEFNODE("If", "condition alternative", { + $documentation: "A `if` statement", + $propdoc: { + condition: "[AST_Node] the `if` condition", + alternative: "[AST_Statement?] the `else` part, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.body._walk(visitor); + if (this.alternative) this.alternative._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.alternative) { + push(this.alternative); + } + push(this.body); + push(this.condition); + } +}, AST_StatementWithBody); + +/* -----[ SWITCH ]----- */ + +var AST_Switch = DEFNODE("Switch", "expression", { + $documentation: "A `switch` statement", + $propdoc: { + expression: "[AST_Node] the `switch` “discriminant”" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + push(this.expression); + } +}, AST_Block); + +var AST_SwitchBranch = DEFNODE("SwitchBranch", null, { + $documentation: "Base class for `switch` branches", +}, AST_Block); + +var AST_Default = DEFNODE("Default", null, { + $documentation: "A `default` switch branch", +}, AST_SwitchBranch); + +var AST_Case = DEFNODE("Case", "expression", { + $documentation: "A `case` switch branch", + $propdoc: { + expression: "[AST_Node] the `case` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + push(this.expression); + }, +}, AST_SwitchBranch); + +/* -----[ EXCEPTIONS ]----- */ + +var AST_Try = DEFNODE("Try", "bcatch bfinally", { + $documentation: "A `try` statement", + $propdoc: { + bcatch: "[AST_Catch?] the catch block, or null if not present", + bfinally: "[AST_Finally?] the finally block, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + walk_body(this, visitor); + if (this.bcatch) this.bcatch._walk(visitor); + if (this.bfinally) this.bfinally._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.bfinally) push(this.bfinally); + if (this.bcatch) push(this.bcatch); + let i = this.body.length; + while (i--) push(this.body[i]); + }, +}, AST_Block); + +var AST_Catch = DEFNODE("Catch", "argname", { + $documentation: "A `catch` node; only makes sense as part of a `try` statement", + $propdoc: { + argname: "[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.argname) this.argname._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + if (this.argname) push(this.argname); + }, +}, AST_Block); + +var AST_Finally = DEFNODE("Finally", null, { + $documentation: "A `finally` node; only makes sense as part of a `try` statement" +}, AST_Block); + +/* -----[ VAR/CONST ]----- */ + +var AST_Definitions = DEFNODE("Definitions", "definitions", { + $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", + $propdoc: { + definitions: "[AST_VarDef*] array of variable definitions" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var definitions = this.definitions; + for (var i = 0, len = definitions.length; i < len; i++) { + definitions[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.definitions.length; + while (i--) push(this.definitions[i]); + }, +}, AST_Statement); + +var AST_Var = DEFNODE("Var", null, { + $documentation: "A `var` statement" +}, AST_Definitions); + +var AST_Let = DEFNODE("Let", null, { + $documentation: "A `let` statement" +}, AST_Definitions); + +var AST_Const = DEFNODE("Const", null, { + $documentation: "A `const` statement" +}, AST_Definitions); + +var AST_VarDef = DEFNODE("VarDef", "name value", { + $documentation: "A variable declaration; only appears in a AST_Definitions node", + $propdoc: { + name: "[AST_Destructuring|AST_SymbolConst|AST_SymbolLet|AST_SymbolVar] name of the variable", + value: "[AST_Node?] initializer, or null of there's no initializer" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.name._walk(visitor); + if (this.value) this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value) push(this.value); + push(this.name); + }, +}); + +var AST_NameMapping = DEFNODE("NameMapping", "foreign_name name", { + $documentation: "The part of the export/import statement that declare names from a module.", + $propdoc: { + foreign_name: "[AST_SymbolExportForeign|AST_SymbolImportForeign] The name being exported/imported (as specified in the module)", + name: "[AST_SymbolExport|AST_SymbolImport] The name as it is visible to this module." + }, + _walk: function (visitor) { + return visitor._visit(this, function() { + this.foreign_name._walk(visitor); + this.name._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.name); + push(this.foreign_name); + }, +}); + +var AST_Import = DEFNODE("Import", "imported_name imported_names module_name assert_clause", { + $documentation: "An `import` statement", + $propdoc: { + imported_name: "[AST_SymbolImport] The name of the variable holding the module's default export.", + imported_names: "[AST_NameMapping*] The names of non-default imported variables", + module_name: "[AST_String] String literal describing where this module came from", + assert_clause: "[AST_Object?] The import assertion" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.imported_name) { + this.imported_name._walk(visitor); + } + if (this.imported_names) { + this.imported_names.forEach(function(name_import) { + name_import._walk(visitor); + }); + } + this.module_name._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.module_name); + if (this.imported_names) { + let i = this.imported_names.length; + while (i--) push(this.imported_names[i]); + } + if (this.imported_name) push(this.imported_name); + }, +}); + +var AST_ImportMeta = DEFNODE("ImportMeta", null, { + $documentation: "A reference to import.meta", +}); + +var AST_Export = DEFNODE("Export", "exported_definition exported_value is_default exported_names module_name assert_clause", { + $documentation: "An `export` statement", + $propdoc: { + exported_definition: "[AST_Defun|AST_Definitions|AST_DefClass?] An exported definition", + exported_value: "[AST_Node?] An exported value", + exported_names: "[AST_NameMapping*?] List of exported names", + module_name: "[AST_String?] Name of the file to load exports from", + is_default: "[Boolean] Whether this is the default exported value of this module", + assert_clause: "[AST_Object?] The import assertion" + }, + _walk: function (visitor) { + return visitor._visit(this, function () { + if (this.exported_definition) { + this.exported_definition._walk(visitor); + } + if (this.exported_value) { + this.exported_value._walk(visitor); + } + if (this.exported_names) { + this.exported_names.forEach(function(name_export) { + name_export._walk(visitor); + }); + } + if (this.module_name) { + this.module_name._walk(visitor); + } + }); + }, + _children_backwards(push) { + if (this.module_name) push(this.module_name); + if (this.exported_names) { + let i = this.exported_names.length; + while (i--) push(this.exported_names[i]); + } + if (this.exported_value) push(this.exported_value); + if (this.exported_definition) push(this.exported_definition); + } +}, AST_Statement); + +/* -----[ OTHER ]----- */ + +var AST_Call = DEFNODE("Call", "expression args optional _annotations", { + $documentation: "A function call expression", + $propdoc: { + expression: "[AST_Node] expression to invoke as function", + args: "[AST_Node*] array of arguments", + optional: "[boolean] whether this is an optional call (IE ?.() )", + _annotations: "[number] bitfield containing information about the call" + }, + initialize() { + if (this._annotations == null) this._annotations = 0; + }, + _walk(visitor) { + return visitor._visit(this, function() { + var args = this.args; + for (var i = 0, len = args.length; i < len; i++) { + args[i]._walk(visitor); + } + this.expression._walk(visitor); // TODO why do we need to crawl this last? + }); + }, + _children_backwards(push) { + let i = this.args.length; + while (i--) push(this.args[i]); + push(this.expression); + }, +}); + +var AST_New = DEFNODE("New", null, { + $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" +}, AST_Call); + +var AST_Sequence = DEFNODE("Sequence", "expressions", { + $documentation: "A sequence expression (comma-separated expressions)", + $propdoc: { + expressions: "[AST_Node*] array of expressions (at least two)" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expressions.forEach(function(node) { + node._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.expressions.length; + while (i--) push(this.expressions[i]); + }, +}); + +var AST_PropAccess = DEFNODE("PropAccess", "expression property optional", { + $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", + $propdoc: { + expression: "[AST_Node] the “container” expression", + property: "[AST_Node|string] the property to access. For AST_Dot & AST_DotHash this is always a plain string, while for AST_Sub it's an arbitrary AST_Node", + + optional: "[boolean] whether this is an optional property access (IE ?.)" + } +}); + +var AST_Dot = DEFNODE("Dot", "quote", { + $documentation: "A dotted property access expression", + $propdoc: { + quote: "[string] the original quote character when transformed from AST_Sub", + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}, AST_PropAccess); + +var AST_DotHash = DEFNODE("DotHash", "", { + $documentation: "A dotted property access to a private property", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}, AST_PropAccess); + +var AST_Sub = DEFNODE("Sub", null, { + $documentation: "Index-style property access, i.e. `a[\"foo\"]`", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + this.property._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.property); + push(this.expression); + }, +}, AST_PropAccess); + +var AST_Chain = DEFNODE("Chain", "expression", { + $documentation: "A chain expression like a?.b?.(c)?.[d]", + $propdoc: { + expression: "[AST_Call|AST_Dot|AST_DotHash|AST_Sub] chain element." + }, + _walk: function (visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Unary = DEFNODE("Unary", "operator expression", { + $documentation: "Base class for unary expressions", + $propdoc: { + operator: "[string] the operator", + expression: "[AST_Node] expression that this unary operator applies to" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, { + $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" +}, AST_Unary); + +var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, { + $documentation: "Unary postfix expression, i.e. `i++`" +}, AST_Unary); + +var AST_Binary = DEFNODE("Binary", "operator left right", { + $documentation: "Binary expression, i.e. `a + b`", + $propdoc: { + left: "[AST_Node] left-hand side expression", + operator: "[string] the operator", + right: "[AST_Node] right-hand side expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.left._walk(visitor); + this.right._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.right); + push(this.left); + }, +}); + +var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", { + $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", + $propdoc: { + condition: "[AST_Node]", + consequent: "[AST_Node]", + alternative: "[AST_Node]" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.consequent._walk(visitor); + this.alternative._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.alternative); + push(this.consequent); + push(this.condition); + }, +}); + +var AST_Assign = DEFNODE("Assign", "logical", { + $documentation: "An assignment expression — `a = b + 5`", + $propdoc: { + logical: "Whether it's a logical assignment" + } +}, AST_Binary); + +var AST_DefaultAssign = DEFNODE("DefaultAssign", null, { + $documentation: "A default assignment expression like in `(a = 3) => a`" +}, AST_Binary); + +/* -----[ LITERALS ]----- */ + +var AST_Array = DEFNODE("Array", "elements", { + $documentation: "An array literal", + $propdoc: { + elements: "[AST_Node*] array of elements" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var elements = this.elements; + for (var i = 0, len = elements.length; i < len; i++) { + elements[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.elements.length; + while (i--) push(this.elements[i]); + }, +}); + +var AST_Object = DEFNODE("Object", "properties", { + $documentation: "An object literal", + $propdoc: { + properties: "[AST_ObjectProperty*] array of properties" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var properties = this.properties; + for (var i = 0, len = properties.length; i < len; i++) { + properties[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.properties.length; + while (i--) push(this.properties[i]); + }, +}); + +var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { + $documentation: "Base class for literal object properties", + $propdoc: { + key: "[string|AST_Node] property name. For ObjectKeyVal this is a string. For getters, setters and computed property this is an AST_Node.", + value: "[AST_Node] property value. For getters and setters this is an AST_Accessor." + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.key instanceof AST_Node) + this.key._walk(visitor); + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.value); + if (this.key instanceof AST_Node) push(this.key); + } +}); + +var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", { + $documentation: "A key: value object property", + $propdoc: { + quote: "[string] the original quote character" + }, + computed_key() { + return this.key instanceof AST_Node; + } +}, AST_ObjectProperty); + +var AST_PrivateSetter = DEFNODE("PrivateSetter", "static", { + $propdoc: { + static: "[boolean] whether this is a static private setter" + }, + $documentation: "A private setter property", + computed_key() { + return false; + } +}, AST_ObjectProperty); + +var AST_PrivateGetter = DEFNODE("PrivateGetter", "static", { + $propdoc: { + static: "[boolean] whether this is a static private getter" + }, + $documentation: "A private getter property", + computed_key() { + return false; + } +}, AST_ObjectProperty); + +var AST_ObjectSetter = DEFNODE("ObjectSetter", "quote static", { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] whether this is a static setter (classes only)" + }, + $documentation: "An object setter property", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } +}, AST_ObjectProperty); + +var AST_ObjectGetter = DEFNODE("ObjectGetter", "quote static", { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] whether this is a static getter (classes only)" + }, + $documentation: "An object getter property", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } +}, AST_ObjectProperty); + +var AST_ConciseMethod = DEFNODE("ConciseMethod", "quote static is_generator async", { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] is this method static (classes only)", + is_generator: "[boolean] is this a generator method", + async: "[boolean] is this method async", + }, + $documentation: "An ES6 concise method inside an object or class", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } +}, AST_ObjectProperty); + +var AST_PrivateMethod = DEFNODE("PrivateMethod", "", { + $documentation: "A private class method inside a class", +}, AST_ConciseMethod); + +var AST_Class = DEFNODE("Class", "name extends properties", { + $propdoc: { + name: "[AST_SymbolClass|AST_SymbolDefClass?] optional class name.", + extends: "[AST_Node]? optional parent class", + properties: "[AST_ObjectProperty*] array of properties" + }, + $documentation: "An ES6 class", + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.name) { + this.name._walk(visitor); + } + if (this.extends) { + this.extends._walk(visitor); + } + this.properties.forEach((prop) => prop._walk(visitor)); + }); + }, + _children_backwards(push) { + let i = this.properties.length; + while (i--) push(this.properties[i]); + if (this.extends) push(this.extends); + if (this.name) push(this.name); + }, +}, AST_Scope /* TODO a class might have a scope but it's not a scope */); + +var AST_ClassProperty = DEFNODE("ClassProperty", "static quote", { + $documentation: "A class property", + $propdoc: { + static: "[boolean] whether this is a static key", + quote: "[string] which quote is being used" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.key instanceof AST_Node) + this.key._walk(visitor); + if (this.value instanceof AST_Node) + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value instanceof AST_Node) push(this.value); + if (this.key instanceof AST_Node) push(this.key); + }, + computed_key() { + return !(this.key instanceof AST_SymbolClassProperty); + } +}, AST_ObjectProperty); + +var AST_ClassPrivateProperty = DEFNODE("ClassPrivateProperty", "", { + $documentation: "A class property for a private property", +}, AST_ClassProperty); + +var AST_DefClass = DEFNODE("DefClass", null, { + $documentation: "A class definition", +}, AST_Class); + +var AST_ClassExpression = DEFNODE("ClassExpression", null, { + $documentation: "A class expression." +}, AST_Class); + +var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { + $propdoc: { + name: "[string] name of this symbol", + scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", + thedef: "[SymbolDef/S] the definition of this symbol" + }, + $documentation: "Base class for all symbols" +}); + +var AST_NewTarget = DEFNODE("NewTarget", null, { + $documentation: "A reference to new.target" +}); + +var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { + $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", +}, AST_Symbol); + +var AST_SymbolVar = DEFNODE("SymbolVar", null, { + $documentation: "Symbol defining a variable", +}, AST_SymbolDeclaration); + +var AST_SymbolBlockDeclaration = DEFNODE("SymbolBlockDeclaration", null, { + $documentation: "Base class for block-scoped declaration symbols" +}, AST_SymbolDeclaration); + +var AST_SymbolConst = DEFNODE("SymbolConst", null, { + $documentation: "A constant declaration" +}, AST_SymbolBlockDeclaration); + +var AST_SymbolLet = DEFNODE("SymbolLet", null, { + $documentation: "A block-scoped `let` declaration" +}, AST_SymbolBlockDeclaration); + +var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, { + $documentation: "Symbol naming a function argument", +}, AST_SymbolVar); + +var AST_SymbolDefun = DEFNODE("SymbolDefun", null, { + $documentation: "Symbol defining a function", +}, AST_SymbolDeclaration); + +var AST_SymbolMethod = DEFNODE("SymbolMethod", null, { + $documentation: "Symbol in an object defining a method", +}, AST_Symbol); + +var AST_SymbolClassProperty = DEFNODE("SymbolClassProperty", null, { + $documentation: "Symbol for a class property", +}, AST_Symbol); + +var AST_SymbolLambda = DEFNODE("SymbolLambda", null, { + $documentation: "Symbol naming a function expression", +}, AST_SymbolDeclaration); + +var AST_SymbolDefClass = DEFNODE("SymbolDefClass", null, { + $documentation: "Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class." +}, AST_SymbolBlockDeclaration); + +var AST_SymbolClass = DEFNODE("SymbolClass", null, { + $documentation: "Symbol naming a class's name. Lexically scoped to the class." +}, AST_SymbolDeclaration); + +var AST_SymbolCatch = DEFNODE("SymbolCatch", null, { + $documentation: "Symbol naming the exception in catch", +}, AST_SymbolBlockDeclaration); + +var AST_SymbolImport = DEFNODE("SymbolImport", null, { + $documentation: "Symbol referring to an imported name", +}, AST_SymbolBlockDeclaration); + +var AST_SymbolImportForeign = DEFNODE("SymbolImportForeign", null, { + $documentation: "A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes", +}, AST_Symbol); + +var AST_Label = DEFNODE("Label", "references", { + $documentation: "Symbol naming a label (declaration)", + $propdoc: { + references: "[AST_LoopControl*] a list of nodes referring to this label" + }, + initialize: function() { + this.references = []; + this.thedef = this; + } +}, AST_Symbol); + +var AST_SymbolRef = DEFNODE("SymbolRef", null, { + $documentation: "Reference to some symbol (not definition/declaration)", +}, AST_Symbol); + +var AST_SymbolExport = DEFNODE("SymbolExport", null, { + $documentation: "Symbol referring to a name to export", +}, AST_SymbolRef); + +var AST_SymbolExportForeign = DEFNODE("SymbolExportForeign", null, { + $documentation: "A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes", +}, AST_Symbol); + +var AST_LabelRef = DEFNODE("LabelRef", null, { + $documentation: "Reference to a label symbol", +}, AST_Symbol); + +var AST_This = DEFNODE("This", null, { + $documentation: "The `this` symbol", +}, AST_Symbol); + +var AST_Super = DEFNODE("Super", null, { + $documentation: "The `super` symbol", +}, AST_This); + +var AST_Constant = DEFNODE("Constant", null, { + $documentation: "Base class for all constants", + getValue: function() { + return this.value; + } +}); + +var AST_String = DEFNODE("String", "value quote", { + $documentation: "A string literal", + $propdoc: { + value: "[string] the contents of this string", + quote: "[string] the original quote character" + } +}, AST_Constant); + +var AST_Number = DEFNODE("Number", "value raw", { + $documentation: "A number literal", + $propdoc: { + value: "[number] the numeric value", + raw: "[string] numeric value as string" + } +}, AST_Constant); + +var AST_BigInt = DEFNODE("BigInt", "value", { + $documentation: "A big int literal", + $propdoc: { + value: "[string] big int value" + } +}, AST_Constant); + +var AST_RegExp = DEFNODE("RegExp", "value", { + $documentation: "A regexp literal", + $propdoc: { + value: "[RegExp] the actual regexp", + } +}, AST_Constant); + +var AST_Atom = DEFNODE("Atom", null, { + $documentation: "Base class for atoms", +}, AST_Constant); + +var AST_Null = DEFNODE("Null", null, { + $documentation: "The `null` atom", + value: null +}, AST_Atom); + +var AST_NaN = DEFNODE("NaN", null, { + $documentation: "The impossible value", + value: 0/0 +}, AST_Atom); + +var AST_Undefined = DEFNODE("Undefined", null, { + $documentation: "The `undefined` value", + value: (function() {}()) +}, AST_Atom); + +var AST_Hole = DEFNODE("Hole", null, { + $documentation: "A hole in an array", + value: (function() {}()) +}, AST_Atom); + +var AST_Infinity = DEFNODE("Infinity", null, { + $documentation: "The `Infinity` value", + value: 1/0 +}, AST_Atom); + +var AST_Boolean = DEFNODE("Boolean", null, { + $documentation: "Base class for booleans", +}, AST_Atom); + +var AST_False = DEFNODE("False", null, { + $documentation: "The `false` atom", + value: false +}, AST_Boolean); + +var AST_True = DEFNODE("True", null, { + $documentation: "The `true` atom", + value: true +}, AST_Boolean); + +/* -----[ Walk function ]---- */ + +/** + * Walk nodes in depth-first search fashion. + * Callback can return `walk_abort` symbol to stop iteration. + * It can also return `true` to stop iteration just for child nodes. + * Iteration can be stopped and continued by passing the `to_visit` argument, + * which is given to the callback in the second argument. + **/ +function walk(node, cb, to_visit = [node]) { + const push = to_visit.push.bind(to_visit); + while (to_visit.length) { + const node = to_visit.pop(); + const ret = cb(node, to_visit); + + if (ret) { + if (ret === walk_abort) return true; + continue; + } + + node._children_backwards(push); + } + return false; +} + +function walk_parent(node, cb, initial_stack) { + const to_visit = [node]; + const push = to_visit.push.bind(to_visit); + const stack = initial_stack ? initial_stack.slice() : []; + const parent_pop_indices = []; + + let current; + + const info = { + parent: (n = 0) => { + if (n === -1) { + return current; + } + + // [ p1 p0 ] [ 1 0 ] + if (initial_stack && n >= stack.length) { + n -= stack.length; + return initial_stack[ + initial_stack.length - (n + 1) + ]; + } + + return stack[stack.length - (1 + n)]; + }, + }; + + while (to_visit.length) { + current = to_visit.pop(); + + while ( + parent_pop_indices.length && + to_visit.length == parent_pop_indices[parent_pop_indices.length - 1] + ) { + stack.pop(); + parent_pop_indices.pop(); + } + + const ret = cb(current, info); + + if (ret) { + if (ret === walk_abort) return true; + continue; + } + + const visit_length = to_visit.length; + + current._children_backwards(push); + + // Push only if we're going to traverse the children + if (to_visit.length > visit_length) { + stack.push(current); + parent_pop_indices.push(visit_length - 1); + } + } + + return false; +} + +const walk_abort = Symbol("abort walk"); + +/* -----[ TreeWalker ]----- */ + +class TreeWalker { + constructor(callback) { + this.visit = callback; + this.stack = []; + this.directives = Object.create(null); + } + + _visit(node, descend) { + this.push(node); + var ret = this.visit(node, descend ? function() { + descend.call(node); + } : noop); + if (!ret && descend) { + descend.call(node); + } + this.pop(); + return ret; + } + + parent(n) { + return this.stack[this.stack.length - 2 - (n || 0)]; + } + + push(node) { + if (node instanceof AST_Lambda) { + this.directives = Object.create(this.directives); + } else if (node instanceof AST_Directive && !this.directives[node.value]) { + this.directives[node.value] = node; + } else if (node instanceof AST_Class) { + this.directives = Object.create(this.directives); + if (!this.directives["use strict"]) { + this.directives["use strict"] = node; + } + } + this.stack.push(node); + } + + pop() { + var node = this.stack.pop(); + if (node instanceof AST_Lambda || node instanceof AST_Class) { + this.directives = Object.getPrototypeOf(this.directives); + } + } + + self() { + return this.stack[this.stack.length - 1]; + } + + find_parent(type) { + var stack = this.stack; + for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof type) return x; + } + } + + has_directive(type) { + var dir = this.directives[type]; + if (dir) return dir; + var node = this.stack[this.stack.length - 1]; + if (node instanceof AST_Scope && node.body) { + for (var i = 0; i < node.body.length; ++i) { + var st = node.body[i]; + if (!(st instanceof AST_Directive)) break; + if (st.value == type) return st; + } + } + } + + loopcontrol_target(node) { + var stack = this.stack; + if (node.label) for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_LabeledStatement && x.label.name == node.label.name) + return x.body; + } else for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_IterationStatement + || node instanceof AST_Break && x instanceof AST_Switch) + return x; + } + } +} + +// Tree transformer helpers. +class TreeTransformer extends TreeWalker { + constructor(before, after) { + super(); + this.before = before; + this.after = after; + } +} + +const _PURE = 0b00000001; +const _INLINE = 0b00000010; +const _NOINLINE = 0b00000100; + +export { + AST_Accessor, + AST_Array, + AST_Arrow, + AST_Assign, + AST_Atom, + AST_Await, + AST_BigInt, + AST_Binary, + AST_Block, + AST_BlockStatement, + AST_Boolean, + AST_Break, + AST_Call, + AST_Case, + AST_Catch, + AST_Chain, + AST_Class, + AST_ClassExpression, + AST_ClassPrivateProperty, + AST_ClassProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Const, + AST_Constant, + AST_Continue, + AST_Debugger, + AST_Default, + AST_DefaultAssign, + AST_DefClass, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DotHash, + AST_DWLoop, + AST_EmptyStatement, + AST_Exit, + AST_Expansion, + AST_Export, + AST_False, + AST_Finally, + AST_For, + AST_ForIn, + AST_ForOf, + AST_Function, + AST_Hole, + AST_If, + AST_Import, + AST_ImportMeta, + AST_Infinity, + AST_IterationStatement, + AST_Jump, + AST_Label, + AST_LabeledStatement, + AST_LabelRef, + AST_Lambda, + AST_Let, + AST_LoopControl, + AST_NameMapping, + AST_NaN, + AST_New, + AST_NewTarget, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PrefixedTemplateString, + AST_PrivateGetter, + AST_PrivateMethod, + AST_PrivateSetter, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_StatementWithBody, + AST_String, + AST_Sub, + AST_Super, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_SymbolBlockDeclaration, + AST_SymbolCatch, + AST_SymbolClass, + AST_SymbolClassProperty, + AST_SymbolConst, + AST_SymbolDeclaration, + AST_SymbolDefClass, + AST_SymbolDefun, + AST_SymbolExport, + AST_SymbolExportForeign, + AST_SymbolFunarg, + AST_SymbolImport, + AST_SymbolImportForeign, + AST_SymbolLambda, + AST_SymbolLet, + AST_SymbolMethod, + AST_SymbolRef, + AST_SymbolVar, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Throw, + AST_Token, + AST_Toplevel, + AST_True, + AST_Try, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Undefined, + AST_Var, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, + + // Walkers + TreeTransformer, + TreeWalker, + walk, + walk_abort, + walk_body, + walk_parent, + + // annotations + _INLINE, + _NOINLINE, + _PURE, +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/cli.js b/node_modules/mathjs/examples/node_modules/terser/lib/cli.js new file mode 100644 index 0000000..1929813 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/cli.js @@ -0,0 +1,479 @@ +import { minify, _default_options } from "../main.js"; +import { parse } from "./parse.js"; +import { + AST_Assign, + AST_Array, + AST_Constant, + AST_Node, + AST_PropAccess, + AST_RegExp, + AST_Sequence, + AST_Symbol, + AST_Token, + walk +} from "./ast.js"; +import { OutputStream } from "./output.js"; + +export async function run_cli({ program, packageJson, fs, path }) { + const skip_keys = new Set([ "cname", "parent_scope", "scope", "uses_eval", "uses_with" ]); + var files = {}; + var options = { + compress: false, + mangle: false + }; + const default_options = await _default_options(); + program.version(packageJson.name + " " + packageJson.version); + program.parseArgv = program.parse; + program.parse = undefined; + + if (process.argv.includes("ast")) program.helpInformation = describe_ast; + else if (process.argv.includes("options")) program.helpInformation = function() { + var text = []; + for (var option in default_options) { + text.push("--" + (option === "sourceMap" ? "source-map" : option) + " options:"); + text.push(format_object(default_options[option])); + text.push(""); + } + return text.join("\n"); + }; + + program.option("-p, --parse ", "Specify parser options.", parse_js()); + program.option("-c, --compress [options]", "Enable compressor/specify compressor options.", parse_js()); + program.option("-m, --mangle [options]", "Mangle names/specify mangler options.", parse_js()); + program.option("--mangle-props [options]", "Mangle properties/specify mangler options.", parse_js()); + program.option("-f, --format [options]", "Format options.", parse_js()); + program.option("-b, --beautify [options]", "Alias for --format.", parse_js()); + program.option("-o, --output ", "Output file (default STDOUT)."); + program.option("--comments [filter]", "Preserve copyright comments in the output."); + program.option("--config-file ", "Read minify() options from JSON file."); + program.option("-d, --define [=value]", "Global definitions.", parse_js("define")); + program.option("--ecma ", "Specify ECMAScript release: 5, 2015, 2016 or 2017..."); + program.option("-e, --enclose [arg[,...][:value[,...]]]", "Embed output in a big function with configurable arguments and values."); + program.option("--ie8", "Support non-standard Internet Explorer 8."); + program.option("--keep-classnames", "Do not mangle/drop class names."); + program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name."); + program.option("--module", "Input is an ES6 module"); + program.option("--name-cache ", "File to hold mangled name mappings."); + program.option("--rename", "Force symbol expansion."); + program.option("--no-rename", "Disable symbol expansion."); + program.option("--safari10", "Support non-standard Safari 10."); + program.option("--source-map [options]", "Enable source map/specify source map options.", parse_js()); + program.option("--timings", "Display operations run time on STDERR."); + program.option("--toplevel", "Compress and/or mangle variables in toplevel scope."); + program.option("--wrap ", "Embed everything as a function with “exports” corresponding to “name” globally."); + program.arguments("[files...]").parseArgv(process.argv); + if (program.configFile) { + options = JSON.parse(read_file(program.configFile)); + } + if (!program.output && program.sourceMap && program.sourceMap.url != "inline") { + fatal("ERROR: cannot write source map to STDOUT"); + } + + [ + "compress", + "enclose", + "ie8", + "mangle", + "module", + "safari10", + "sourceMap", + "toplevel", + "wrap" + ].forEach(function(name) { + if (name in program) { + options[name] = program[name]; + } + }); + + if ("ecma" in program) { + if (program.ecma != (program.ecma | 0)) fatal("ERROR: ecma must be an integer"); + const ecma = program.ecma | 0; + if (ecma > 5 && ecma < 2015) + options.ecma = ecma + 2009; + else + options.ecma = ecma; + } + if (program.format || program.beautify) { + const chosenOption = program.format || program.beautify; + options.format = typeof chosenOption === "object" ? chosenOption : {}; + } + if (program.comments) { + if (typeof options.format != "object") options.format = {}; + options.format.comments = typeof program.comments == "string" ? (program.comments == "false" ? false : program.comments) : "some"; + } + if (program.define) { + if (typeof options.compress != "object") options.compress = {}; + if (typeof options.compress.global_defs != "object") options.compress.global_defs = {}; + for (var expr in program.define) { + options.compress.global_defs[expr] = program.define[expr]; + } + } + if (program.keepClassnames) { + options.keep_classnames = true; + } + if (program.keepFnames) { + options.keep_fnames = true; + } + if (program.mangleProps) { + if (program.mangleProps.domprops) { + delete program.mangleProps.domprops; + } else { + if (typeof program.mangleProps != "object") program.mangleProps = {}; + if (!Array.isArray(program.mangleProps.reserved)) program.mangleProps.reserved = []; + } + if (typeof options.mangle != "object") options.mangle = {}; + options.mangle.properties = program.mangleProps; + } + if (program.nameCache) { + options.nameCache = JSON.parse(read_file(program.nameCache, "{}")); + } + if (program.output == "ast") { + options.format = { + ast: true, + code: false + }; + } + if (program.parse) { + if (!program.parse.acorn && !program.parse.spidermonkey) { + options.parse = program.parse; + } else if (program.sourceMap && program.sourceMap.content == "inline") { + fatal("ERROR: inline source map only works with built-in parser"); + } + } + if (~program.rawArgs.indexOf("--rename")) { + options.rename = true; + } else if (!program.rename) { + options.rename = false; + } + + let convert_path = name => name; + if (typeof program.sourceMap == "object" && "base" in program.sourceMap) { + convert_path = function() { + var base = program.sourceMap.base; + delete options.sourceMap.base; + return function(name) { + return path.relative(base, name); + }; + }(); + } + + let filesList; + if (options.files && options.files.length) { + filesList = options.files; + + delete options.files; + } else if (program.args.length) { + filesList = program.args; + } + + if (filesList) { + simple_glob(filesList).forEach(function(name) { + files[convert_path(name)] = read_file(name); + }); + } else { + await new Promise((resolve) => { + var chunks = []; + process.stdin.setEncoding("utf8"); + process.stdin.on("data", function(chunk) { + chunks.push(chunk); + }).on("end", function() { + files = [ chunks.join("") ]; + resolve(); + }); + process.stdin.resume(); + }); + } + + await run_cli(); + + function convert_ast(fn) { + return AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null)); + } + + async function run_cli() { + var content = program.sourceMap && program.sourceMap.content; + if (content && content !== "inline") { + options.sourceMap.content = read_file(content, content); + } + if (program.timings) options.timings = true; + + try { + if (program.parse) { + if (program.parse.acorn) { + files = convert_ast(function(toplevel, name) { + return require("acorn").parse(files[name], { + ecmaVersion: 2018, + locations: true, + program: toplevel, + sourceFile: name, + sourceType: options.module || program.parse.module ? "module" : "script" + }); + }); + } else if (program.parse.spidermonkey) { + files = convert_ast(function(toplevel, name) { + var obj = JSON.parse(files[name]); + if (!toplevel) return obj; + toplevel.body = toplevel.body.concat(obj.body); + return toplevel; + }); + } + } + } catch (ex) { + fatal(ex); + } + + let result; + try { + result = await minify(files, options, fs); + } catch (ex) { + if (ex.name == "SyntaxError") { + print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col); + var col = ex.col; + var lines = files[ex.filename].split(/\r?\n/); + var line = lines[ex.line - 1]; + if (!line && !col) { + line = lines[ex.line - 2]; + col = line.length; + } + if (line) { + var limit = 70; + if (col > limit) { + line = line.slice(col - limit); + col = limit; + } + print_error(line.slice(0, 80)); + print_error(line.slice(0, col).replace(/\S/g, " ") + "^"); + } + } + if (ex.defs) { + print_error("Supported options:"); + print_error(format_object(ex.defs)); + } + fatal(ex); + return; + } + + if (program.output == "ast") { + if (!options.compress && !options.mangle) { + result.ast.figure_out_scope({}); + } + console.log(JSON.stringify(result.ast, function(key, value) { + if (value) switch (key) { + case "thedef": + return symdef(value); + case "enclosed": + return value.length ? value.map(symdef) : undefined; + case "variables": + case "globals": + return value.size ? collect_from_map(value, symdef) : undefined; + } + if (skip_keys.has(key)) return; + if (value instanceof AST_Token) return; + if (value instanceof Map) return; + if (value instanceof AST_Node) { + var result = { + _class: "AST_" + value.TYPE + }; + if (value.block_scope) { + result.variables = value.block_scope.variables; + result.enclosed = value.block_scope.enclosed; + } + value.CTOR.PROPS.forEach(function(prop) { + result[prop] = value[prop]; + }); + return result; + } + return value; + }, 2)); + } else if (program.output == "spidermonkey") { + try { + const minified = await minify( + result.code, + { + compress: false, + mangle: false, + format: { + ast: true, + code: false + } + }, + fs + ); + console.log(JSON.stringify(minified.ast.to_mozilla_ast(), null, 2)); + } catch (ex) { + fatal(ex); + return; + } + } else if (program.output) { + fs.writeFileSync(program.output, result.code); + if (options.sourceMap && options.sourceMap.url !== "inline" && result.map) { + fs.writeFileSync(program.output + ".map", result.map); + } + } else { + console.log(result.code); + } + if (program.nameCache) { + fs.writeFileSync(program.nameCache, JSON.stringify(options.nameCache)); + } + if (result.timings) for (var phase in result.timings) { + print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s"); + } + } + + function fatal(message) { + if (message instanceof Error) message = message.stack.replace(/^\S*?Error:/, "ERROR:"); + print_error(message); + process.exit(1); + } + + // A file glob function that only supports "*" and "?" wildcards in the basename. + // Example: "foo/bar/*baz??.*.js" + // Argument `glob` may be a string or an array of strings. + // Returns an array of strings. Garbage in, garbage out. + function simple_glob(glob) { + if (Array.isArray(glob)) { + return [].concat.apply([], glob.map(simple_glob)); + } + if (glob && glob.match(/[*?]/)) { + var dir = path.dirname(glob); + try { + var entries = fs.readdirSync(dir); + } catch (ex) {} + if (entries) { + var pattern = "^" + path.basename(glob) + .replace(/[.+^$[\]\\(){}]/g, "\\$&") + .replace(/\*/g, "[^/\\\\]*") + .replace(/\?/g, "[^/\\\\]") + "$"; + var mod = process.platform === "win32" ? "i" : ""; + var rx = new RegExp(pattern, mod); + var results = entries.filter(function(name) { + return rx.test(name); + }).map(function(name) { + return path.join(dir, name); + }); + if (results.length) return results; + } + } + return [ glob ]; + } + + function read_file(path, default_value) { + try { + return fs.readFileSync(path, "utf8"); + } catch (ex) { + if ((ex.code == "ENOENT" || ex.code == "ENAMETOOLONG") && default_value != null) return default_value; + fatal(ex); + } + } + + function parse_js(flag) { + return function(value, options) { + options = options || {}; + try { + walk(parse(value, { expression: true }), node => { + if (node instanceof AST_Assign) { + var name = node.left.print_to_string(); + var value = node.right; + if (flag) { + options[name] = value; + } else if (value instanceof AST_Array) { + options[name] = value.elements.map(to_string); + } else if (value instanceof AST_RegExp) { + value = value.value; + options[name] = new RegExp(value.source, value.flags); + } else { + options[name] = to_string(value); + } + return true; + } + if (node instanceof AST_Symbol || node instanceof AST_PropAccess) { + var name = node.print_to_string(); + options[name] = true; + return true; + } + if (!(node instanceof AST_Sequence)) throw node; + + function to_string(value) { + return value instanceof AST_Constant ? value.getValue() : value.print_to_string({ + quote_keys: true + }); + } + }); + } catch(ex) { + if (flag) { + fatal("Error parsing arguments for '" + flag + "': " + value); + } else { + options[value] = null; + } + } + return options; + }; + } + + function symdef(def) { + var ret = (1e6 + def.id) + " " + def.name; + if (def.mangled_name) ret += " " + def.mangled_name; + return ret; + } + + function collect_from_map(map, callback) { + var result = []; + map.forEach(function (def) { + result.push(callback(def)); + }); + return result; + } + + function format_object(obj) { + var lines = []; + var padding = ""; + Object.keys(obj).map(function(name) { + if (padding.length < name.length) padding = Array(name.length + 1).join(" "); + return [ name, JSON.stringify(obj[name]) ]; + }).forEach(function(tokens) { + lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]); + }); + return lines.join("\n"); + } + + function print_error(msg) { + process.stderr.write(msg); + process.stderr.write("\n"); + } + + function describe_ast() { + var out = OutputStream({ beautify: true }); + function doitem(ctor) { + out.print("AST_" + ctor.TYPE); + const props = ctor.SELF_PROPS.filter(prop => !/^\$/.test(prop)); + + if (props.length > 0) { + out.space(); + out.with_parens(function() { + props.forEach(function(prop, i) { + if (i) out.space(); + out.print(prop); + }); + }); + } + + if (ctor.documentation) { + out.space(); + out.print_string(ctor.documentation); + } + + if (ctor.SUBCLASSES.length > 0) { + out.space(); + out.with_block(function() { + ctor.SUBCLASSES.forEach(function(ctor) { + out.indent(); + doitem(ctor); + out.newline(); + }); + }); + } + } + doitem(AST_Node); + return out + "\n"; + } +} diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/compress/common.js b/node_modules/mathjs/examples/node_modules/terser/lib/compress/common.js new file mode 100644 index 0000000..75b12d2 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/compress/common.js @@ -0,0 +1,296 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Array, + AST_Arrow, + AST_BlockStatement, + AST_Call, + AST_Class, + AST_Const, + AST_Constant, + AST_DefClass, + AST_Defun, + AST_EmptyStatement, + AST_Export, + AST_False, + AST_Function, + AST_Import, + AST_Infinity, + AST_LabeledStatement, + AST_Lambda, + AST_Let, + AST_LoopControl, + AST_NaN, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectKeyVal, + AST_PropAccess, + AST_RegExp, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_String, + AST_SymbolRef, + AST_True, + AST_UnaryPrefix, + AST_Undefined, + + TreeWalker, +} from "../ast.js"; +import { make_node, regexp_source_fix, string_template, makePredicate } from "../utils/index.js"; +import { first_in_statement } from "../utils/first_in_statement.js"; + +export function merge_sequence(array, node) { + if (node instanceof AST_Sequence) { + array.push(...node.expressions); + } else { + array.push(node); + } + return array; +} + +export function make_sequence(orig, expressions) { + if (expressions.length == 1) return expressions[0]; + if (expressions.length == 0) throw new Error("trying to create a sequence with length zero!"); + return make_node(AST_Sequence, orig, { + expressions: expressions.reduce(merge_sequence, []) + }); +} + +export function make_node_from_constant(val, orig) { + switch (typeof val) { + case "string": + return make_node(AST_String, orig, { + value: val + }); + case "number": + if (isNaN(val)) return make_node(AST_NaN, orig); + if (isFinite(val)) { + return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Number, orig, { value: -val }) + }) : make_node(AST_Number, orig, { value: val }); + } + return val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Infinity, orig) + }) : make_node(AST_Infinity, orig); + case "boolean": + return make_node(val ? AST_True : AST_False, orig); + case "undefined": + return make_node(AST_Undefined, orig); + default: + if (val === null) { + return make_node(AST_Null, orig, { value: null }); + } + if (val instanceof RegExp) { + return make_node(AST_RegExp, orig, { + value: { + source: regexp_source_fix(val.source), + flags: val.flags + } + }); + } + throw new Error(string_template("Can't handle constant of type: {type}", { + type: typeof val + })); + } +} + +export function best_of_expression(ast1, ast2) { + return ast1.size() > ast2.size() ? ast2 : ast1; +} + +export function best_of_statement(ast1, ast2) { + return best_of_expression( + make_node(AST_SimpleStatement, ast1, { + body: ast1 + }), + make_node(AST_SimpleStatement, ast2, { + body: ast2 + }) + ).body; +} + +/** Find which node is smaller, and return that */ +export function best_of(compressor, ast1, ast2) { + if (first_in_statement(compressor)) { + return best_of_statement(ast1, ast2); + } else { + return best_of_expression(ast1, ast2); + } +} + +/** Simplify an object property's key, if possible */ +export function get_simple_key(key) { + if (key instanceof AST_Constant) { + return key.getValue(); + } + if (key instanceof AST_UnaryPrefix + && key.operator == "void" + && key.expression instanceof AST_Constant) { + return; + } + return key; +} + +export function read_property(obj, key) { + key = get_simple_key(key); + if (key instanceof AST_Node) return; + + var value; + if (obj instanceof AST_Array) { + var elements = obj.elements; + if (key == "length") return make_node_from_constant(elements.length, obj); + if (typeof key == "number" && key in elements) value = elements[key]; + } else if (obj instanceof AST_Object) { + key = "" + key; + var props = obj.properties; + for (var i = props.length; --i >= 0;) { + var prop = props[i]; + if (!(prop instanceof AST_ObjectKeyVal)) return; + if (!value && props[i].key === key) value = props[i].value; + } + } + + return value instanceof AST_SymbolRef && value.fixed_value() || value; +} + +export function has_break_or_continue(loop, parent) { + var found = false; + var tw = new TreeWalker(function(node) { + if (found || node instanceof AST_Scope) return true; + if (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === loop) { + return found = true; + } + }); + if (parent instanceof AST_LabeledStatement) tw.push(parent); + tw.push(loop); + loop.body.walk(tw); + return found; +} + +// we shouldn't compress (1,func)(something) to +// func(something) because that changes the meaning of +// the func (becomes lexical instead of global). +export function maintain_this_binding(parent, orig, val) { + if ( + parent instanceof AST_UnaryPrefix && parent.operator == "delete" + || parent instanceof AST_Call && parent.expression === orig + && ( + val instanceof AST_PropAccess + || val instanceof AST_SymbolRef && val.name == "eval" + ) + ) { + const zero = make_node(AST_Number, orig, { value: 0 }); + return make_sequence(orig, [ zero, val ]); + } else { + return val; + } +} + +export function is_func_expr(node) { + return node instanceof AST_Arrow || node instanceof AST_Function; +} + +export function is_iife_call(node) { + // Used to determine whether the node can benefit from negation. + // Not the case with arrow functions (you need an extra set of parens). + if (node.TYPE != "Call") return false; + return node.expression instanceof AST_Function || is_iife_call(node.expression); +} + +export const identifier_atom = makePredicate("Infinity NaN undefined"); +export function is_identifier_atom(node) { + return node instanceof AST_Infinity + || node instanceof AST_NaN + || node instanceof AST_Undefined; +} + +/** Check if this is a SymbolRef node which has one def of a certain AST type */ +export function is_ref_of(ref, type) { + if (!(ref instanceof AST_SymbolRef)) return false; + var orig = ref.definition().orig; + for (var i = orig.length; --i >= 0;) { + if (orig[i] instanceof type) return true; + } +} + +// Can we turn { block contents... } into just the block contents ? +// Not if one of these is inside. +export function can_be_evicted_from_block(node) { + return !( + node instanceof AST_DefClass || + node instanceof AST_Defun || + node instanceof AST_Let || + node instanceof AST_Const || + node instanceof AST_Export || + node instanceof AST_Import + ); +} + +export function as_statement_array(thing) { + if (thing === null) return []; + if (thing instanceof AST_BlockStatement) return thing.body; + if (thing instanceof AST_EmptyStatement) return []; + if (thing instanceof AST_Statement) return [ thing ]; + throw new Error("Can't convert thing to statement array"); +} + +/** Check if a ref refers to the name of a function/class it's defined within */ +export function is_recursive_ref(compressor, def) { + var node; + for (var i = 0; node = compressor.parent(i); i++) { + if (node instanceof AST_Lambda || node instanceof AST_Class) { + var name = node.name; + if (name && name.definition() === def) { + return true; + } + } + } + return false; +} diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/compress/compressor-flags.js b/node_modules/mathjs/examples/node_modules/terser/lib/compress/compressor-flags.js new file mode 100644 index 0000000..1341658 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/compress/compressor-flags.js @@ -0,0 +1,63 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +// bitfield flags to be stored in node.flags. +// These are set and unset during compression, and store information in the node without requiring multiple fields. +export const UNUSED = 0b00000001; +export const TRUTHY = 0b00000010; +export const FALSY = 0b00000100; +export const UNDEFINED = 0b00001000; +export const INLINED = 0b00010000; + +// Nodes to which values are ever written. Used when keep_assign is part of the unused option string. +export const WRITE_ONLY = 0b00100000; + +// information specific to a single compression pass +export const SQUEEZED = 0b0000000100000000; +export const OPTIMIZED = 0b0000001000000000; +export const TOP = 0b0000010000000000; +export const CLEAR_BETWEEN_PASSES = SQUEEZED | OPTIMIZED | TOP; + +export const has_flag = (node, flag) => node.flags & flag; +export const set_flag = (node, flag) => { node.flags |= flag; }; +export const clear_flag = (node, flag) => { node.flags &= ~flag; }; diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/compress/drop-side-effect-free.js b/node_modules/mathjs/examples/node_modules/terser/lib/compress/drop-side-effect-free.js new file mode 100644 index 0000000..60ee014 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/compress/drop-side-effect-free.js @@ -0,0 +1,350 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Accessor, + AST_Array, + AST_Arrow, + AST_Assign, + AST_Binary, + AST_Call, + AST_Chain, + AST_Class, + AST_ClassProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Constant, + AST_Dot, + AST_Expansion, + AST_Function, + AST_Node, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PropAccess, + AST_Scope, + AST_Sequence, + AST_Sub, + AST_SymbolRef, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Unary, +} from "../ast.js"; +import { make_node, return_null, return_this } from "../utils/index.js"; +import { first_in_statement } from "../utils/first_in_statement.js"; + +import { pure_prop_access_globals } from "./native-objects.js"; +import { lazy_op, unary_side_effects, is_nullish_shortcircuited } from "./inference.js"; +import { WRITE_ONLY, set_flag, clear_flag } from "./compressor-flags.js"; +import { make_sequence, is_func_expr, is_iife_call } from "./common.js"; + +// AST_Node#drop_side_effect_free() gets called when we don't care about the value, +// only about side effects. We'll be defining this method for each node type in this module +// +// Examples: +// foo++ -> foo++ +// 1 + func() -> func() +// 10 -> (nothing) +// knownPureFunc(foo++) -> foo++ + +function def_drop_side_effect_free(node, func) { + node.DEFMETHOD("drop_side_effect_free", func); +} + +// Drop side-effect-free elements from an array of expressions. +// Returns an array of expressions with side-effects or null +// if all elements were dropped. Note: original array may be +// returned if nothing changed. +function trim(nodes, compressor, first_in_statement) { + var len = nodes.length; + if (!len) return null; + + var ret = [], changed = false; + for (var i = 0; i < len; i++) { + var node = nodes[i].drop_side_effect_free(compressor, first_in_statement); + changed |= node !== nodes[i]; + if (node) { + ret.push(node); + first_in_statement = false; + } + } + return changed ? ret.length ? ret : null : nodes; +} + +def_drop_side_effect_free(AST_Node, return_this); +def_drop_side_effect_free(AST_Constant, return_null); +def_drop_side_effect_free(AST_This, return_null); + +def_drop_side_effect_free(AST_Call, function (compressor, first_in_statement) { + if (is_nullish_shortcircuited(this, compressor)) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); + } + + if (!this.is_callee_pure(compressor)) { + if (this.expression.is_call_pure(compressor)) { + var exprs = this.args.slice(); + exprs.unshift(this.expression.expression); + exprs = trim(exprs, compressor, first_in_statement); + return exprs && make_sequence(this, exprs); + } + if (is_func_expr(this.expression) + && (!this.expression.name || !this.expression.name.definition().references.length)) { + var node = this.clone(); + node.expression.process_expression(false, compressor); + return node; + } + return this; + } + + var args = trim(this.args, compressor, first_in_statement); + return args && make_sequence(this, args); +}); + +def_drop_side_effect_free(AST_Accessor, return_null); + +def_drop_side_effect_free(AST_Function, return_null); + +def_drop_side_effect_free(AST_Arrow, return_null); + +def_drop_side_effect_free(AST_Class, function (compressor) { + const with_effects = []; + const trimmed_extends = this.extends && this.extends.drop_side_effect_free(compressor); + if (trimmed_extends) + with_effects.push(trimmed_extends); + for (const prop of this.properties) { + const trimmed_prop = prop.drop_side_effect_free(compressor); + if (trimmed_prop) + with_effects.push(trimmed_prop); + } + if (!with_effects.length) + return null; + return make_sequence(this, with_effects); +}); + +def_drop_side_effect_free(AST_Binary, function (compressor, first_in_statement) { + var right = this.right.drop_side_effect_free(compressor); + if (!right) + return this.left.drop_side_effect_free(compressor, first_in_statement); + if (lazy_op.has(this.operator)) { + if (right === this.right) + return this; + var node = this.clone(); + node.right = right; + return node; + } else { + var left = this.left.drop_side_effect_free(compressor, first_in_statement); + if (!left) + return this.right.drop_side_effect_free(compressor, first_in_statement); + return make_sequence(this, [left, right]); + } +}); + +def_drop_side_effect_free(AST_Assign, function (compressor) { + if (this.logical) + return this; + + var left = this.left; + if (left.has_side_effects(compressor) + || compressor.has_directive("use strict") + && left instanceof AST_PropAccess + && left.expression.is_constant()) { + return this; + } + set_flag(this, WRITE_ONLY); + while (left instanceof AST_PropAccess) { + left = left.expression; + } + if (left.is_constant_expression(compressor.find_parent(AST_Scope))) { + return this.right.drop_side_effect_free(compressor); + } + return this; +}); + +def_drop_side_effect_free(AST_Conditional, function (compressor) { + var consequent = this.consequent.drop_side_effect_free(compressor); + var alternative = this.alternative.drop_side_effect_free(compressor); + if (consequent === this.consequent && alternative === this.alternative) + return this; + if (!consequent) + return alternative ? make_node(AST_Binary, this, { + operator: "||", + left: this.condition, + right: alternative + }) : this.condition.drop_side_effect_free(compressor); + if (!alternative) + return make_node(AST_Binary, this, { + operator: "&&", + left: this.condition, + right: consequent + }); + var node = this.clone(); + node.consequent = consequent; + node.alternative = alternative; + return node; +}); + +def_drop_side_effect_free(AST_Unary, function (compressor, first_in_statement) { + if (unary_side_effects.has(this.operator)) { + if (!this.expression.has_side_effects(compressor)) { + set_flag(this, WRITE_ONLY); + } else { + clear_flag(this, WRITE_ONLY); + } + return this; + } + if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) + return null; + var expression = this.expression.drop_side_effect_free(compressor, first_in_statement); + if (first_in_statement && expression && is_iife_call(expression)) { + if (expression === this.expression && this.operator == "!") + return this; + return expression.negate(compressor, first_in_statement); + } + return expression; +}); + +def_drop_side_effect_free(AST_SymbolRef, function (compressor) { + const safe_access = this.is_declared(compressor) + || pure_prop_access_globals.has(this.name); + return safe_access ? null : this; +}); + +def_drop_side_effect_free(AST_Object, function (compressor, first_in_statement) { + var values = trim(this.properties, compressor, first_in_statement); + return values && make_sequence(this, values); +}); + +def_drop_side_effect_free(AST_ObjectProperty, function (compressor, first_in_statement) { + const computed_key = this instanceof AST_ObjectKeyVal && this.key instanceof AST_Node; + const key = computed_key && this.key.drop_side_effect_free(compressor, first_in_statement); + const value = this.value && this.value.drop_side_effect_free(compressor, first_in_statement); + if (key && value) { + return make_sequence(this, [key, value]); + } + return key || value; +}); + +def_drop_side_effect_free(AST_ClassProperty, function (compressor) { + const key = this.computed_key() && this.key.drop_side_effect_free(compressor); + + const value = this.static && this.value + && this.value.drop_side_effect_free(compressor); + + if (key && value) + return make_sequence(this, [key, value]); + return key || value || null; +}); + +def_drop_side_effect_free(AST_ConciseMethod, function () { + return this.computed_key() ? this.key : null; +}); + +def_drop_side_effect_free(AST_ObjectGetter, function () { + return this.computed_key() ? this.key : null; +}); + +def_drop_side_effect_free(AST_ObjectSetter, function () { + return this.computed_key() ? this.key : null; +}); + +def_drop_side_effect_free(AST_Array, function (compressor, first_in_statement) { + var values = trim(this.elements, compressor, first_in_statement); + return values && make_sequence(this, values); +}); + +def_drop_side_effect_free(AST_Dot, function (compressor, first_in_statement) { + if (is_nullish_shortcircuited(this, compressor)) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); + } + if (this.expression.may_throw_on_access(compressor)) return this; + + return this.expression.drop_side_effect_free(compressor, first_in_statement); +}); + +def_drop_side_effect_free(AST_Sub, function (compressor, first_in_statement) { + if (is_nullish_shortcircuited(this, compressor)) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); + } + if (this.expression.may_throw_on_access(compressor)) return this; + + var expression = this.expression.drop_side_effect_free(compressor, first_in_statement); + if (!expression) + return this.property.drop_side_effect_free(compressor, first_in_statement); + var property = this.property.drop_side_effect_free(compressor); + if (!property) + return expression; + return make_sequence(this, [expression, property]); +}); + +def_drop_side_effect_free(AST_Chain, function (compressor, first_in_statement) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); +}); + +def_drop_side_effect_free(AST_Sequence, function (compressor) { + var last = this.tail_node(); + var expr = last.drop_side_effect_free(compressor); + if (expr === last) + return this; + var expressions = this.expressions.slice(0, -1); + if (expr) + expressions.push(expr); + if (!expressions.length) { + return make_node(AST_Number, this, { value: 0 }); + } + return make_sequence(this, expressions); +}); + +def_drop_side_effect_free(AST_Expansion, function (compressor, first_in_statement) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); +}); + +def_drop_side_effect_free(AST_TemplateSegment, return_null); + +def_drop_side_effect_free(AST_TemplateString, function (compressor) { + var values = trim(this.segments, compressor, first_in_statement); + return values && make_sequence(this, values); +}); diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/compress/evaluate.js b/node_modules/mathjs/examples/node_modules/terser/lib/compress/evaluate.js new file mode 100644 index 0000000..a9c52e7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/compress/evaluate.js @@ -0,0 +1,461 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + HOP, + makePredicate, + return_this, + string_template, + regexp_source_fix +} from "../utils/index.js"; +import { + AST_Array, + AST_BigInt, + AST_Binary, + AST_Call, + AST_Chain, + AST_Class, + AST_Conditional, + AST_Constant, + AST_Dot, + AST_Expansion, + AST_Function, + AST_Lambda, + AST_New, + AST_Node, + AST_Object, + AST_PropAccess, + AST_RegExp, + AST_Statement, + AST_Symbol, + AST_SymbolRef, + AST_TemplateString, + AST_UnaryPrefix, + AST_With, +} from "../ast.js"; +import { is_undeclared_ref} from "./inference.js"; +import { is_pure_native_value, is_pure_native_fn, is_pure_native_method } from "./native-objects.js"; + +// methods to evaluate a constant expression + +function def_eval(node, func) { + node.DEFMETHOD("_eval", func); +} + +// Used to propagate a nullish short-circuit signal upwards through the chain. +export const nullish = Symbol("This AST_Chain is nullish"); + +// If the node has been successfully reduced to a constant, +// then its value is returned; otherwise the element itself +// is returned. +// They can be distinguished as constant value is never a +// descendant of AST_Node. +AST_Node.DEFMETHOD("evaluate", function (compressor) { + if (!compressor.option("evaluate")) + return this; + var val = this._eval(compressor, 1); + if (!val || val instanceof RegExp) + return val; + if (typeof val == "function" || typeof val == "object" || val == nullish) + return this; + return val; +}); + +var unaryPrefix = makePredicate("! ~ - + void"); +AST_Node.DEFMETHOD("is_constant", function () { + // Accomodate when compress option evaluate=false + // as well as the common constant expressions !0 and -1 + if (this instanceof AST_Constant) { + return !(this instanceof AST_RegExp); + } else { + return this instanceof AST_UnaryPrefix + && this.expression instanceof AST_Constant + && unaryPrefix.has(this.operator); + } +}); + +def_eval(AST_Statement, function () { + throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start)); +}); + +def_eval(AST_Lambda, return_this); +def_eval(AST_Class, return_this); +def_eval(AST_Node, return_this); +def_eval(AST_Constant, function () { + return this.getValue(); +}); + +def_eval(AST_BigInt, return_this); + +def_eval(AST_RegExp, function (compressor) { + let evaluated = compressor.evaluated_regexps.get(this); + if (evaluated === undefined) { + try { + evaluated = (0, eval)(this.print_to_string()); + } catch (e) { + evaluated = null; + } + compressor.evaluated_regexps.set(this, evaluated); + } + return evaluated || this; +}); + +def_eval(AST_TemplateString, function () { + if (this.segments.length !== 1) return this; + return this.segments[0].value; +}); + +def_eval(AST_Function, function (compressor) { + if (compressor.option("unsafe")) { + var fn = function () { }; + fn.node = this; + fn.toString = () => this.print_to_string(); + return fn; + } + return this; +}); + +def_eval(AST_Array, function (compressor, depth) { + if (compressor.option("unsafe")) { + var elements = []; + for (var i = 0, len = this.elements.length; i < len; i++) { + var element = this.elements[i]; + var value = element._eval(compressor, depth); + if (element === value) + return this; + elements.push(value); + } + return elements; + } + return this; +}); + +def_eval(AST_Object, function (compressor, depth) { + if (compressor.option("unsafe")) { + var val = {}; + for (var i = 0, len = this.properties.length; i < len; i++) { + var prop = this.properties[i]; + if (prop instanceof AST_Expansion) + return this; + var key = prop.key; + if (key instanceof AST_Symbol) { + key = key.name; + } else if (key instanceof AST_Node) { + key = key._eval(compressor, depth); + if (key === prop.key) + return this; + } + if (typeof Object.prototype[key] === "function") { + return this; + } + if (prop.value instanceof AST_Function) + continue; + val[key] = prop.value._eval(compressor, depth); + if (val[key] === prop.value) + return this; + } + return val; + } + return this; +}); + +var non_converting_unary = makePredicate("! typeof void"); +def_eval(AST_UnaryPrefix, function (compressor, depth) { + var e = this.expression; + // Function would be evaluated to an array and so typeof would + // incorrectly return 'object'. Hence making is a special case. + if (compressor.option("typeofs") + && this.operator == "typeof" + && (e instanceof AST_Lambda + || e instanceof AST_SymbolRef + && e.fixed_value() instanceof AST_Lambda)) { + return typeof function () { }; + } + if (!non_converting_unary.has(this.operator)) + depth++; + e = e._eval(compressor, depth); + if (e === this.expression) + return this; + switch (this.operator) { + case "!": return !e; + case "typeof": + // typeof returns "object" or "function" on different platforms + // so cannot evaluate reliably + if (e instanceof RegExp) + return this; + return typeof e; + case "void": return void e; + case "~": return ~e; + case "-": return -e; + case "+": return +e; + } + return this; +}); + +var non_converting_binary = makePredicate("&& || ?? === !=="); +const identity_comparison = makePredicate("== != === !=="); +const has_identity = value => typeof value === "object" + || typeof value === "function" + || typeof value === "symbol"; + +def_eval(AST_Binary, function (compressor, depth) { + if (!non_converting_binary.has(this.operator)) + depth++; + + var left = this.left._eval(compressor, depth); + if (left === this.left) + return this; + var right = this.right._eval(compressor, depth); + if (right === this.right) + return this; + var result; + + if (left != null + && right != null + && identity_comparison.has(this.operator) + && has_identity(left) + && has_identity(right) + && typeof left === typeof right) { + // Do not compare by reference + return this; + } + + switch (this.operator) { + case "&&": result = left && right; break; + case "||": result = left || right; break; + case "??": result = left != null ? left : right; break; + case "|": result = left | right; break; + case "&": result = left & right; break; + case "^": result = left ^ right; break; + case "+": result = left + right; break; + case "*": result = left * right; break; + case "**": result = Math.pow(left, right); break; + case "/": result = left / right; break; + case "%": result = left % right; break; + case "-": result = left - right; break; + case "<<": result = left << right; break; + case ">>": result = left >> right; break; + case ">>>": result = left >>> right; break; + case "==": result = left == right; break; + case "===": result = left === right; break; + case "!=": result = left != right; break; + case "!==": result = left !== right; break; + case "<": result = left < right; break; + case "<=": result = left <= right; break; + case ">": result = left > right; break; + case ">=": result = left >= right; break; + default: + return this; + } + if (isNaN(result) && compressor.find_parent(AST_With)) { + // leave original expression as is + return this; + } + return result; +}); + +def_eval(AST_Conditional, function (compressor, depth) { + var condition = this.condition._eval(compressor, depth); + if (condition === this.condition) + return this; + var node = condition ? this.consequent : this.alternative; + var value = node._eval(compressor, depth); + return value === node ? this : value; +}); + +// Set of AST_SymbolRef which are currently being evaluated. +// Avoids infinite recursion of ._eval() +const reentrant_ref_eval = new Set(); +def_eval(AST_SymbolRef, function (compressor, depth) { + if (reentrant_ref_eval.has(this)) + return this; + + var fixed = this.fixed_value(); + if (!fixed) + return this; + + reentrant_ref_eval.add(this); + const value = fixed._eval(compressor, depth); + reentrant_ref_eval.delete(this); + + if (value === fixed) + return this; + + if (value && typeof value == "object") { + var escaped = this.definition().escaped; + if (escaped && depth > escaped) + return this; + } + return value; +}); + +const global_objs = { Array, Math, Number, Object, String }; + +const regexp_flags = new Set([ + "dotAll", + "global", + "ignoreCase", + "multiline", + "sticky", + "unicode", +]); + +def_eval(AST_PropAccess, function (compressor, depth) { + const obj = this.expression._eval(compressor, depth); + if (obj === nullish || (this.optional && obj == null)) return nullish; + if (compressor.option("unsafe")) { + var key = this.property; + if (key instanceof AST_Node) { + key = key._eval(compressor, depth); + if (key === this.property) + return this; + } + var exp = this.expression; + var val; + if (is_undeclared_ref(exp)) { + + var aa; + var first_arg = exp.name === "hasOwnProperty" + && key === "call" + && (aa = compressor.parent() && compressor.parent().args) + && (aa && aa[0] + && aa[0].evaluate(compressor)); + + first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg; + + if (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared) { + return this.clone(); + } + if (!is_pure_native_value(exp.name, key)) + return this; + val = global_objs[exp.name]; + } else { + val = exp._eval(compressor, depth + 1); + if (val instanceof RegExp) { + if (key == "source") { + return regexp_source_fix(val.source); + } else if (key == "flags" || regexp_flags.has(key)) { + return val[key]; + } + } + if (!val || val === exp || !HOP(val, key)) + return this; + if (typeof val == "function") + switch (key) { + case "name": + return val.node.name ? val.node.name.name : ""; + case "length": + return val.node.length_property(); + default: + return this; + } + } + return val[key]; + } + return this; +}); + +def_eval(AST_Chain, function (compressor, depth) { + const evaluated = this.expression._eval(compressor, depth); + return evaluated === nullish + ? undefined + : evaluated === this.expression + ? this + : evaluated; +}); + +def_eval(AST_Call, function (compressor, depth) { + var exp = this.expression; + + const callee = exp._eval(compressor, depth); + if (callee === nullish || (this.optional && callee == null)) return nullish; + + if (compressor.option("unsafe") && exp instanceof AST_PropAccess) { + var key = exp.property; + if (key instanceof AST_Node) { + key = key._eval(compressor, depth); + if (key === exp.property) + return this; + } + var val; + var e = exp.expression; + if (is_undeclared_ref(e)) { + var first_arg = e.name === "hasOwnProperty" && + key === "call" && + (this.args[0] && this.args[0].evaluate(compressor)); + + first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg; + + if ((first_arg == null || first_arg.thedef && first_arg.thedef.undeclared)) { + return this.clone(); + } + if (!is_pure_native_fn(e.name, key)) return this; + val = global_objs[e.name]; + } else { + val = e._eval(compressor, depth + 1); + if (val === e || !val) + return this; + if (!is_pure_native_method(val.constructor.name, key)) + return this; + } + var args = []; + for (var i = 0, len = this.args.length; i < len; i++) { + var arg = this.args[i]; + var value = arg._eval(compressor, depth); + if (arg === value) + return this; + if (arg instanceof AST_Lambda) + return this; + args.push(value); + } + try { + return val[key].apply(val, args); + } catch (ex) { + // We don't really care + } + } + return this; +}); + +// Also a subclass of AST_Call +def_eval(AST_New, return_this); diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/compress/index.js b/node_modules/mathjs/examples/node_modules/terser/lib/compress/index.js new file mode 100644 index 0000000..8b901a3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/compress/index.js @@ -0,0 +1,4667 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Accessor, + AST_Array, + AST_Arrow, + AST_Assign, + AST_BigInt, + AST_Binary, + AST_Block, + AST_BlockStatement, + AST_Boolean, + AST_Break, + AST_Call, + AST_Catch, + AST_Chain, + AST_Class, + AST_ClassExpression, + AST_ClassProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Const, + AST_Constant, + AST_Debugger, + AST_Default, + AST_DefaultAssign, + AST_DefClass, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DWLoop, + AST_EmptyStatement, + AST_Exit, + AST_Expansion, + AST_Export, + AST_False, + AST_For, + AST_ForIn, + AST_Function, + AST_Hole, + AST_If, + AST_Import, + AST_Infinity, + AST_IterationStatement, + AST_LabeledStatement, + AST_Lambda, + AST_Let, + AST_NaN, + AST_New, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_PrefixedTemplateString, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_String, + AST_Sub, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_SymbolBlockDeclaration, + AST_SymbolCatch, + AST_SymbolClassProperty, + AST_SymbolDeclaration, + AST_SymbolDefun, + AST_SymbolExport, + AST_SymbolFunarg, + AST_SymbolLambda, + AST_SymbolLet, + AST_SymbolMethod, + AST_SymbolRef, + AST_SymbolVar, + AST_TemplateString, + AST_This, + AST_Toplevel, + AST_True, + AST_Try, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Undefined, + AST_Var, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, + + TreeTransformer, + TreeWalker, + walk, + walk_abort, + walk_parent, + + _INLINE, + _NOINLINE, + _PURE +} from "../ast.js"; +import { + defaults, + HOP, + keep_name, + make_node, + makePredicate, + map_add, + MAP, + member, + remove, + return_false, + return_true, + regexp_source_fix, + has_annotation +} from "../utils/index.js"; +import { first_in_statement } from "../utils/first_in_statement.js"; +import { equivalent_to } from "../equivalent-to.js"; +import { + is_basic_identifier_string, + JS_Parse_Error, + parse, + PRECEDENCE, +} from "../parse.js"; +import { OutputStream } from "../output.js"; +import { + base54, + SymbolDef, +} from "../scope.js"; +import "../size.js"; + +import "./evaluate.js"; +import "./drop-side-effect-free.js"; +import "./reduce-vars.js"; +import { + is_undeclared_ref, + lazy_op, + is_nullish, + is_undefined, + is_lhs, + aborts, +} from "./inference.js"; +import { + SQUEEZED, + OPTIMIZED, + INLINED, + CLEAR_BETWEEN_PASSES, + TOP, + WRITE_ONLY, + UNDEFINED, + UNUSED, + TRUTHY, + FALSY, + + has_flag, + set_flag, + clear_flag, +} from "./compressor-flags.js"; +import { + make_sequence, + best_of, + best_of_expression, + make_node_from_constant, + merge_sequence, + get_simple_key, + has_break_or_continue, + maintain_this_binding, + identifier_atom, + is_identifier_atom, + is_func_expr, + is_ref_of, + can_be_evicted_from_block, + as_statement_array, + is_iife_call, + is_recursive_ref +} from "./common.js"; +import { tighten_body, trim_unreachable_code } from "./tighten-body.js"; + +class Compressor extends TreeWalker { + constructor(options, { false_by_default = false, mangle_options = false }) { + super(); + if (options.defaults !== undefined && !options.defaults) false_by_default = true; + this.options = defaults(options, { + arguments : false, + arrows : !false_by_default, + booleans : !false_by_default, + booleans_as_integers : false, + collapse_vars : !false_by_default, + comparisons : !false_by_default, + computed_props: !false_by_default, + conditionals : !false_by_default, + dead_code : !false_by_default, + defaults : true, + directives : !false_by_default, + drop_console : false, + drop_debugger : !false_by_default, + ecma : 5, + evaluate : !false_by_default, + expression : false, + global_defs : false, + hoist_funs : false, + hoist_props : !false_by_default, + hoist_vars : false, + ie8 : false, + if_return : !false_by_default, + inline : !false_by_default, + join_vars : !false_by_default, + keep_classnames: false, + keep_fargs : true, + keep_fnames : false, + keep_infinity : false, + loops : !false_by_default, + module : false, + negate_iife : !false_by_default, + passes : 1, + properties : !false_by_default, + pure_getters : !false_by_default && "strict", + pure_funcs : null, + reduce_funcs : !false_by_default, + reduce_vars : !false_by_default, + sequences : !false_by_default, + side_effects : !false_by_default, + switches : !false_by_default, + top_retain : null, + toplevel : !!(options && options["top_retain"]), + typeofs : !false_by_default, + unsafe : false, + unsafe_arrows : false, + unsafe_comps : false, + unsafe_Function: false, + unsafe_math : false, + unsafe_symbols: false, + unsafe_methods: false, + unsafe_proto : false, + unsafe_regexp : false, + unsafe_undefined: false, + unused : !false_by_default, + warnings : false // legacy + }, true); + var global_defs = this.options["global_defs"]; + if (typeof global_defs == "object") for (var key in global_defs) { + if (key[0] === "@" && HOP(global_defs, key)) { + global_defs[key.slice(1)] = parse(global_defs[key], { + expression: true + }); + } + } + if (this.options["inline"] === true) this.options["inline"] = 3; + var pure_funcs = this.options["pure_funcs"]; + if (typeof pure_funcs == "function") { + this.pure_funcs = pure_funcs; + } else { + this.pure_funcs = pure_funcs ? function(node) { + return !pure_funcs.includes(node.expression.print_to_string()); + } : return_true; + } + var top_retain = this.options["top_retain"]; + if (top_retain instanceof RegExp) { + this.top_retain = function(def) { + return top_retain.test(def.name); + }; + } else if (typeof top_retain == "function") { + this.top_retain = top_retain; + } else if (top_retain) { + if (typeof top_retain == "string") { + top_retain = top_retain.split(/,/); + } + this.top_retain = function(def) { + return top_retain.includes(def.name); + }; + } + if (this.options["module"]) { + this.directives["use strict"] = true; + this.options["toplevel"] = true; + } + var toplevel = this.options["toplevel"]; + this.toplevel = typeof toplevel == "string" ? { + funcs: /funcs/.test(toplevel), + vars: /vars/.test(toplevel) + } : { + funcs: toplevel, + vars: toplevel + }; + var sequences = this.options["sequences"]; + this.sequences_limit = sequences == 1 ? 800 : sequences | 0; + this.evaluated_regexps = new Map(); + this._toplevel = undefined; + this.mangle_options = mangle_options; + } + + option(key) { + return this.options[key]; + } + + exposed(def) { + if (def.export) return true; + if (def.global) for (var i = 0, len = def.orig.length; i < len; i++) + if (!this.toplevel[def.orig[i] instanceof AST_SymbolDefun ? "funcs" : "vars"]) + return true; + return false; + } + + in_boolean_context() { + if (!this.option("booleans")) return false; + var self = this.self(); + for (var i = 0, p; p = this.parent(i); i++) { + if (p instanceof AST_SimpleStatement + || p instanceof AST_Conditional && p.condition === self + || p instanceof AST_DWLoop && p.condition === self + || p instanceof AST_For && p.condition === self + || p instanceof AST_If && p.condition === self + || p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self) { + return true; + } + if ( + p instanceof AST_Binary + && ( + p.operator == "&&" + || p.operator == "||" + || p.operator == "??" + ) + || p instanceof AST_Conditional + || p.tail_node() === self + ) { + self = p; + } else { + return false; + } + } + } + + get_toplevel() { + return this._toplevel; + } + + compress(toplevel) { + toplevel = toplevel.resolve_defines(this); + this._toplevel = toplevel; + if (this.option("expression")) { + this._toplevel.process_expression(true); + } + var passes = +this.options.passes || 1; + var min_count = 1 / 0; + var stopping = false; + var nth_identifier = this.mangle_options && this.mangle_options.nth_identifier || base54; + var mangle = { ie8: this.option("ie8"), nth_identifier: nth_identifier }; + for (var pass = 0; pass < passes; pass++) { + this._toplevel.figure_out_scope(mangle); + if (pass === 0 && this.option("drop_console")) { + // must be run before reduce_vars and compress pass + this._toplevel = this._toplevel.drop_console(); + } + if (pass > 0 || this.option("reduce_vars")) { + this._toplevel.reset_opt_flags(this); + } + this._toplevel = this._toplevel.transform(this); + if (passes > 1) { + let count = 0; + walk(this._toplevel, () => { count++; }); + if (count < min_count) { + min_count = count; + stopping = false; + } else if (stopping) { + break; + } else { + stopping = true; + } + } + } + if (this.option("expression")) { + this._toplevel.process_expression(false); + } + toplevel = this._toplevel; + this._toplevel = undefined; + return toplevel; + } + + before(node, descend) { + if (has_flag(node, SQUEEZED)) return node; + var was_scope = false; + if (node instanceof AST_Scope) { + node = node.hoist_properties(this); + node = node.hoist_declarations(this); + was_scope = true; + } + // Before https://github.com/mishoo/UglifyJS2/pull/1602 AST_Node.optimize() + // would call AST_Node.transform() if a different instance of AST_Node is + // produced after def_optimize(). + // This corrupts TreeWalker.stack, which cause AST look-ups to malfunction. + // Migrate and defer all children's AST_Node.transform() to below, which + // will now happen after this parent AST_Node has been properly substituted + // thus gives a consistent AST snapshot. + descend(node, this); + // Existing code relies on how AST_Node.optimize() worked, and omitting the + // following replacement call would result in degraded efficiency of both + // output and performance. + descend(node, this); + var opt = node.optimize(this); + if (was_scope && opt instanceof AST_Scope) { + opt.drop_unused(this); + descend(opt, this); + } + if (opt === node) set_flag(opt, SQUEEZED); + return opt; + } +} + +function def_optimize(node, optimizer) { + node.DEFMETHOD("optimize", function(compressor) { + var self = this; + if (has_flag(self, OPTIMIZED)) return self; + if (compressor.has_directive("use asm")) return self; + var opt = optimizer(self, compressor); + set_flag(opt, OPTIMIZED); + return opt; + }); +} + +def_optimize(AST_Node, function(self) { + return self; +}); + +AST_Toplevel.DEFMETHOD("drop_console", function() { + return this.transform(new TreeTransformer(function(self) { + if (self.TYPE == "Call") { + var exp = self.expression; + if (exp instanceof AST_PropAccess) { + var name = exp.expression; + while (name.expression) { + name = name.expression; + } + if (is_undeclared_ref(name) && name.name == "console") { + return make_node(AST_Undefined, self); + } + } + } + })); +}); + +AST_Node.DEFMETHOD("equivalent_to", function(node) { + return equivalent_to(this, node); +}); + +AST_Scope.DEFMETHOD("process_expression", function(insert, compressor) { + var self = this; + var tt = new TreeTransformer(function(node) { + if (insert && node instanceof AST_SimpleStatement) { + return make_node(AST_Return, node, { + value: node.body + }); + } + if (!insert && node instanceof AST_Return) { + if (compressor) { + var value = node.value && node.value.drop_side_effect_free(compressor, true); + return value + ? make_node(AST_SimpleStatement, node, { body: value }) + : make_node(AST_EmptyStatement, node); + } + return make_node(AST_SimpleStatement, node, { + body: node.value || make_node(AST_UnaryPrefix, node, { + operator: "void", + expression: make_node(AST_Number, node, { + value: 0 + }) + }) + }); + } + if (node instanceof AST_Class || node instanceof AST_Lambda && node !== self) { + return node; + } + if (node instanceof AST_Block) { + var index = node.body.length - 1; + if (index >= 0) { + node.body[index] = node.body[index].transform(tt); + } + } else if (node instanceof AST_If) { + node.body = node.body.transform(tt); + if (node.alternative) { + node.alternative = node.alternative.transform(tt); + } + } else if (node instanceof AST_With) { + node.body = node.body.transform(tt); + } + return node; + }); + self.transform(tt); +}); + +AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) { + const self = this; + const reduce_vars = compressor.option("reduce_vars"); + + const preparation = new TreeWalker(function(node, descend) { + clear_flag(node, CLEAR_BETWEEN_PASSES); + if (reduce_vars) { + if (compressor.top_retain + && node instanceof AST_Defun // Only functions are retained + && preparation.parent() === self + ) { + set_flag(node, TOP); + } + return node.reduce_vars(preparation, descend, compressor); + } + }); + // Stack of look-up tables to keep track of whether a `SymbolDef` has been + // properly assigned before use: + // - `push()` & `pop()` when visiting conditional branches + preparation.safe_ids = Object.create(null); + preparation.in_loop = null; + preparation.loop_ids = new Map(); + preparation.defs_to_safe_ids = new Map(); + self.walk(preparation); +}); + +AST_Symbol.DEFMETHOD("fixed_value", function() { + var fixed = this.thedef.fixed; + if (!fixed || fixed instanceof AST_Node) return fixed; + return fixed(); +}); + +AST_SymbolRef.DEFMETHOD("is_immutable", function() { + var orig = this.definition().orig; + return orig.length == 1 && orig[0] instanceof AST_SymbolLambda; +}); + +function find_scope(tw) { + for (let i = 0;;i++) { + const p = tw.parent(i); + if (p instanceof AST_Toplevel) return p; + if (p instanceof AST_Lambda) return p; + if (p.block_scope) return p.block_scope; + } +} + +function find_variable(compressor, name) { + var scope, i = 0; + while (scope = compressor.parent(i++)) { + if (scope instanceof AST_Scope) break; + if (scope instanceof AST_Catch && scope.argname) { + scope = scope.argname.definition().scope; + break; + } + } + return scope.find_variable(name); +} + +function is_empty(thing) { + if (thing === null) return true; + if (thing instanceof AST_EmptyStatement) return true; + if (thing instanceof AST_BlockStatement) return thing.body.length == 0; + return false; +} + +var global_names = makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError"); +AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) { + return !this.definition().undeclared + || compressor.option("unsafe") && global_names.has(this.name); +}); + +/* -----[ optimizers ]----- */ + +var directives = new Set(["use asm", "use strict"]); +def_optimize(AST_Directive, function(self, compressor) { + if (compressor.option("directives") + && (!directives.has(self.value) || compressor.has_directive(self.value) !== self)) { + return make_node(AST_EmptyStatement, self); + } + return self; +}); + +def_optimize(AST_Debugger, function(self, compressor) { + if (compressor.option("drop_debugger")) + return make_node(AST_EmptyStatement, self); + return self; +}); + +def_optimize(AST_LabeledStatement, function(self, compressor) { + if (self.body instanceof AST_Break + && compressor.loopcontrol_target(self.body) === self.body) { + return make_node(AST_EmptyStatement, self); + } + return self.label.references.length == 0 ? self.body : self; +}); + +def_optimize(AST_Block, function(self, compressor) { + tighten_body(self.body, compressor); + return self; +}); + +function can_be_extracted_from_if_block(node) { + return !( + node instanceof AST_Const + || node instanceof AST_Let + || node instanceof AST_Class + ); +} + +def_optimize(AST_BlockStatement, function(self, compressor) { + tighten_body(self.body, compressor); + switch (self.body.length) { + case 1: + if (!compressor.has_directive("use strict") + && compressor.parent() instanceof AST_If + && can_be_extracted_from_if_block(self.body[0]) + || can_be_evicted_from_block(self.body[0])) { + return self.body[0]; + } + break; + case 0: return make_node(AST_EmptyStatement, self); + } + return self; +}); + +function opt_AST_Lambda(self, compressor) { + tighten_body(self.body, compressor); + if (compressor.option("side_effects") + && self.body.length == 1 + && self.body[0] === compressor.has_directive("use strict")) { + self.body.length = 0; + } + return self; +} +def_optimize(AST_Lambda, opt_AST_Lambda); + +const r_keep_assign = /keep_assign/; +AST_Scope.DEFMETHOD("drop_unused", function(compressor) { + if (!compressor.option("unused")) return; + if (compressor.has_directive("use asm")) return; + var self = this; + if (self.pinned()) return; + var drop_funcs = !(self instanceof AST_Toplevel) || compressor.toplevel.funcs; + var drop_vars = !(self instanceof AST_Toplevel) || compressor.toplevel.vars; + const assign_as_unused = r_keep_assign.test(compressor.option("unused")) ? return_false : function(node) { + if (node instanceof AST_Assign + && !node.logical + && (has_flag(node, WRITE_ONLY) || node.operator == "=") + ) { + return node.left; + } + if (node instanceof AST_Unary && has_flag(node, WRITE_ONLY)) { + return node.expression; + } + }; + var in_use_ids = new Map(); + var fixed_ids = new Map(); + if (self instanceof AST_Toplevel && compressor.top_retain) { + self.variables.forEach(function(def) { + if (compressor.top_retain(def) && !in_use_ids.has(def.id)) { + in_use_ids.set(def.id, def); + } + }); + } + var var_defs_by_id = new Map(); + var initializations = new Map(); + // pass 1: find out which symbols are directly used in + // this scope (not in nested scopes). + var scope = this; + var tw = new TreeWalker(function(node, descend) { + if (node instanceof AST_Lambda && node.uses_arguments && !tw.has_directive("use strict")) { + node.argnames.forEach(function(argname) { + if (!(argname instanceof AST_SymbolDeclaration)) return; + var def = argname.definition(); + if (!in_use_ids.has(def.id)) { + in_use_ids.set(def.id, def); + } + }); + } + if (node === self) return; + if (node instanceof AST_Defun || node instanceof AST_DefClass) { + var node_def = node.name.definition(); + const in_export = tw.parent() instanceof AST_Export; + if (in_export || !drop_funcs && scope === self) { + if (node_def.global && !in_use_ids.has(node_def.id)) { + in_use_ids.set(node_def.id, node_def); + } + } + if (node instanceof AST_DefClass) { + if ( + node.extends + && (node.extends.has_side_effects(compressor) + || node.extends.may_throw(compressor)) + ) { + node.extends.walk(tw); + } + for (const prop of node.properties) { + if ( + prop.has_side_effects(compressor) || + prop.may_throw(compressor) + ) { + prop.walk(tw); + } + } + } + map_add(initializations, node_def.id, node); + return true; // don't go in nested scopes + } + if (node instanceof AST_SymbolFunarg && scope === self) { + map_add(var_defs_by_id, node.definition().id, node); + } + if (node instanceof AST_Definitions && scope === self) { + const in_export = tw.parent() instanceof AST_Export; + node.definitions.forEach(function(def) { + if (def.name instanceof AST_SymbolVar) { + map_add(var_defs_by_id, def.name.definition().id, def); + } + if (in_export || !drop_vars) { + walk(def.name, node => { + if (node instanceof AST_SymbolDeclaration) { + const def = node.definition(); + if ( + (in_export || def.global) + && !in_use_ids.has(def.id) + ) { + in_use_ids.set(def.id, def); + } + } + }); + } + if (def.value) { + if (def.name instanceof AST_Destructuring) { + def.walk(tw); + } else { + var node_def = def.name.definition(); + map_add(initializations, node_def.id, def.value); + if (!node_def.chained && def.name.fixed_value() === def.value) { + fixed_ids.set(node_def.id, def); + } + } + if (def.value.has_side_effects(compressor)) { + def.value.walk(tw); + } + } + }); + return true; + } + return scan_ref_scoped(node, descend); + }); + self.walk(tw); + // pass 2: for every used symbol we need to walk its + // initialization code to figure out if it uses other + // symbols (that may not be in_use). + tw = new TreeWalker(scan_ref_scoped); + in_use_ids.forEach(function (def) { + var init = initializations.get(def.id); + if (init) init.forEach(function(init) { + init.walk(tw); + }); + }); + // pass 3: we should drop declarations not in_use + var tt = new TreeTransformer( + function before(node, descend, in_list) { + var parent = tt.parent(); + if (drop_vars) { + const sym = assign_as_unused(node); + if (sym instanceof AST_SymbolRef) { + var def = sym.definition(); + var in_use = in_use_ids.has(def.id); + if (node instanceof AST_Assign) { + if (!in_use || fixed_ids.has(def.id) && fixed_ids.get(def.id) !== node) { + return maintain_this_binding(parent, node, node.right.transform(tt)); + } + } else if (!in_use) return in_list ? MAP.skip : make_node(AST_Number, node, { + value: 0 + }); + } + } + if (scope !== self) return; + var def; + if (node.name + && (node instanceof AST_ClassExpression + && !keep_name(compressor.option("keep_classnames"), (def = node.name.definition()).name) + || node instanceof AST_Function + && !keep_name(compressor.option("keep_fnames"), (def = node.name.definition()).name))) { + // any declarations with same name will overshadow + // name of this anonymous function and can therefore + // never be used anywhere + if (!in_use_ids.has(def.id) || def.orig.length > 1) node.name = null; + } + if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) { + var trim = !compressor.option("keep_fargs"); + for (var a = node.argnames, i = a.length; --i >= 0;) { + var sym = a[i]; + if (sym instanceof AST_Expansion) { + sym = sym.expression; + } + if (sym instanceof AST_DefaultAssign) { + sym = sym.left; + } + // Do not drop destructuring arguments. + // They constitute a type assertion, so dropping + // them would stop that TypeError which would happen + // if someone called it with an incorrectly formatted + // parameter. + if (!(sym instanceof AST_Destructuring) && !in_use_ids.has(sym.definition().id)) { + set_flag(sym, UNUSED); + if (trim) { + a.pop(); + } + } else { + trim = false; + } + } + } + if ((node instanceof AST_Defun || node instanceof AST_DefClass) && node !== self) { + const def = node.name.definition(); + let keep = def.global && !drop_funcs || in_use_ids.has(def.id); + if (!keep) { + def.eliminated++; + if (node instanceof AST_DefClass) { + // Classes might have extends with side effects + const side_effects = node.drop_side_effect_free(compressor); + if (side_effects) { + return make_node(AST_SimpleStatement, node, { + body: side_effects + }); + } + } + return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); + } + } + if (node instanceof AST_Definitions && !(parent instanceof AST_ForIn && parent.init === node)) { + var drop_block = !(parent instanceof AST_Toplevel) && !(node instanceof AST_Var); + // place uninitialized names at the start + var body = [], head = [], tail = []; + // for unused names whose initialization has + // side effects, we can cascade the init. code + // into the next one, or next statement. + var side_effects = []; + node.definitions.forEach(function(def) { + if (def.value) def.value = def.value.transform(tt); + var is_destructure = def.name instanceof AST_Destructuring; + var sym = is_destructure + ? new SymbolDef(null, { name: "" }) /* fake SymbolDef */ + : def.name.definition(); + if (drop_block && sym.global) return tail.push(def); + if (!(drop_vars || drop_block) + || is_destructure + && (def.name.names.length + || def.name.is_array + || compressor.option("pure_getters") != true) + || in_use_ids.has(sym.id) + ) { + if (def.value && fixed_ids.has(sym.id) && fixed_ids.get(sym.id) !== def) { + def.value = def.value.drop_side_effect_free(compressor); + } + if (def.name instanceof AST_SymbolVar) { + var var_defs = var_defs_by_id.get(sym.id); + if (var_defs.length > 1 && (!def.value || sym.orig.indexOf(def.name) > sym.eliminated)) { + if (def.value) { + var ref = make_node(AST_SymbolRef, def.name, def.name); + sym.references.push(ref); + var assign = make_node(AST_Assign, def, { + operator: "=", + logical: false, + left: ref, + right: def.value + }); + if (fixed_ids.get(sym.id) === def) { + fixed_ids.set(sym.id, assign); + } + side_effects.push(assign.transform(tt)); + } + remove(var_defs, def); + sym.eliminated++; + return; + } + } + if (def.value) { + if (side_effects.length > 0) { + if (tail.length > 0) { + side_effects.push(def.value); + def.value = make_sequence(def.value, side_effects); + } else { + body.push(make_node(AST_SimpleStatement, node, { + body: make_sequence(node, side_effects) + })); + } + side_effects = []; + } + tail.push(def); + } else { + head.push(def); + } + } else if (sym.orig[0] instanceof AST_SymbolCatch) { + var value = def.value && def.value.drop_side_effect_free(compressor); + if (value) side_effects.push(value); + def.value = null; + head.push(def); + } else { + var value = def.value && def.value.drop_side_effect_free(compressor); + if (value) { + side_effects.push(value); + } + sym.eliminated++; + } + }); + if (head.length > 0 || tail.length > 0) { + node.definitions = head.concat(tail); + body.push(node); + } + if (side_effects.length > 0) { + body.push(make_node(AST_SimpleStatement, node, { + body: make_sequence(node, side_effects) + })); + } + switch (body.length) { + case 0: + return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); + case 1: + return body[0]; + default: + return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, { + body: body + }); + } + } + // certain combination of unused name + side effect leads to: + // https://github.com/mishoo/UglifyJS2/issues/44 + // https://github.com/mishoo/UglifyJS2/issues/1830 + // https://github.com/mishoo/UglifyJS2/issues/1838 + // that's an invalid AST. + // We fix it at this stage by moving the `var` outside the `for`. + if (node instanceof AST_For) { + descend(node, this); + var block; + if (node.init instanceof AST_BlockStatement) { + block = node.init; + node.init = block.body.pop(); + block.body.push(node); + } + if (node.init instanceof AST_SimpleStatement) { + node.init = node.init.body; + } else if (is_empty(node.init)) { + node.init = null; + } + return !block ? node : in_list ? MAP.splice(block.body) : block; + } + if (node instanceof AST_LabeledStatement + && node.body instanceof AST_For + ) { + descend(node, this); + if (node.body instanceof AST_BlockStatement) { + var block = node.body; + node.body = block.body.pop(); + block.body.push(node); + return in_list ? MAP.splice(block.body) : block; + } + return node; + } + if (node instanceof AST_BlockStatement) { + descend(node, this); + if (in_list && node.body.every(can_be_evicted_from_block)) { + return MAP.splice(node.body); + } + return node; + } + if (node instanceof AST_Scope) { + const save_scope = scope; + scope = node; + descend(node, this); + scope = save_scope; + return node; + } + } + ); + + self.transform(tt); + + function scan_ref_scoped(node, descend) { + var node_def; + const sym = assign_as_unused(node); + if (sym instanceof AST_SymbolRef + && !is_ref_of(node.left, AST_SymbolBlockDeclaration) + && self.variables.get(sym.name) === (node_def = sym.definition()) + ) { + if (node instanceof AST_Assign) { + node.right.walk(tw); + if (!node_def.chained && node.left.fixed_value() === node.right) { + fixed_ids.set(node_def.id, node); + } + } + return true; + } + if (node instanceof AST_SymbolRef) { + node_def = node.definition(); + if (!in_use_ids.has(node_def.id)) { + in_use_ids.set(node_def.id, node_def); + if (node_def.orig[0] instanceof AST_SymbolCatch) { + const redef = node_def.scope.is_block_scope() + && node_def.scope.get_defun_scope().variables.get(node_def.name); + if (redef) in_use_ids.set(redef.id, redef); + } + } + return true; + } + if (node instanceof AST_Scope) { + var save_scope = scope; + scope = node; + descend(); + scope = save_scope; + return true; + } + } +}); + +AST_Scope.DEFMETHOD("hoist_declarations", function(compressor) { + var self = this; + if (compressor.has_directive("use asm")) return self; + // Hoisting makes no sense in an arrow func + if (!Array.isArray(self.body)) return self; + + var hoist_funs = compressor.option("hoist_funs"); + var hoist_vars = compressor.option("hoist_vars"); + + if (hoist_funs || hoist_vars) { + var dirs = []; + var hoisted = []; + var vars = new Map(), vars_found = 0, var_decl = 0; + // let's count var_decl first, we seem to waste a lot of + // space if we hoist `var` when there's only one. + walk(self, node => { + if (node instanceof AST_Scope && node !== self) + return true; + if (node instanceof AST_Var) { + ++var_decl; + return true; + } + }); + hoist_vars = hoist_vars && var_decl > 1; + var tt = new TreeTransformer( + function before(node) { + if (node !== self) { + if (node instanceof AST_Directive) { + dirs.push(node); + return make_node(AST_EmptyStatement, node); + } + if (hoist_funs && node instanceof AST_Defun + && !(tt.parent() instanceof AST_Export) + && tt.parent() === self) { + hoisted.push(node); + return make_node(AST_EmptyStatement, node); + } + if ( + hoist_vars + && node instanceof AST_Var + && !node.definitions.some(def => def.name instanceof AST_Destructuring) + ) { + node.definitions.forEach(function(def) { + vars.set(def.name.name, def); + ++vars_found; + }); + var seq = node.to_assignments(compressor); + var p = tt.parent(); + if (p instanceof AST_ForIn && p.init === node) { + if (seq == null) { + var def = node.definitions[0].name; + return make_node(AST_SymbolRef, def, def); + } + return seq; + } + if (p instanceof AST_For && p.init === node) { + return seq; + } + if (!seq) return make_node(AST_EmptyStatement, node); + return make_node(AST_SimpleStatement, node, { + body: seq + }); + } + if (node instanceof AST_Scope) + return node; // to avoid descending in nested scopes + } + } + ); + self = self.transform(tt); + if (vars_found > 0) { + // collect only vars which don't show up in self's arguments list + var defs = []; + const is_lambda = self instanceof AST_Lambda; + const args_as_names = is_lambda ? self.args_as_names() : null; + vars.forEach((def, name) => { + if (is_lambda && args_as_names.some((x) => x.name === def.name.name)) { + vars.delete(name); + } else { + def = def.clone(); + def.value = null; + defs.push(def); + vars.set(name, def); + } + }); + if (defs.length > 0) { + // try to merge in assignments + for (var i = 0; i < self.body.length;) { + if (self.body[i] instanceof AST_SimpleStatement) { + var expr = self.body[i].body, sym, assign; + if (expr instanceof AST_Assign + && expr.operator == "=" + && (sym = expr.left) instanceof AST_Symbol + && vars.has(sym.name) + ) { + var def = vars.get(sym.name); + if (def.value) break; + def.value = expr.right; + remove(defs, def); + defs.push(def); + self.body.splice(i, 1); + continue; + } + if (expr instanceof AST_Sequence + && (assign = expr.expressions[0]) instanceof AST_Assign + && assign.operator == "=" + && (sym = assign.left) instanceof AST_Symbol + && vars.has(sym.name) + ) { + var def = vars.get(sym.name); + if (def.value) break; + def.value = assign.right; + remove(defs, def); + defs.push(def); + self.body[i].body = make_sequence(expr, expr.expressions.slice(1)); + continue; + } + } + if (self.body[i] instanceof AST_EmptyStatement) { + self.body.splice(i, 1); + continue; + } + if (self.body[i] instanceof AST_BlockStatement) { + self.body.splice(i, 1, ...self.body[i].body); + continue; + } + break; + } + defs = make_node(AST_Var, self, { + definitions: defs + }); + hoisted.push(defs); + } + } + self.body = dirs.concat(hoisted, self.body); + } + return self; +}); + +AST_Scope.DEFMETHOD("hoist_properties", function(compressor) { + var self = this; + if (!compressor.option("hoist_props") || compressor.has_directive("use asm")) return self; + var top_retain = self instanceof AST_Toplevel && compressor.top_retain || return_false; + var defs_by_id = new Map(); + var hoister = new TreeTransformer(function(node, descend) { + if (node instanceof AST_Definitions + && hoister.parent() instanceof AST_Export) return node; + if (node instanceof AST_VarDef) { + const sym = node.name; + let def; + let value; + if (sym.scope === self + && (def = sym.definition()).escaped != 1 + && !def.assignments + && !def.direct_access + && !def.single_use + && !compressor.exposed(def) + && !top_retain(def) + && (value = sym.fixed_value()) === node.value + && value instanceof AST_Object + && !value.properties.some(prop => + prop instanceof AST_Expansion || prop.computed_key() + ) + ) { + descend(node, this); + const defs = new Map(); + const assignments = []; + value.properties.forEach(({ key, value }) => { + const scope = find_scope(hoister); + const symbol = self.create_symbol(sym.CTOR, { + source: sym, + scope, + conflict_scopes: new Set([ + scope, + ...sym.definition().references.map(ref => ref.scope) + ]), + tentative_name: sym.name + "_" + key + }); + + defs.set(String(key), symbol.definition()); + + assignments.push(make_node(AST_VarDef, node, { + name: symbol, + value + })); + }); + defs_by_id.set(def.id, defs); + return MAP.splice(assignments); + } + } else if (node instanceof AST_PropAccess + && node.expression instanceof AST_SymbolRef + ) { + const defs = defs_by_id.get(node.expression.definition().id); + if (defs) { + const def = defs.get(String(get_simple_key(node.property))); + const sym = make_node(AST_SymbolRef, node, { + name: def.name, + scope: node.expression.scope, + thedef: def + }); + sym.reference({}); + return sym; + } + } + }); + return self.transform(hoister); +}); + +def_optimize(AST_SimpleStatement, function(self, compressor) { + if (compressor.option("side_effects")) { + var body = self.body; + var node = body.drop_side_effect_free(compressor, true); + if (!node) { + return make_node(AST_EmptyStatement, self); + } + if (node !== body) { + return make_node(AST_SimpleStatement, self, { body: node }); + } + } + return self; +}); + +def_optimize(AST_While, function(self, compressor) { + return compressor.option("loops") ? make_node(AST_For, self, self).optimize(compressor) : self; +}); + +def_optimize(AST_Do, function(self, compressor) { + if (!compressor.option("loops")) return self; + var cond = self.condition.tail_node().evaluate(compressor); + if (!(cond instanceof AST_Node)) { + if (cond) return make_node(AST_For, self, { + body: make_node(AST_BlockStatement, self.body, { + body: [ + self.body, + make_node(AST_SimpleStatement, self.condition, { + body: self.condition + }) + ] + }) + }).optimize(compressor); + if (!has_break_or_continue(self, compressor.parent())) { + return make_node(AST_BlockStatement, self.body, { + body: [ + self.body, + make_node(AST_SimpleStatement, self.condition, { + body: self.condition + }) + ] + }).optimize(compressor); + } + } + return self; +}); + +function if_break_in_loop(self, compressor) { + var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body; + if (compressor.option("dead_code") && is_break(first)) { + var body = []; + if (self.init instanceof AST_Statement) { + body.push(self.init); + } else if (self.init) { + body.push(make_node(AST_SimpleStatement, self.init, { + body: self.init + })); + } + if (self.condition) { + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + } + trim_unreachable_code(compressor, self.body, body); + return make_node(AST_BlockStatement, self, { + body: body + }); + } + if (first instanceof AST_If) { + if (is_break(first.body)) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition.negate(compressor), + }); + } else { + self.condition = first.condition.negate(compressor); + } + drop_it(first.alternative); + } else if (is_break(first.alternative)) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition, + }); + } else { + self.condition = first.condition; + } + drop_it(first.body); + } + } + return self; + + function is_break(node) { + return node instanceof AST_Break + && compressor.loopcontrol_target(node) === compressor.self(); + } + + function drop_it(rest) { + rest = as_statement_array(rest); + if (self.body instanceof AST_BlockStatement) { + self.body = self.body.clone(); + self.body.body = rest.concat(self.body.body.slice(1)); + self.body = self.body.transform(compressor); + } else { + self.body = make_node(AST_BlockStatement, self.body, { + body: rest + }).transform(compressor); + } + self = if_break_in_loop(self, compressor); + } +} + +def_optimize(AST_For, function(self, compressor) { + if (!compressor.option("loops")) return self; + if (compressor.option("side_effects") && self.init) { + self.init = self.init.drop_side_effect_free(compressor); + } + if (self.condition) { + var cond = self.condition.evaluate(compressor); + if (!(cond instanceof AST_Node)) { + if (cond) self.condition = null; + else if (!compressor.option("dead_code")) { + var orig = self.condition; + self.condition = make_node_from_constant(cond, self.condition); + self.condition = best_of_expression(self.condition.transform(compressor), orig); + } + } + if (compressor.option("dead_code")) { + if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor); + if (!cond) { + var body = []; + trim_unreachable_code(compressor, self.body, body); + if (self.init instanceof AST_Statement) { + body.push(self.init); + } else if (self.init) { + body.push(make_node(AST_SimpleStatement, self.init, { + body: self.init + })); + } + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } + } + } + return if_break_in_loop(self, compressor); +}); + +def_optimize(AST_If, function(self, compressor) { + if (is_empty(self.alternative)) self.alternative = null; + + if (!compressor.option("conditionals")) return self; + // if condition can be statically determined, drop + // one of the blocks. note, statically determined implies + // “has no side effects”; also it doesn't work for cases like + // `x && true`, though it probably should. + var cond = self.condition.evaluate(compressor); + if (!compressor.option("dead_code") && !(cond instanceof AST_Node)) { + var orig = self.condition; + self.condition = make_node_from_constant(cond, orig); + self.condition = best_of_expression(self.condition.transform(compressor), orig); + } + if (compressor.option("dead_code")) { + if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor); + if (!cond) { + var body = []; + trim_unreachable_code(compressor, self.body, body); + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + if (self.alternative) body.push(self.alternative); + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } else if (!(cond instanceof AST_Node)) { + var body = []; + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + body.push(self.body); + if (self.alternative) { + trim_unreachable_code(compressor, self.alternative, body); + } + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } + } + var negated = self.condition.negate(compressor); + var self_condition_length = self.condition.size(); + var negated_length = negated.size(); + var negated_is_best = negated_length < self_condition_length; + if (self.alternative && negated_is_best) { + negated_is_best = false; // because we already do the switch here. + // no need to swap values of self_condition_length and negated_length + // here because they are only used in an equality comparison later on. + self.condition = negated; + var tmp = self.body; + self.body = self.alternative || make_node(AST_EmptyStatement, self); + self.alternative = tmp; + } + if (is_empty(self.body) && is_empty(self.alternative)) { + return make_node(AST_SimpleStatement, self.condition, { + body: self.condition.clone() + }).optimize(compressor); + } + if (self.body instanceof AST_SimpleStatement + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.body, + alternative : self.alternative.body + }) + }).optimize(compressor); + } + if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) { + if (self_condition_length === negated_length && !negated_is_best + && self.condition instanceof AST_Binary && self.condition.operator == "||") { + // although the code length of self.condition and negated are the same, + // negated does not require additional surrounding parentheses. + // see https://github.com/mishoo/UglifyJS2/issues/979 + negated_is_best = true; + } + if (negated_is_best) return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : negated, + right : self.body.body + }) + }).optimize(compressor); + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "&&", + left : self.condition, + right : self.body.body + }) + }).optimize(compressor); + } + if (self.body instanceof AST_EmptyStatement + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : self.condition, + right : self.alternative.body + }) + }).optimize(compressor); + } + if (self.body instanceof AST_Exit + && self.alternative instanceof AST_Exit + && self.body.TYPE == self.alternative.TYPE) { + return make_node(self.body.CTOR, self, { + value: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.value || make_node(AST_Undefined, self.body), + alternative : self.alternative.value || make_node(AST_Undefined, self.alternative) + }).transform(compressor) + }).optimize(compressor); + } + if (self.body instanceof AST_If + && !self.body.alternative + && !self.alternative) { + self = make_node(AST_If, self, { + condition: make_node(AST_Binary, self.condition, { + operator: "&&", + left: self.condition, + right: self.body.condition + }), + body: self.body.body, + alternative: null + }); + } + if (aborts(self.body)) { + if (self.alternative) { + var alt = self.alternative; + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, alt ] + }).optimize(compressor); + } + } + if (aborts(self.alternative)) { + var body = self.body; + self.body = self.alternative; + self.condition = negated_is_best ? negated : self.condition.negate(compressor); + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, body ] + }).optimize(compressor); + } + return self; +}); + +def_optimize(AST_Switch, function(self, compressor) { + if (!compressor.option("switches")) return self; + var branch; + var value = self.expression.evaluate(compressor); + if (!(value instanceof AST_Node)) { + var orig = self.expression; + self.expression = make_node_from_constant(value, orig); + self.expression = best_of_expression(self.expression.transform(compressor), orig); + } + if (!compressor.option("dead_code")) return self; + if (value instanceof AST_Node) { + value = self.expression.tail_node().evaluate(compressor); + } + var decl = []; + var body = []; + var default_branch; + var exact_match; + for (var i = 0, len = self.body.length; i < len && !exact_match; i++) { + branch = self.body[i]; + if (branch instanceof AST_Default) { + if (!default_branch) { + default_branch = branch; + } else { + eliminate_branch(branch, body[body.length - 1]); + } + } else if (!(value instanceof AST_Node)) { + var exp = branch.expression.evaluate(compressor); + if (!(exp instanceof AST_Node) && exp !== value) { + eliminate_branch(branch, body[body.length - 1]); + continue; + } + if (exp instanceof AST_Node) exp = branch.expression.tail_node().evaluate(compressor); + if (exp === value) { + exact_match = branch; + if (default_branch) { + var default_index = body.indexOf(default_branch); + body.splice(default_index, 1); + eliminate_branch(default_branch, body[default_index - 1]); + default_branch = null; + } + } + } + body.push(branch); + } + while (i < len) eliminate_branch(self.body[i++], body[body.length - 1]); + self.body = body; + + let default_or_exact = default_branch || exact_match; + default_branch = null; + exact_match = null; + + // group equivalent branches so they will be located next to each other, + // that way the next micro-optimization will merge them. + // ** bail micro-optimization if not a simple switch case with breaks + if (body.every((branch, i) => + (branch === default_or_exact || branch.expression instanceof AST_Constant) + && (branch.body.length === 0 || aborts(branch) || body.length - 1 === i)) + ) { + for (let i = 0; i < body.length; i++) { + const branch = body[i]; + for (let j = i + 1; j < body.length; j++) { + const next = body[j]; + if (next.body.length === 0) continue; + const last_branch = j === (body.length - 1); + const equivalentBranch = branches_equivalent(next, branch, false); + if (equivalentBranch || (last_branch && branches_equivalent(next, branch, true))) { + if (!equivalentBranch && last_branch) { + next.body.push(make_node(AST_Break)); + } + + // let's find previous siblings with inert fallthrough... + let x = j - 1; + let fallthroughDepth = 0; + while (x > i) { + if (is_inert_body(body[x--])) { + fallthroughDepth++; + } else { + break; + } + } + + const plucked = body.splice(j - fallthroughDepth, 1 + fallthroughDepth); + body.splice(i + 1, 0, ...plucked); + i += plucked.length; + } + } + } + } + + // merge equivalent branches in a row + for (let i = 0; i < body.length; i++) { + let branch = body[i]; + if (branch.body.length === 0) continue; + if (!aborts(branch)) continue; + + for (let j = i + 1; j < body.length; i++, j++) { + let next = body[j]; + if (next.body.length === 0) continue; + if ( + branches_equivalent(next, branch, false) + || (j === body.length - 1 && branches_equivalent(next, branch, true)) + ) { + branch.body = []; + branch = next; + continue; + } + break; + } + } + + // Prune any empty branches at the end of the switch statement. + { + let i = body.length - 1; + for (; i >= 0; i--) { + let bbody = body[i].body; + if (is_break(bbody[bbody.length - 1], compressor)) bbody.pop(); + if (!is_inert_body(body[i])) break; + } + // i now points to the index of a branch that contains a body. By incrementing, it's + // pointing to the first branch that's empty. + i++; + if (!default_or_exact || body.indexOf(default_or_exact) >= i) { + // The default behavior is to do nothing. We can take advantage of that to + // remove all case expressions that are side-effect free that also do + // nothing, since they'll default to doing nothing. But we can't remove any + // case expressions before one that would side-effect, since they may cause + // the side-effect to be skipped. + for (let j = body.length - 1; j >= i; j--) { + let branch = body[j]; + if (branch === default_or_exact) { + default_or_exact = null; + body.pop(); + } else if (!branch.expression.has_side_effects(compressor)) { + body.pop(); + } else { + break; + } + } + } + } + + + // Prune side-effect free branches that fall into default. + DEFAULT: if (default_or_exact) { + let default_index = body.indexOf(default_or_exact); + let default_body_index = default_index; + for (; default_body_index < body.length - 1; default_body_index++) { + if (!is_inert_body(body[default_body_index])) break; + } + if (default_body_index < body.length - 1) { + break DEFAULT; + } + + let side_effect_index = body.length - 1; + for (; side_effect_index >= 0; side_effect_index--) { + let branch = body[side_effect_index]; + if (branch === default_or_exact) continue; + if (branch.expression.has_side_effects(compressor)) break; + } + // If the default behavior comes after any side-effect case expressions, + // then we can fold all side-effect free cases into the default branch. + // If the side-effect case is after the default, then any side-effect + // free cases could prevent the side-effect from occurring. + if (default_body_index > side_effect_index) { + let prev_body_index = default_index - 1; + for (; prev_body_index >= 0; prev_body_index--) { + if (!is_inert_body(body[prev_body_index])) break; + } + let before = Math.max(side_effect_index, prev_body_index) + 1; + let after = default_index; + if (side_effect_index > default_index) { + // If the default falls into the same body as a side-effect + // case, then we need preserve that case and only prune the + // cases after it. + after = side_effect_index; + body[side_effect_index].body = body[default_body_index].body; + } else { + // The default will be the last branch. + default_or_exact.body = body[default_body_index].body; + } + + // Prune everything after the default (or last side-effect case) + // until the next case with a body. + body.splice(after + 1, default_body_index - after); + // Prune everything before the default that falls into it. + body.splice(before, default_index - before); + } + } + + // See if we can remove the switch entirely if all cases (the default) fall into the same case body. + DEFAULT: if (default_or_exact) { + let i = body.findIndex(branch => !is_inert_body(branch)); + let caseBody; + // `i` is equal to one of the following: + // - `-1`, there is no body in the switch statement. + // - `body.length - 1`, all cases fall into the same body. + // - anything else, there are multiple bodies in the switch. + if (i === body.length - 1) { + // All cases fall into the case body. + let branch = body[i]; + if (has_nested_break(self)) break DEFAULT; + + // This is the last case body, and we've already pruned any breaks, so it's + // safe to hoist. + caseBody = make_node(AST_BlockStatement, branch, { + body: branch.body + }); + branch.body = []; + } else if (i !== -1) { + // If there are multiple bodies, then we cannot optimize anything. + break DEFAULT; + } + + let sideEffect = body.find(branch => { + return ( + branch !== default_or_exact + && branch.expression.has_side_effects(compressor) + ); + }); + // If no cases cause a side-effect, we can eliminate the switch entirely. + if (!sideEffect) { + return make_node(AST_BlockStatement, self, { + body: decl.concat( + statement(self.expression), + default_or_exact.expression ? statement(default_or_exact.expression) : [], + caseBody || [] + ) + }).optimize(compressor); + } + + // If we're this far, either there was no body or all cases fell into the same body. + // If there was no body, then we don't need a default branch (because the default is + // do nothing). If there was a body, we'll extract it to after the switch, so the + // switch's new default is to do nothing and we can still prune it. + const default_index = body.indexOf(default_or_exact); + body.splice(default_index, 1); + default_or_exact = null; + + if (caseBody) { + // Recurse into switch statement one more time so that we can append the case body + // outside of the switch. This recursion will only happen once since we've pruned + // the default case. + return make_node(AST_BlockStatement, self, { + body: decl.concat(self, caseBody) + }).optimize(compressor); + } + // If we fall here, there is a default branch somewhere, there are no case bodies, + // and there's a side-effect somewhere. Just let the below paths take care of it. + } + + if (body.length > 0) { + body[0].body = decl.concat(body[0].body); + } + + if (body.length == 0) { + return make_node(AST_BlockStatement, self, { + body: decl.concat(statement(self.expression)) + }).optimize(compressor); + } + if (body.length == 1 && !has_nested_break(self)) { + // This is the last case body, and we've already pruned any breaks, so it's + // safe to hoist. + let branch = body[0]; + return make_node(AST_If, self, { + condition: make_node(AST_Binary, self, { + operator: "===", + left: self.expression, + right: branch.expression, + }), + body: make_node(AST_BlockStatement, branch, { + body: branch.body + }), + alternative: null + }).optimize(compressor); + } + if (body.length === 2 && default_or_exact && !has_nested_break(self)) { + let branch = body[0] === default_or_exact ? body[1] : body[0]; + let exact_exp = default_or_exact.expression && statement(default_or_exact.expression); + if (aborts(body[0])) { + // Only the first branch body could have a break (at the last statement) + let first = body[0]; + if (is_break(first.body[first.body.length - 1], compressor)) { + first.body.pop(); + } + return make_node(AST_If, self, { + condition: make_node(AST_Binary, self, { + operator: "===", + left: self.expression, + right: branch.expression, + }), + body: make_node(AST_BlockStatement, branch, { + body: branch.body + }), + alternative: make_node(AST_BlockStatement, default_or_exact, { + body: [].concat( + exact_exp || [], + default_or_exact.body + ) + }) + }).optimize(compressor); + } + let operator = "==="; + let consequent = make_node(AST_BlockStatement, branch, { + body: branch.body, + }); + let always = make_node(AST_BlockStatement, default_or_exact, { + body: [].concat( + exact_exp || [], + default_or_exact.body + ) + }); + if (body[0] === default_or_exact) { + operator = "!=="; + let tmp = always; + always = consequent; + consequent = tmp; + } + return make_node(AST_BlockStatement, self, { + body: [ + make_node(AST_If, self, { + condition: make_node(AST_Binary, self, { + operator: operator, + left: self.expression, + right: branch.expression, + }), + body: consequent, + alternative: null + }) + ].concat(always) + }).optimize(compressor); + } + return self; + + function eliminate_branch(branch, prev) { + if (prev && !aborts(prev)) { + prev.body = prev.body.concat(branch.body); + } else { + trim_unreachable_code(compressor, branch, decl); + } + } + function branches_equivalent(branch, prev, insertBreak) { + let bbody = branch.body; + let pbody = prev.body; + if (insertBreak) { + bbody = bbody.concat(make_node(AST_Break)); + } + if (bbody.length !== pbody.length) return false; + let bblock = make_node(AST_BlockStatement, branch, { body: bbody }); + let pblock = make_node(AST_BlockStatement, prev, { body: pbody }); + return bblock.equivalent_to(pblock); + } + function statement(expression) { + return make_node(AST_SimpleStatement, expression, { + body: expression + }); + } + function has_nested_break(root) { + let has_break = false; + let tw = new TreeWalker(node => { + if (has_break) return true; + if (node instanceof AST_Lambda) return true; + if (node instanceof AST_SimpleStatement) return true; + if (!is_break(node, tw)) return; + let parent = tw.parent(); + if ( + parent instanceof AST_SwitchBranch + && parent.body[parent.body.length - 1] === node + ) { + return; + } + has_break = true; + }); + root.walk(tw); + return has_break; + } + function is_break(node, stack) { + return node instanceof AST_Break + && stack.loopcontrol_target(node) === self; + } + function is_inert_body(branch) { + return !aborts(branch) && !make_node(AST_BlockStatement, branch, { + body: branch.body + }).has_side_effects(compressor); + } +}); + +def_optimize(AST_Try, function(self, compressor) { + tighten_body(self.body, compressor); + if (self.bcatch && self.bfinally && self.bfinally.body.every(is_empty)) self.bfinally = null; + if (compressor.option("dead_code") && self.body.every(is_empty)) { + var body = []; + if (self.bcatch) { + trim_unreachable_code(compressor, self.bcatch, body); + } + if (self.bfinally) body.push(...self.bfinally.body); + return make_node(AST_BlockStatement, self, { + body: body + }).optimize(compressor); + } + return self; +}); + +AST_Definitions.DEFMETHOD("remove_initializers", function() { + var decls = []; + this.definitions.forEach(function(def) { + if (def.name instanceof AST_SymbolDeclaration) { + def.value = null; + decls.push(def); + } else { + walk(def.name, node => { + if (node instanceof AST_SymbolDeclaration) { + decls.push(make_node(AST_VarDef, def, { + name: node, + value: null + })); + } + }); + } + }); + this.definitions = decls; +}); + +AST_Definitions.DEFMETHOD("to_assignments", function(compressor) { + var reduce_vars = compressor.option("reduce_vars"); + var assignments = []; + + for (const def of this.definitions) { + if (def.value) { + var name = make_node(AST_SymbolRef, def.name, def.name); + assignments.push(make_node(AST_Assign, def, { + operator : "=", + logical: false, + left : name, + right : def.value + })); + if (reduce_vars) name.definition().fixed = false; + } else if (def.value) { + // Because it's a destructuring, do not turn into an assignment. + var varDef = make_node(AST_VarDef, def, { + name: def.name, + value: def.value + }); + var var_ = make_node(AST_Var, def, { + definitions: [ varDef ] + }); + assignments.push(var_); + } + const thedef = def.name.definition(); + thedef.eliminated++; + thedef.replaced--; + } + + if (assignments.length == 0) return null; + return make_sequence(this, assignments); +}); + +def_optimize(AST_Definitions, function(self) { + if (self.definitions.length == 0) + return make_node(AST_EmptyStatement, self); + return self; +}); + +def_optimize(AST_VarDef, function(self, compressor) { + if ( + self.name instanceof AST_SymbolLet + && self.value != null + && is_undefined(self.value, compressor) + ) { + self.value = null; + } + return self; +}); + +def_optimize(AST_Import, function(self) { + return self; +}); + +// TODO this only works with AST_Defun, shouldn't it work for other ways of defining functions? +function retain_top_func(fn, compressor) { + return compressor.top_retain + && fn instanceof AST_Defun + && has_flag(fn, TOP) + && fn.name + && compressor.top_retain(fn.name); +} + +def_optimize(AST_Call, function(self, compressor) { + var exp = self.expression; + var fn = exp; + inline_array_like_spread(self.args); + var simple_args = self.args.every((arg) => + !(arg instanceof AST_Expansion) + ); + + if (compressor.option("reduce_vars") + && fn instanceof AST_SymbolRef + && !has_annotation(self, _NOINLINE) + ) { + const fixed = fn.fixed_value(); + if (!retain_top_func(fixed, compressor)) { + fn = fixed; + } + } + + var is_func = fn instanceof AST_Lambda; + + if (is_func && fn.pinned()) return self; + + if (compressor.option("unused") + && simple_args + && is_func + && !fn.uses_arguments) { + var pos = 0, last = 0; + for (var i = 0, len = self.args.length; i < len; i++) { + if (fn.argnames[i] instanceof AST_Expansion) { + if (has_flag(fn.argnames[i].expression, UNUSED)) while (i < len) { + var node = self.args[i++].drop_side_effect_free(compressor); + if (node) { + self.args[pos++] = node; + } + } else while (i < len) { + self.args[pos++] = self.args[i++]; + } + last = pos; + break; + } + var trim = i >= fn.argnames.length; + if (trim || has_flag(fn.argnames[i], UNUSED)) { + var node = self.args[i].drop_side_effect_free(compressor); + if (node) { + self.args[pos++] = node; + } else if (!trim) { + self.args[pos++] = make_node(AST_Number, self.args[i], { + value: 0 + }); + continue; + } + } else { + self.args[pos++] = self.args[i]; + } + last = pos; + } + self.args.length = last; + } + + if (compressor.option("unsafe")) { + if (exp instanceof AST_Dot && exp.start.value === "Array" && exp.property === "from" && self.args.length === 1) { + const [argument] = self.args; + if (argument instanceof AST_Array) { + return make_node(AST_Array, argument, { + elements: argument.elements + }).optimize(compressor); + } + } + if (is_undeclared_ref(exp)) switch (exp.name) { + case "Array": + if (self.args.length != 1) { + return make_node(AST_Array, self, { + elements: self.args + }).optimize(compressor); + } else if (self.args[0] instanceof AST_Number && self.args[0].value <= 11) { + const elements = []; + for (let i = 0; i < self.args[0].value; i++) elements.push(new AST_Hole); + return new AST_Array({ elements }); + } + break; + case "Object": + if (self.args.length == 0) { + return make_node(AST_Object, self, { + properties: [] + }); + } + break; + case "String": + if (self.args.length == 0) return make_node(AST_String, self, { + value: "" + }); + if (self.args.length <= 1) return make_node(AST_Binary, self, { + left: self.args[0], + operator: "+", + right: make_node(AST_String, self, { value: "" }) + }).optimize(compressor); + break; + case "Number": + if (self.args.length == 0) return make_node(AST_Number, self, { + value: 0 + }); + if (self.args.length == 1 && compressor.option("unsafe_math")) { + return make_node(AST_UnaryPrefix, self, { + expression: self.args[0], + operator: "+" + }).optimize(compressor); + } + break; + case "Symbol": + if (self.args.length == 1 && self.args[0] instanceof AST_String && compressor.option("unsafe_symbols")) + self.args.length = 0; + break; + case "Boolean": + if (self.args.length == 0) return make_node(AST_False, self); + if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { + expression: make_node(AST_UnaryPrefix, self, { + expression: self.args[0], + operator: "!" + }), + operator: "!" + }).optimize(compressor); + break; + case "RegExp": + var params = []; + if (self.args.length >= 1 + && self.args.length <= 2 + && self.args.every((arg) => { + var value = arg.evaluate(compressor); + params.push(value); + return arg !== value; + }) + ) { + let [ source, flags ] = params; + source = regexp_source_fix(new RegExp(source).source); + const rx = make_node(AST_RegExp, self, { + value: { source, flags } + }); + if (rx._eval(compressor) !== rx) { + return rx; + } + } + break; + } else if (exp instanceof AST_Dot) switch(exp.property) { + case "toString": + if (self.args.length == 0 && !exp.expression.may_throw_on_access(compressor)) { + return make_node(AST_Binary, self, { + left: make_node(AST_String, self, { value: "" }), + operator: "+", + right: exp.expression + }).optimize(compressor); + } + break; + case "join": + if (exp.expression instanceof AST_Array) EXIT: { + var separator; + if (self.args.length > 0) { + separator = self.args[0].evaluate(compressor); + if (separator === self.args[0]) break EXIT; // not a constant + } + var elements = []; + var consts = []; + for (var i = 0, len = exp.expression.elements.length; i < len; i++) { + var el = exp.expression.elements[i]; + if (el instanceof AST_Expansion) break EXIT; + var value = el.evaluate(compressor); + if (value !== el) { + consts.push(value); + } else { + if (consts.length > 0) { + elements.push(make_node(AST_String, self, { + value: consts.join(separator) + })); + consts.length = 0; + } + elements.push(el); + } + } + if (consts.length > 0) { + elements.push(make_node(AST_String, self, { + value: consts.join(separator) + })); + } + if (elements.length == 0) return make_node(AST_String, self, { value: "" }); + if (elements.length == 1) { + if (elements[0].is_string(compressor)) { + return elements[0]; + } + return make_node(AST_Binary, elements[0], { + operator : "+", + left : make_node(AST_String, self, { value: "" }), + right : elements[0] + }); + } + if (separator == "") { + var first; + if (elements[0].is_string(compressor) + || elements[1].is_string(compressor)) { + first = elements.shift(); + } else { + first = make_node(AST_String, self, { value: "" }); + } + return elements.reduce(function(prev, el) { + return make_node(AST_Binary, el, { + operator : "+", + left : prev, + right : el + }); + }, first).optimize(compressor); + } + // need this awkward cloning to not affect original element + // best_of will decide which one to get through. + var node = self.clone(); + node.expression = node.expression.clone(); + node.expression.expression = node.expression.expression.clone(); + node.expression.expression.elements = elements; + return best_of(compressor, self, node); + } + break; + case "charAt": + if (exp.expression.is_string(compressor)) { + var arg = self.args[0]; + var index = arg ? arg.evaluate(compressor) : 0; + if (index !== arg) { + return make_node(AST_Sub, exp, { + expression: exp.expression, + property: make_node_from_constant(index | 0, arg || exp) + }).optimize(compressor); + } + } + break; + case "apply": + if (self.args.length == 2 && self.args[1] instanceof AST_Array) { + var args = self.args[1].elements.slice(); + args.unshift(self.args[0]); + return make_node(AST_Call, self, { + expression: make_node(AST_Dot, exp, { + expression: exp.expression, + optional: false, + property: "call" + }), + args: args + }).optimize(compressor); + } + break; + case "call": + var func = exp.expression; + if (func instanceof AST_SymbolRef) { + func = func.fixed_value(); + } + if (func instanceof AST_Lambda && !func.contains_this()) { + return (self.args.length ? make_sequence(this, [ + self.args[0], + make_node(AST_Call, self, { + expression: exp.expression, + args: self.args.slice(1) + }) + ]) : make_node(AST_Call, self, { + expression: exp.expression, + args: [] + })).optimize(compressor); + } + break; + } + } + + if (compressor.option("unsafe_Function") + && is_undeclared_ref(exp) + && exp.name == "Function") { + // new Function() => function(){} + if (self.args.length == 0) return make_node(AST_Function, self, { + argnames: [], + body: [] + }).optimize(compressor); + var nth_identifier = compressor.mangle_options && compressor.mangle_options.nth_identifier || base54; + if (self.args.every((x) => x instanceof AST_String)) { + // quite a corner-case, but we can handle it: + // https://github.com/mishoo/UglifyJS2/issues/203 + // if the code argument is a constant, then we can minify it. + try { + var code = "n(function(" + self.args.slice(0, -1).map(function(arg) { + return arg.value; + }).join(",") + "){" + self.args[self.args.length - 1].value + "})"; + var ast = parse(code); + var mangle = { ie8: compressor.option("ie8"), nth_identifier: nth_identifier }; + ast.figure_out_scope(mangle); + var comp = new Compressor(compressor.options, { + mangle_options: compressor.mangle_options + }); + ast = ast.transform(comp); + ast.figure_out_scope(mangle); + ast.compute_char_frequency(mangle); + ast.mangle_names(mangle); + var fun; + walk(ast, node => { + if (is_func_expr(node)) { + fun = node; + return walk_abort; + } + }); + var code = OutputStream(); + AST_BlockStatement.prototype._codegen.call(fun, fun, code); + self.args = [ + make_node(AST_String, self, { + value: fun.argnames.map(function(arg) { + return arg.print_to_string(); + }).join(",") + }), + make_node(AST_String, self.args[self.args.length - 1], { + value: code.get().replace(/^{|}$/g, "") + }) + ]; + return self; + } catch (ex) { + if (!(ex instanceof JS_Parse_Error)) { + throw ex; + } + + // Otherwise, it crashes at runtime. Or maybe it's nonstandard syntax. + } + } + } + + var stat = is_func && fn.body[0]; + var is_regular_func = is_func && !fn.is_generator && !fn.async; + var can_inline = is_regular_func && compressor.option("inline") && !self.is_callee_pure(compressor); + if (can_inline && stat instanceof AST_Return) { + let returned = stat.value; + if (!returned || returned.is_constant_expression()) { + if (returned) { + returned = returned.clone(true); + } else { + returned = make_node(AST_Undefined, self); + } + const args = self.args.concat(returned); + return make_sequence(self, args).optimize(compressor); + } + + // optimize identity function + if ( + fn.argnames.length === 1 + && (fn.argnames[0] instanceof AST_SymbolFunarg) + && self.args.length < 2 + && returned instanceof AST_SymbolRef + && returned.name === fn.argnames[0].name + ) { + const replacement = + (self.args[0] || make_node(AST_Undefined)).optimize(compressor); + + let parent; + if ( + replacement instanceof AST_PropAccess + && (parent = compressor.parent()) instanceof AST_Call + && parent.expression === self + ) { + // identity function was being used to remove `this`, like in + // + // id(bag.no_this)(...) + // + // Replace with a larger but more effish (0, bag.no_this) wrapper. + + return make_sequence(self, [ + make_node(AST_Number, self, { value: 0 }), + replacement + ]); + } + // replace call with first argument or undefined if none passed + return replacement; + } + } + + if (can_inline) { + var scope, in_loop, level = -1; + let def; + let returned_value; + let nearest_scope; + if (simple_args + && !fn.uses_arguments + && !(compressor.parent() instanceof AST_Class) + && !(fn.name && fn instanceof AST_Function) + && (returned_value = can_flatten_body(stat)) + && (exp === fn + || has_annotation(self, _INLINE) + || compressor.option("unused") + && (def = exp.definition()).references.length == 1 + && !is_recursive_ref(compressor, def) + && fn.is_constant_expression(exp.scope)) + && !has_annotation(self, _PURE | _NOINLINE) + && !fn.contains_this() + && can_inject_symbols() + && (nearest_scope = find_scope(compressor)) + && !scope_encloses_variables_in_this_scope(nearest_scope, fn) + && !(function in_default_assign() { + // Due to the fact function parameters have their own scope + // which can't use `var something` in the function body within, + // we simply don't inline into DefaultAssign. + let i = 0; + let p; + while ((p = compressor.parent(i++))) { + if (p instanceof AST_DefaultAssign) return true; + if (p instanceof AST_Block) break; + } + return false; + })() + && !(scope instanceof AST_Class) + ) { + set_flag(fn, SQUEEZED); + nearest_scope.add_child_scope(fn); + return make_sequence(self, flatten_fn(returned_value)).optimize(compressor); + } + } + + if (can_inline && has_annotation(self, _INLINE)) { + set_flag(fn, SQUEEZED); + fn = make_node(fn.CTOR === AST_Defun ? AST_Function : fn.CTOR, fn, fn); + fn = fn.clone(true); + fn.figure_out_scope({}, { + parent_scope: find_scope(compressor), + toplevel: compressor.get_toplevel() + }); + + return make_node(AST_Call, self, { + expression: fn, + args: self.args, + }).optimize(compressor); + } + + const can_drop_this_call = is_regular_func && compressor.option("side_effects") && fn.body.every(is_empty); + if (can_drop_this_call) { + var args = self.args.concat(make_node(AST_Undefined, self)); + return make_sequence(self, args).optimize(compressor); + } + + if (compressor.option("negate_iife") + && compressor.parent() instanceof AST_SimpleStatement + && is_iife_call(self)) { + return self.negate(compressor, true); + } + + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + + return self; + + function return_value(stat) { + if (!stat) return make_node(AST_Undefined, self); + if (stat instanceof AST_Return) { + if (!stat.value) return make_node(AST_Undefined, self); + return stat.value.clone(true); + } + if (stat instanceof AST_SimpleStatement) { + return make_node(AST_UnaryPrefix, stat, { + operator: "void", + expression: stat.body.clone(true) + }); + } + } + + function can_flatten_body(stat) { + var body = fn.body; + var len = body.length; + if (compressor.option("inline") < 3) { + return len == 1 && return_value(stat); + } + stat = null; + for (var i = 0; i < len; i++) { + var line = body[i]; + if (line instanceof AST_Var) { + if (stat && !line.definitions.every((var_def) => + !var_def.value + )) { + return false; + } + } else if (stat) { + return false; + } else if (!(line instanceof AST_EmptyStatement)) { + stat = line; + } + } + return return_value(stat); + } + + function can_inject_args(block_scoped, safe_to_inject) { + for (var i = 0, len = fn.argnames.length; i < len; i++) { + var arg = fn.argnames[i]; + if (arg instanceof AST_DefaultAssign) { + if (has_flag(arg.left, UNUSED)) continue; + return false; + } + if (arg instanceof AST_Destructuring) return false; + if (arg instanceof AST_Expansion) { + if (has_flag(arg.expression, UNUSED)) continue; + return false; + } + if (has_flag(arg, UNUSED)) continue; + if (!safe_to_inject + || block_scoped.has(arg.name) + || identifier_atom.has(arg.name) + || scope.conflicting_def(arg.name)) { + return false; + } + if (in_loop) in_loop.push(arg.definition()); + } + return true; + } + + function can_inject_vars(block_scoped, safe_to_inject) { + var len = fn.body.length; + for (var i = 0; i < len; i++) { + var stat = fn.body[i]; + if (!(stat instanceof AST_Var)) continue; + if (!safe_to_inject) return false; + for (var j = stat.definitions.length; --j >= 0;) { + var name = stat.definitions[j].name; + if (name instanceof AST_Destructuring + || block_scoped.has(name.name) + || identifier_atom.has(name.name) + || scope.conflicting_def(name.name)) { + return false; + } + if (in_loop) in_loop.push(name.definition()); + } + } + return true; + } + + function can_inject_symbols() { + var block_scoped = new Set(); + do { + scope = compressor.parent(++level); + if (scope.is_block_scope() && scope.block_scope) { + // TODO this is sometimes undefined during compression. + // But it should always have a value! + scope.block_scope.variables.forEach(function (variable) { + block_scoped.add(variable.name); + }); + } + if (scope instanceof AST_Catch) { + // TODO can we delete? AST_Catch is a block scope. + if (scope.argname) { + block_scoped.add(scope.argname.name); + } + } else if (scope instanceof AST_IterationStatement) { + in_loop = []; + } else if (scope instanceof AST_SymbolRef) { + if (scope.fixed_value() instanceof AST_Scope) return false; + } + } while (!(scope instanceof AST_Scope)); + + var safe_to_inject = !(scope instanceof AST_Toplevel) || compressor.toplevel.vars; + var inline = compressor.option("inline"); + if (!can_inject_vars(block_scoped, inline >= 3 && safe_to_inject)) return false; + if (!can_inject_args(block_scoped, inline >= 2 && safe_to_inject)) return false; + return !in_loop || in_loop.length == 0 || !is_reachable(fn, in_loop); + } + + function append_var(decls, expressions, name, value) { + var def = name.definition(); + + // Name already exists, only when a function argument had the same name + const already_appended = scope.variables.has(name.name); + if (!already_appended) { + scope.variables.set(name.name, def); + scope.enclosed.push(def); + decls.push(make_node(AST_VarDef, name, { + name: name, + value: null + })); + } + + var sym = make_node(AST_SymbolRef, name, name); + def.references.push(sym); + if (value) expressions.push(make_node(AST_Assign, self, { + operator: "=", + logical: false, + left: sym, + right: value.clone() + })); + } + + function flatten_args(decls, expressions) { + var len = fn.argnames.length; + for (var i = self.args.length; --i >= len;) { + expressions.push(self.args[i]); + } + for (i = len; --i >= 0;) { + var name = fn.argnames[i]; + var value = self.args[i]; + if (has_flag(name, UNUSED) || !name.name || scope.conflicting_def(name.name)) { + if (value) expressions.push(value); + } else { + var symbol = make_node(AST_SymbolVar, name, name); + name.definition().orig.push(symbol); + if (!value && in_loop) value = make_node(AST_Undefined, self); + append_var(decls, expressions, symbol, value); + } + } + decls.reverse(); + expressions.reverse(); + } + + function flatten_vars(decls, expressions) { + var pos = expressions.length; + for (var i = 0, lines = fn.body.length; i < lines; i++) { + var stat = fn.body[i]; + if (!(stat instanceof AST_Var)) continue; + for (var j = 0, defs = stat.definitions.length; j < defs; j++) { + var var_def = stat.definitions[j]; + var name = var_def.name; + append_var(decls, expressions, name, var_def.value); + if (in_loop && fn.argnames.every((argname) => + argname.name != name.name + )) { + var def = fn.variables.get(name.name); + var sym = make_node(AST_SymbolRef, name, name); + def.references.push(sym); + expressions.splice(pos++, 0, make_node(AST_Assign, var_def, { + operator: "=", + logical: false, + left: sym, + right: make_node(AST_Undefined, name) + })); + } + } + } + } + + function flatten_fn(returned_value) { + var decls = []; + var expressions = []; + flatten_args(decls, expressions); + flatten_vars(decls, expressions); + expressions.push(returned_value); + + if (decls.length) { + const i = scope.body.indexOf(compressor.parent(level - 1)) + 1; + scope.body.splice(i, 0, make_node(AST_Var, fn, { + definitions: decls + })); + } + + return expressions.map(exp => exp.clone(true)); + } +}); + +def_optimize(AST_New, function(self, compressor) { + if ( + compressor.option("unsafe") && + is_undeclared_ref(self.expression) && + ["Object", "RegExp", "Function", "Error", "Array"].includes(self.expression.name) + ) return make_node(AST_Call, self, self).transform(compressor); + return self; +}); + +def_optimize(AST_Sequence, function(self, compressor) { + if (!compressor.option("side_effects")) return self; + var expressions = []; + filter_for_side_effects(); + var end = expressions.length - 1; + trim_right_for_undefined(); + if (end == 0) { + self = maintain_this_binding(compressor.parent(), compressor.self(), expressions[0]); + if (!(self instanceof AST_Sequence)) self = self.optimize(compressor); + return self; + } + self.expressions = expressions; + return self; + + function filter_for_side_effects() { + var first = first_in_statement(compressor); + var last = self.expressions.length - 1; + self.expressions.forEach(function(expr, index) { + if (index < last) expr = expr.drop_side_effect_free(compressor, first); + if (expr) { + merge_sequence(expressions, expr); + first = false; + } + }); + } + + function trim_right_for_undefined() { + while (end > 0 && is_undefined(expressions[end], compressor)) end--; + if (end < expressions.length - 1) { + expressions[end] = make_node(AST_UnaryPrefix, self, { + operator : "void", + expression : expressions[end] + }); + expressions.length = end + 1; + } + } +}); + +AST_Unary.DEFMETHOD("lift_sequences", function(compressor) { + if (compressor.option("sequences")) { + if (this.expression instanceof AST_Sequence) { + var x = this.expression.expressions.slice(); + var e = this.clone(); + e.expression = x.pop(); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } + } + return this; +}); + +def_optimize(AST_UnaryPostfix, function(self, compressor) { + return self.lift_sequences(compressor); +}); + +def_optimize(AST_UnaryPrefix, function(self, compressor) { + var e = self.expression; + if ( + self.operator == "delete" && + !( + e instanceof AST_SymbolRef || + e instanceof AST_PropAccess || + e instanceof AST_Chain || + is_identifier_atom(e) + ) + ) { + return make_sequence(self, [e, make_node(AST_True, self)]).optimize(compressor); + } + var seq = self.lift_sequences(compressor); + if (seq !== self) { + return seq; + } + if (compressor.option("side_effects") && self.operator == "void") { + e = e.drop_side_effect_free(compressor); + if (e) { + self.expression = e; + return self; + } else { + return make_node(AST_Undefined, self).optimize(compressor); + } + } + if (compressor.in_boolean_context()) { + switch (self.operator) { + case "!": + if (e instanceof AST_UnaryPrefix && e.operator == "!") { + // !!foo ==> foo, if we're in boolean context + return e.expression; + } + if (e instanceof AST_Binary) { + self = best_of(compressor, self, e.negate(compressor, first_in_statement(compressor))); + } + break; + case "typeof": + // typeof always returns a non-empty string, thus it's + // always true in booleans + // And we don't need to check if it's undeclared, because in typeof, that's OK + return (e instanceof AST_SymbolRef ? make_node(AST_True, self) : make_sequence(self, [ + e, + make_node(AST_True, self) + ])).optimize(compressor); + } + } + if (self.operator == "-" && e instanceof AST_Infinity) { + e = e.transform(compressor); + } + if (e instanceof AST_Binary + && (self.operator == "+" || self.operator == "-") + && (e.operator == "*" || e.operator == "/" || e.operator == "%")) { + return make_node(AST_Binary, self, { + operator: e.operator, + left: make_node(AST_UnaryPrefix, e.left, { + operator: self.operator, + expression: e.left + }), + right: e.right + }); + } + // avoids infinite recursion of numerals + if (self.operator != "-" + || !(e instanceof AST_Number || e instanceof AST_Infinity || e instanceof AST_BigInt)) { + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + } + return self; +}); + +AST_Binary.DEFMETHOD("lift_sequences", function(compressor) { + if (compressor.option("sequences")) { + if (this.left instanceof AST_Sequence) { + var x = this.left.expressions.slice(); + var e = this.clone(); + e.left = x.pop(); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } + if (this.right instanceof AST_Sequence && !this.left.has_side_effects(compressor)) { + var assign = this.operator == "=" && this.left instanceof AST_SymbolRef; + var x = this.right.expressions; + var last = x.length - 1; + for (var i = 0; i < last; i++) { + if (!assign && x[i].has_side_effects(compressor)) break; + } + if (i == last) { + x = x.slice(); + var e = this.clone(); + e.right = x.pop(); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } else if (i > 0) { + var e = this.clone(); + e.right = make_sequence(this.right, x.slice(i)); + x = x.slice(0, i); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } + } + } + return this; +}); + +var commutativeOperators = makePredicate("== === != !== * & | ^"); +function is_object(node) { + return node instanceof AST_Array + || node instanceof AST_Lambda + || node instanceof AST_Object + || node instanceof AST_Class; +} + +def_optimize(AST_Binary, function(self, compressor) { + function reversible() { + return self.left.is_constant() + || self.right.is_constant() + || !self.left.has_side_effects(compressor) + && !self.right.has_side_effects(compressor); + } + function reverse(op) { + if (reversible()) { + if (op) self.operator = op; + var tmp = self.left; + self.left = self.right; + self.right = tmp; + } + } + if (commutativeOperators.has(self.operator)) { + if (self.right.is_constant() + && !self.left.is_constant()) { + // if right is a constant, whatever side effects the + // left side might have could not influence the + // result. hence, force switch. + + if (!(self.left instanceof AST_Binary + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + reverse(); + } + } + } + self = self.lift_sequences(compressor); + if (compressor.option("comparisons")) switch (self.operator) { + case "===": + case "!==": + var is_strict_comparison = true; + if ((self.left.is_string(compressor) && self.right.is_string(compressor)) || + (self.left.is_number(compressor) && self.right.is_number(compressor)) || + (self.left.is_boolean() && self.right.is_boolean()) || + self.left.equivalent_to(self.right)) { + self.operator = self.operator.substr(0, 2); + } + // XXX: intentionally falling down to the next case + case "==": + case "!=": + // void 0 == x => null == x + if (!is_strict_comparison && is_undefined(self.left, compressor)) { + self.left = make_node(AST_Null, self.left); + } else if (compressor.option("typeofs") + // "undefined" == typeof x => undefined === x + && self.left instanceof AST_String + && self.left.value == "undefined" + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "typeof") { + var expr = self.right.expression; + if (expr instanceof AST_SymbolRef ? expr.is_declared(compressor) + : !(expr instanceof AST_PropAccess && compressor.option("ie8"))) { + self.right = expr; + self.left = make_node(AST_Undefined, self.left).optimize(compressor); + if (self.operator.length == 2) self.operator += "="; + } + } else if (self.left instanceof AST_SymbolRef + // obj !== obj => false + && self.right instanceof AST_SymbolRef + && self.left.definition() === self.right.definition() + && is_object(self.left.fixed_value())) { + return make_node(self.operator[0] == "=" ? AST_True : AST_False, self); + } + break; + case "&&": + case "||": + var lhs = self.left; + if (lhs.operator == self.operator) { + lhs = lhs.right; + } + if (lhs instanceof AST_Binary + && lhs.operator == (self.operator == "&&" ? "!==" : "===") + && self.right instanceof AST_Binary + && lhs.operator == self.right.operator + && (is_undefined(lhs.left, compressor) && self.right.left instanceof AST_Null + || lhs.left instanceof AST_Null && is_undefined(self.right.left, compressor)) + && !lhs.right.has_side_effects(compressor) + && lhs.right.equivalent_to(self.right.right)) { + var combined = make_node(AST_Binary, self, { + operator: lhs.operator.slice(0, -1), + left: make_node(AST_Null, self), + right: lhs.right + }); + if (lhs !== self.left) { + combined = make_node(AST_Binary, self, { + operator: self.operator, + left: self.left.left, + right: combined + }); + } + return combined; + } + break; + } + if (self.operator == "+" && compressor.in_boolean_context()) { + var ll = self.left.evaluate(compressor); + var rr = self.right.evaluate(compressor); + if (ll && typeof ll == "string") { + return make_sequence(self, [ + self.right, + make_node(AST_True, self) + ]).optimize(compressor); + } + if (rr && typeof rr == "string") { + return make_sequence(self, [ + self.left, + make_node(AST_True, self) + ]).optimize(compressor); + } + } + if (compressor.option("comparisons") && self.is_boolean()) { + if (!(compressor.parent() instanceof AST_Binary) + || compressor.parent() instanceof AST_Assign) { + var negated = make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: self.negate(compressor, first_in_statement(compressor)) + }); + self = best_of(compressor, self, negated); + } + if (compressor.option("unsafe_comps")) { + switch (self.operator) { + case "<": reverse(">"); break; + case "<=": reverse(">="); break; + } + } + } + if (self.operator == "+") { + if (self.right instanceof AST_String + && self.right.getValue() == "" + && self.left.is_string(compressor)) { + return self.left; + } + if (self.left instanceof AST_String + && self.left.getValue() == "" + && self.right.is_string(compressor)) { + return self.right; + } + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.left instanceof AST_String + && self.left.left.getValue() == "" + && self.right.is_string(compressor)) { + self.left = self.left.right; + return self; + } + } + if (compressor.option("evaluate")) { + switch (self.operator) { + case "&&": + var ll = has_flag(self.left, TRUTHY) + ? true + : has_flag(self.left, FALSY) + ? false + : self.left.evaluate(compressor); + if (!ll) { + return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor); + } else if (!(ll instanceof AST_Node)) { + return make_sequence(self, [ self.left, self.right ]).optimize(compressor); + } + var rr = self.right.evaluate(compressor); + if (!rr) { + if (compressor.in_boolean_context()) { + return make_sequence(self, [ + self.left, + make_node(AST_False, self) + ]).optimize(compressor); + } else { + set_flag(self, FALSY); + } + } else if (!(rr instanceof AST_Node)) { + var parent = compressor.parent(); + if (parent.operator == "&&" && parent.left === compressor.self() || compressor.in_boolean_context()) { + return self.left.optimize(compressor); + } + } + // x || false && y ---> x ? y : false + if (self.left.operator == "||") { + var lr = self.left.right.evaluate(compressor); + if (!lr) return make_node(AST_Conditional, self, { + condition: self.left.left, + consequent: self.right, + alternative: self.left.right + }).optimize(compressor); + } + break; + case "||": + var ll = has_flag(self.left, TRUTHY) + ? true + : has_flag(self.left, FALSY) + ? false + : self.left.evaluate(compressor); + if (!ll) { + return make_sequence(self, [ self.left, self.right ]).optimize(compressor); + } else if (!(ll instanceof AST_Node)) { + return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor); + } + var rr = self.right.evaluate(compressor); + if (!rr) { + var parent = compressor.parent(); + if (parent.operator == "||" && parent.left === compressor.self() || compressor.in_boolean_context()) { + return self.left.optimize(compressor); + } + } else if (!(rr instanceof AST_Node)) { + if (compressor.in_boolean_context()) { + return make_sequence(self, [ + self.left, + make_node(AST_True, self) + ]).optimize(compressor); + } else { + set_flag(self, TRUTHY); + } + } + if (self.left.operator == "&&") { + var lr = self.left.right.evaluate(compressor); + if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self, { + condition: self.left.left, + consequent: self.left.right, + alternative: self.right + }).optimize(compressor); + } + break; + case "??": + if (is_nullish(self.left, compressor)) { + return self.right; + } + + var ll = self.left.evaluate(compressor); + if (!(ll instanceof AST_Node)) { + // if we know the value for sure we can simply compute right away. + return ll == null ? self.right : self.left; + } + + if (compressor.in_boolean_context()) { + const rr = self.right.evaluate(compressor); + if (!(rr instanceof AST_Node) && !rr) { + return self.left; + } + } + } + var associative = true; + switch (self.operator) { + case "+": + // (x + "foo") + "bar" => x + "foobar" + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.is_string(compressor)) { + var binary = make_node(AST_Binary, self, { + operator: "+", + left: self.left.right, + right: self.right, + }); + var r = binary.optimize(compressor); + if (binary !== r) { + self = make_node(AST_Binary, self, { + operator: "+", + left: self.left.left, + right: r + }); + } + } + // (x + "foo") + ("bar" + y) => (x + "foobar") + y + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.is_string(compressor) + && self.right instanceof AST_Binary + && self.right.operator == "+" + && self.right.is_string(compressor)) { + var binary = make_node(AST_Binary, self, { + operator: "+", + left: self.left.right, + right: self.right.left, + }); + var m = binary.optimize(compressor); + if (binary !== m) { + self = make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_Binary, self.left, { + operator: "+", + left: self.left.left, + right: m + }), + right: self.right.right + }); + } + } + // a + -b => a - b + if (self.right instanceof AST_UnaryPrefix + && self.right.operator == "-" + && self.left.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.left, + right: self.right.expression + }); + break; + } + // -a + b => b - a + if (self.left instanceof AST_UnaryPrefix + && self.left.operator == "-" + && reversible() + && self.right.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.right, + right: self.left.expression + }); + break; + } + // `foo${bar}baz` + 1 => `foo${bar}baz1` + if (self.left instanceof AST_TemplateString) { + var l = self.left; + var r = self.right.evaluate(compressor); + if (r != self.right) { + l.segments[l.segments.length - 1].value += String(r); + return l; + } + } + // 1 + `foo${bar}baz` => `1foo${bar}baz` + if (self.right instanceof AST_TemplateString) { + var r = self.right; + var l = self.left.evaluate(compressor); + if (l != self.left) { + r.segments[0].value = String(l) + r.segments[0].value; + return r; + } + } + // `1${bar}2` + `foo${bar}baz` => `1${bar}2foo${bar}baz` + if (self.left instanceof AST_TemplateString + && self.right instanceof AST_TemplateString) { + var l = self.left; + var segments = l.segments; + var r = self.right; + segments[segments.length - 1].value += r.segments[0].value; + for (var i = 1; i < r.segments.length; i++) { + segments.push(r.segments[i]); + } + return l; + } + case "*": + associative = compressor.option("unsafe_math"); + case "&": + case "|": + case "^": + // a + +b => +b + a + if (self.left.is_number(compressor) + && self.right.is_number(compressor) + && reversible() + && !(self.left instanceof AST_Binary + && self.left.operator != self.operator + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + var reversed = make_node(AST_Binary, self, { + operator: self.operator, + left: self.right, + right: self.left + }); + if (self.right instanceof AST_Constant + && !(self.left instanceof AST_Constant)) { + self = best_of(compressor, reversed, self); + } else { + self = best_of(compressor, self, reversed); + } + } + if (associative && self.is_number(compressor)) { + // a + (b + c) => (a + b) + c + if (self.right instanceof AST_Binary + && self.right.operator == self.operator) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left, + right: self.right.left, + start: self.left.start, + end: self.right.left.end + }), + right: self.right.right + }); + } + // (n + 2) + 3 => 5 + n + // (2 * n) * 3 => 6 + n + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == self.operator) { + if (self.left.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.left, + right: self.right, + start: self.left.left.start, + end: self.right.end + }), + right: self.left.right + }); + } else if (self.left.right instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.right, + right: self.right, + start: self.left.right.start, + end: self.right.end + }), + right: self.left.left + }); + } + } + // (a | 1) | (2 | d) => (3 | a) | b + if (self.left instanceof AST_Binary + && self.left.operator == self.operator + && self.left.right instanceof AST_Constant + && self.right instanceof AST_Binary + && self.right.operator == self.operator + && self.right.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: make_node(AST_Binary, self.left.left, { + operator: self.operator, + left: self.left.right, + right: self.right.left, + start: self.left.right.start, + end: self.right.left.end + }), + right: self.left.left + }), + right: self.right.right + }); + } + } + } + } + // x && (y && z) ==> x && y && z + // x || (y || z) ==> x || y || z + // x + ("y" + z) ==> x + "y" + z + // "x" + (y + "z")==> "x" + y + "z" + if (self.right instanceof AST_Binary + && self.right.operator == self.operator + && (lazy_op.has(self.operator) + || (self.operator == "+" + && (self.right.left.is_string(compressor) + || (self.left.is_string(compressor) + && self.right.right.is_string(compressor))))) + ) { + self.left = make_node(AST_Binary, self.left, { + operator : self.operator, + left : self.left.transform(compressor), + right : self.right.left.transform(compressor) + }); + self.right = self.right.right.transform(compressor); + return self.transform(compressor); + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +def_optimize(AST_SymbolExport, function(self) { + return self; +}); + +function within_array_or_object_literal(compressor) { + var node, level = 0; + while (node = compressor.parent(level++)) { + if (node instanceof AST_Statement) return false; + if (node instanceof AST_Array + || node instanceof AST_ObjectKeyVal + || node instanceof AST_Object) { + return true; + } + } + return false; +} + +def_optimize(AST_SymbolRef, function(self, compressor) { + if ( + !compressor.option("ie8") + && is_undeclared_ref(self) + && !compressor.find_parent(AST_With) + ) { + switch (self.name) { + case "undefined": + return make_node(AST_Undefined, self).optimize(compressor); + case "NaN": + return make_node(AST_NaN, self).optimize(compressor); + case "Infinity": + return make_node(AST_Infinity, self).optimize(compressor); + } + } + + const parent = compressor.parent(); + if (compressor.option("reduce_vars") && is_lhs(self, parent) !== self) { + const def = self.definition(); + const nearest_scope = find_scope(compressor); + if (compressor.top_retain && def.global && compressor.top_retain(def)) { + def.fixed = false; + def.single_use = false; + return self; + } + + let fixed = self.fixed_value(); + let single_use = def.single_use + && !(parent instanceof AST_Call + && (parent.is_callee_pure(compressor)) + || has_annotation(parent, _NOINLINE)) + && !(parent instanceof AST_Export + && fixed instanceof AST_Lambda + && fixed.name); + + if (single_use && fixed instanceof AST_Node) { + single_use = + !fixed.has_side_effects(compressor) + && !fixed.may_throw(compressor); + } + + if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) { + if (retain_top_func(fixed, compressor)) { + single_use = false; + } else if (def.scope !== self.scope + && (def.escaped == 1 + || has_flag(fixed, INLINED) + || within_array_or_object_literal(compressor) + || !compressor.option("reduce_funcs"))) { + single_use = false; + } else if (is_recursive_ref(compressor, def)) { + single_use = false; + } else if (def.scope !== self.scope || def.orig[0] instanceof AST_SymbolFunarg) { + single_use = fixed.is_constant_expression(self.scope); + if (single_use == "f") { + var scope = self.scope; + do { + if (scope instanceof AST_Defun || is_func_expr(scope)) { + set_flag(scope, INLINED); + } + } while (scope = scope.parent_scope); + } + } + } + + if (single_use && fixed instanceof AST_Lambda) { + single_use = + def.scope === self.scope + && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) + || parent instanceof AST_Call + && parent.expression === self + && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) + && !(fixed.name && fixed.name.definition().recursive_refs > 0); + } + + if (single_use && fixed) { + if (fixed instanceof AST_DefClass) { + set_flag(fixed, SQUEEZED); + fixed = make_node(AST_ClassExpression, fixed, fixed); + } + if (fixed instanceof AST_Defun) { + set_flag(fixed, SQUEEZED); + fixed = make_node(AST_Function, fixed, fixed); + } + if (def.recursive_refs > 0 && fixed.name instanceof AST_SymbolDefun) { + const defun_def = fixed.name.definition(); + let lambda_def = fixed.variables.get(fixed.name.name); + let name = lambda_def && lambda_def.orig[0]; + if (!(name instanceof AST_SymbolLambda)) { + name = make_node(AST_SymbolLambda, fixed.name, fixed.name); + name.scope = fixed; + fixed.name = name; + lambda_def = fixed.def_function(name); + } + walk(fixed, node => { + if (node instanceof AST_SymbolRef && node.definition() === defun_def) { + node.thedef = lambda_def; + lambda_def.references.push(node); + } + }); + } + if ( + (fixed instanceof AST_Lambda || fixed instanceof AST_Class) + && fixed.parent_scope !== nearest_scope + ) { + fixed = fixed.clone(true, compressor.get_toplevel()); + + nearest_scope.add_child_scope(fixed); + } + return fixed.optimize(compressor); + } + + // multiple uses + if (fixed) { + let replace; + + if (fixed instanceof AST_This) { + if (!(def.orig[0] instanceof AST_SymbolFunarg) + && def.references.every((ref) => + def.scope === ref.scope + )) { + replace = fixed; + } + } else { + var ev = fixed.evaluate(compressor); + if ( + ev !== fixed + && (compressor.option("unsafe_regexp") || !(ev instanceof RegExp)) + ) { + replace = make_node_from_constant(ev, fixed); + } + } + + if (replace) { + const name_length = self.size(compressor); + const replace_size = replace.size(compressor); + + let overhead = 0; + if (compressor.option("unused") && !compressor.exposed(def)) { + overhead = + (name_length + 2 + replace_size) / + (def.references.length - def.assignments); + } + + if (replace_size <= name_length + overhead) { + return replace; + } + } + } + } + + return self; +}); + +function scope_encloses_variables_in_this_scope(scope, pulled_scope) { + for (const enclosed of pulled_scope.enclosed) { + if (pulled_scope.variables.has(enclosed.name)) { + continue; + } + const looked_up = scope.find_variable(enclosed.name); + if (looked_up) { + if (looked_up === enclosed) continue; + return true; + } + } + return false; +} + +function is_atomic(lhs, self) { + return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE; +} + +def_optimize(AST_Undefined, function(self, compressor) { + if (compressor.option("unsafe_undefined")) { + var undef = find_variable(compressor, "undefined"); + if (undef) { + var ref = make_node(AST_SymbolRef, self, { + name : "undefined", + scope : undef.scope, + thedef : undef + }); + set_flag(ref, UNDEFINED); + return ref; + } + } + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && is_atomic(lhs, self)) return self; + return make_node(AST_UnaryPrefix, self, { + operator: "void", + expression: make_node(AST_Number, self, { + value: 0 + }) + }); +}); + +def_optimize(AST_Infinity, function(self, compressor) { + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && is_atomic(lhs, self)) return self; + if ( + compressor.option("keep_infinity") + && !(lhs && !is_atomic(lhs, self)) + && !find_variable(compressor, "Infinity") + ) { + return self; + } + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 1 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); +}); + +def_optimize(AST_NaN, function(self, compressor) { + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && !is_atomic(lhs, self) + || find_variable(compressor, "NaN")) { + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 0 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); + } + return self; +}); + +function is_reachable(self, defs) { + const find_ref = node => { + if (node instanceof AST_SymbolRef && member(node.definition(), defs)) { + return walk_abort; + } + }; + + return walk_parent(self, (node, info) => { + if (node instanceof AST_Scope && node !== self) { + var parent = info.parent(); + + if ( + parent instanceof AST_Call + && parent.expression === node + // Async/Generators aren't guaranteed to sync evaluate all of + // their body steps, so it's possible they close over the variable. + && !(node.async || node.is_generator) + ) { + return; + } + + if (walk(node, find_ref)) return walk_abort; + + return true; + } + }); +} + +const ASSIGN_OPS = makePredicate("+ - / * % >> << >>> | ^ &"); +const ASSIGN_OPS_COMMUTATIVE = makePredicate("* | ^ &"); +def_optimize(AST_Assign, function(self, compressor) { + if (self.logical) { + return self.lift_sequences(compressor); + } + + var def; + if (compressor.option("dead_code") + && self.left instanceof AST_SymbolRef + && (def = self.left.definition()).scope === compressor.find_parent(AST_Lambda)) { + var level = 0, node, parent = self; + do { + node = parent; + parent = compressor.parent(level++); + if (parent instanceof AST_Exit) { + if (in_try(level, parent)) break; + if (is_reachable(def.scope, [ def ])) break; + if (self.operator == "=") return self.right; + def.fixed = false; + return make_node(AST_Binary, self, { + operator: self.operator.slice(0, -1), + left: self.left, + right: self.right + }).optimize(compressor); + } + } while (parent instanceof AST_Binary && parent.right === node + || parent instanceof AST_Sequence && parent.tail_node() === node); + } + self = self.lift_sequences(compressor); + if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) { + // x = expr1 OP expr2 + if (self.right.left instanceof AST_SymbolRef + && self.right.left.name == self.left.name + && ASSIGN_OPS.has(self.right.operator)) { + // x = x - 2 ---> x -= 2 + self.operator = self.right.operator + "="; + self.right = self.right.right; + } else if (self.right.right instanceof AST_SymbolRef + && self.right.right.name == self.left.name + && ASSIGN_OPS_COMMUTATIVE.has(self.right.operator) + && !self.right.left.has_side_effects(compressor)) { + // x = 2 & x ---> x &= 2 + self.operator = self.right.operator + "="; + self.right = self.right.left; + } + } + return self; + + function in_try(level, node) { + var right = self.right; + self.right = make_node(AST_Null, right); + var may_throw = node.may_throw(compressor); + self.right = right; + var scope = self.left.definition().scope; + var parent; + while ((parent = compressor.parent(level++)) !== scope) { + if (parent instanceof AST_Try) { + if (parent.bfinally) return true; + if (may_throw && parent.bcatch) return true; + } + } + } +}); + +def_optimize(AST_DefaultAssign, function(self, compressor) { + if (!compressor.option("evaluate")) { + return self; + } + var evaluateRight = self.right.evaluate(compressor); + + // `[x = undefined] = foo` ---> `[x] = foo` + if (evaluateRight === undefined) { + self = self.left; + } else if (evaluateRight !== self.right) { + evaluateRight = make_node_from_constant(evaluateRight, self.right); + self.right = best_of_expression(evaluateRight, self.right); + } + + return self; +}); + +function is_nullish_check(check, check_subject, compressor) { + if (check_subject.may_throw(compressor)) return false; + + let nullish_side; + + // foo == null + if ( + check instanceof AST_Binary + && check.operator === "==" + // which side is nullish? + && ( + (nullish_side = is_nullish(check.left, compressor) && check.left) + || (nullish_side = is_nullish(check.right, compressor) && check.right) + ) + // is the other side the same as the check_subject + && ( + nullish_side === check.left + ? check.right + : check.left + ).equivalent_to(check_subject) + ) { + return true; + } + + // foo === null || foo === undefined + if (check instanceof AST_Binary && check.operator === "||") { + let null_cmp; + let undefined_cmp; + + const find_comparison = cmp => { + if (!( + cmp instanceof AST_Binary + && (cmp.operator === "===" || cmp.operator === "==") + )) { + return false; + } + + let found = 0; + let defined_side; + + if (cmp.left instanceof AST_Null) { + found++; + null_cmp = cmp; + defined_side = cmp.right; + } + if (cmp.right instanceof AST_Null) { + found++; + null_cmp = cmp; + defined_side = cmp.left; + } + if (is_undefined(cmp.left, compressor)) { + found++; + undefined_cmp = cmp; + defined_side = cmp.right; + } + if (is_undefined(cmp.right, compressor)) { + found++; + undefined_cmp = cmp; + defined_side = cmp.left; + } + + if (found !== 1) { + return false; + } + + if (!defined_side.equivalent_to(check_subject)) { + return false; + } + + return true; + }; + + if (!find_comparison(check.left)) return false; + if (!find_comparison(check.right)) return false; + + if (null_cmp && undefined_cmp && null_cmp !== undefined_cmp) { + return true; + } + } + + return false; +} + +def_optimize(AST_Conditional, function(self, compressor) { + if (!compressor.option("conditionals")) return self; + // This looks like lift_sequences(), should probably be under "sequences" + if (self.condition instanceof AST_Sequence) { + var expressions = self.condition.expressions.slice(); + self.condition = expressions.pop(); + expressions.push(self); + return make_sequence(self, expressions); + } + var cond = self.condition.evaluate(compressor); + if (cond !== self.condition) { + if (cond) { + return maintain_this_binding(compressor.parent(), compressor.self(), self.consequent); + } else { + return maintain_this_binding(compressor.parent(), compressor.self(), self.alternative); + } + } + var negated = cond.negate(compressor, first_in_statement(compressor)); + if (best_of(compressor, cond, negated) === negated) { + self = make_node(AST_Conditional, self, { + condition: negated, + consequent: self.alternative, + alternative: self.consequent + }); + } + var condition = self.condition; + var consequent = self.consequent; + var alternative = self.alternative; + // x?x:y --> x||y + if (condition instanceof AST_SymbolRef + && consequent instanceof AST_SymbolRef + && condition.definition() === consequent.definition()) { + return make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative + }); + } + // if (foo) exp = something; else exp = something_else; + // | + // v + // exp = foo ? something : something_else; + if ( + consequent instanceof AST_Assign + && alternative instanceof AST_Assign + && consequent.operator === alternative.operator + && consequent.logical === alternative.logical + && consequent.left.equivalent_to(alternative.left) + && (!self.condition.has_side_effects(compressor) + || consequent.operator == "=" + && !consequent.left.has_side_effects(compressor)) + ) { + return make_node(AST_Assign, self, { + operator: consequent.operator, + left: consequent.left, + logical: consequent.logical, + right: make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.right, + alternative: alternative.right + }) + }); + } + // x ? y(a) : y(b) --> y(x ? a : b) + var arg_index; + if (consequent instanceof AST_Call + && alternative.TYPE === consequent.TYPE + && consequent.args.length > 0 + && consequent.args.length == alternative.args.length + && consequent.expression.equivalent_to(alternative.expression) + && !self.condition.has_side_effects(compressor) + && !consequent.expression.has_side_effects(compressor) + && typeof (arg_index = single_arg_diff()) == "number") { + var node = consequent.clone(); + node.args[arg_index] = make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.args[arg_index], + alternative: alternative.args[arg_index] + }); + return node; + } + // a ? b : c ? b : d --> (a || c) ? b : d + if (alternative instanceof AST_Conditional + && consequent.equivalent_to(alternative.consequent)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative.condition + }), + consequent: consequent, + alternative: alternative.alternative + }).optimize(compressor); + } + + // a == null ? b : a -> a ?? b + if ( + compressor.option("ecma") >= 2020 && + is_nullish_check(condition, alternative, compressor) + ) { + return make_node(AST_Binary, self, { + operator: "??", + left: alternative, + right: consequent + }).optimize(compressor); + } + + // a ? b : (c, b) --> (a || c), b + if (alternative instanceof AST_Sequence + && consequent.equivalent_to(alternative.expressions[alternative.expressions.length - 1])) { + return make_sequence(self, [ + make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: make_sequence(self, alternative.expressions.slice(0, -1)) + }), + consequent + ]).optimize(compressor); + } + // a ? b : (c && b) --> (a || c) && b + if (alternative instanceof AST_Binary + && alternative.operator == "&&" + && consequent.equivalent_to(alternative.right)) { + return make_node(AST_Binary, self, { + operator: "&&", + left: make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative.left + }), + right: consequent + }).optimize(compressor); + } + // x?y?z:a:a --> x&&y?z:a + if (consequent instanceof AST_Conditional + && consequent.alternative.equivalent_to(alternative)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + left: self.condition, + operator: "&&", + right: consequent.condition + }), + consequent: consequent.consequent, + alternative: alternative + }); + } + // x ? y : y --> x, y + if (consequent.equivalent_to(alternative)) { + return make_sequence(self, [ + self.condition, + consequent + ]).optimize(compressor); + } + // x ? y || z : z --> x && y || z + if (consequent instanceof AST_Binary + && consequent.operator == "||" + && consequent.right.equivalent_to(alternative)) { + return make_node(AST_Binary, self, { + operator: "||", + left: make_node(AST_Binary, self, { + operator: "&&", + left: self.condition, + right: consequent.left + }), + right: alternative + }).optimize(compressor); + } + + const in_bool = compressor.in_boolean_context(); + if (is_true(self.consequent)) { + if (is_false(self.alternative)) { + // c ? true : false ---> !!c + return booleanize(self.condition); + } + // c ? true : x ---> !!c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition), + right: self.alternative + }); + } + if (is_false(self.consequent)) { + if (is_true(self.alternative)) { + // c ? false : true ---> !c + return booleanize(self.condition.negate(compressor)); + } + // c ? false : x ---> !c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition.negate(compressor)), + right: self.alternative + }); + } + if (is_true(self.alternative)) { + // c ? x : true ---> !c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition.negate(compressor)), + right: self.consequent + }); + } + if (is_false(self.alternative)) { + // c ? x : false ---> !!c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition), + right: self.consequent + }); + } + + return self; + + function booleanize(node) { + if (node.is_boolean()) return node; + // !!expression + return make_node(AST_UnaryPrefix, node, { + operator: "!", + expression: node.negate(compressor) + }); + } + + // AST_True or !0 + function is_true(node) { + return node instanceof AST_True + || in_bool + && node instanceof AST_Constant + && node.getValue() + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && !node.expression.getValue()); + } + // AST_False or !1 + function is_false(node) { + return node instanceof AST_False + || in_bool + && node instanceof AST_Constant + && !node.getValue() + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && node.expression.getValue()); + } + + function single_arg_diff() { + var a = consequent.args; + var b = alternative.args; + for (var i = 0, len = a.length; i < len; i++) { + if (a[i] instanceof AST_Expansion) return; + if (!a[i].equivalent_to(b[i])) { + if (b[i] instanceof AST_Expansion) return; + for (var j = i + 1; j < len; j++) { + if (a[j] instanceof AST_Expansion) return; + if (!a[j].equivalent_to(b[j])) return; + } + return i; + } + } + } +}); + +def_optimize(AST_Boolean, function(self, compressor) { + if (compressor.in_boolean_context()) return make_node(AST_Number, self, { + value: +self.value + }); + var p = compressor.parent(); + if (compressor.option("booleans_as_integers")) { + if (p instanceof AST_Binary && (p.operator == "===" || p.operator == "!==")) { + p.operator = p.operator.replace(/=$/, ""); + } + return make_node(AST_Number, self, { + value: +self.value + }); + } + if (compressor.option("booleans")) { + if (p instanceof AST_Binary && (p.operator == "==" + || p.operator == "!=")) { + return make_node(AST_Number, self, { + value: +self.value + }); + } + return make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: make_node(AST_Number, self, { + value: 1 - self.value + }) + }); + } + return self; +}); + +function safe_to_flatten(value, compressor) { + if (value instanceof AST_SymbolRef) { + value = value.fixed_value(); + } + if (!value) return false; + if (!(value instanceof AST_Lambda || value instanceof AST_Class)) return true; + if (!(value instanceof AST_Lambda && value.contains_this())) return true; + return compressor.parent() instanceof AST_New; +} + +AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) { + if (!compressor.option("properties")) return; + if (key === "__proto__") return; + + var arrows = compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015; + var expr = this.expression; + if (expr instanceof AST_Object) { + var props = expr.properties; + + for (var i = props.length; --i >= 0;) { + var prop = props[i]; + + if ("" + (prop instanceof AST_ConciseMethod ? prop.key.name : prop.key) == key) { + const all_props_flattenable = props.every((p) => + (p instanceof AST_ObjectKeyVal + || arrows && p instanceof AST_ConciseMethod && !p.is_generator + ) + && !p.computed_key() + ); + + if (!all_props_flattenable) return; + if (!safe_to_flatten(prop.value, compressor)) return; + + return make_node(AST_Sub, this, { + expression: make_node(AST_Array, expr, { + elements: props.map(function(prop) { + var v = prop.value; + if (v instanceof AST_Accessor) { + v = make_node(AST_Function, v, v); + } + + var k = prop.key; + if (k instanceof AST_Node && !(k instanceof AST_SymbolMethod)) { + return make_sequence(prop, [ k, v ]); + } + + return v; + }) + }), + property: make_node(AST_Number, this, { + value: i + }) + }); + } + } + } +}); + +def_optimize(AST_Sub, function(self, compressor) { + var expr = self.expression; + var prop = self.property; + if (compressor.option("properties")) { + var key = prop.evaluate(compressor); + if (key !== prop) { + if (typeof key == "string") { + if (key == "undefined") { + key = undefined; + } else { + var value = parseFloat(key); + if (value.toString() == key) { + key = value; + } + } + } + prop = self.property = best_of_expression(prop, make_node_from_constant(key, prop).transform(compressor)); + var property = "" + key; + if (is_basic_identifier_string(property) + && property.length <= prop.size() + 1) { + return make_node(AST_Dot, self, { + expression: expr, + optional: self.optional, + property: property, + quote: prop.quote, + }).optimize(compressor); + } + } + } + var fn; + OPT_ARGUMENTS: if (compressor.option("arguments") + && expr instanceof AST_SymbolRef + && expr.name == "arguments" + && expr.definition().orig.length == 1 + && (fn = expr.scope) instanceof AST_Lambda + && fn.uses_arguments + && !(fn instanceof AST_Arrow) + && prop instanceof AST_Number) { + var index = prop.getValue(); + var params = new Set(); + var argnames = fn.argnames; + for (var n = 0; n < argnames.length; n++) { + if (!(argnames[n] instanceof AST_SymbolFunarg)) { + break OPT_ARGUMENTS; // destructuring parameter - bail + } + var param = argnames[n].name; + if (params.has(param)) { + break OPT_ARGUMENTS; // duplicate parameter - bail + } + params.add(param); + } + var argname = fn.argnames[index]; + if (argname && compressor.has_directive("use strict")) { + var def = argname.definition(); + if (!compressor.option("reduce_vars") || def.assignments || def.orig.length > 1) { + argname = null; + } + } else if (!argname && !compressor.option("keep_fargs") && index < fn.argnames.length + 5) { + while (index >= fn.argnames.length) { + argname = fn.create_symbol(AST_SymbolFunarg, { + source: fn, + scope: fn, + tentative_name: "argument_" + fn.argnames.length, + }); + fn.argnames.push(argname); + } + } + if (argname) { + var sym = make_node(AST_SymbolRef, self, argname); + sym.reference({}); + clear_flag(argname, UNUSED); + return sym; + } + } + if (is_lhs(self, compressor.parent())) return self; + if (key !== prop) { + var sub = self.flatten_object(property, compressor); + if (sub) { + expr = self.expression = sub.expression; + prop = self.property = sub.property; + } + } + if (compressor.option("properties") && compressor.option("side_effects") + && prop instanceof AST_Number && expr instanceof AST_Array) { + var index = prop.getValue(); + var elements = expr.elements; + var retValue = elements[index]; + FLATTEN: if (safe_to_flatten(retValue, compressor)) { + var flatten = true; + var values = []; + for (var i = elements.length; --i > index;) { + var value = elements[i].drop_side_effect_free(compressor); + if (value) { + values.unshift(value); + if (flatten && value.has_side_effects(compressor)) flatten = false; + } + } + if (retValue instanceof AST_Expansion) break FLATTEN; + retValue = retValue instanceof AST_Hole ? make_node(AST_Undefined, retValue) : retValue; + if (!flatten) values.unshift(retValue); + while (--i >= 0) { + var value = elements[i]; + if (value instanceof AST_Expansion) break FLATTEN; + value = value.drop_side_effect_free(compressor); + if (value) values.unshift(value); + else index--; + } + if (flatten) { + values.push(retValue); + return make_sequence(self, values).optimize(compressor); + } else return make_node(AST_Sub, self, { + expression: make_node(AST_Array, expr, { + elements: values + }), + property: make_node(AST_Number, prop, { + value: index + }) + }); + } + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +def_optimize(AST_Chain, function (self, compressor) { + if (is_nullish(self.expression, compressor)) { + let parent = compressor.parent(); + // It's valid to delete a nullish optional chain, but if we optimized + // this to `delete undefined` then it would appear to be a syntax error + // when we try to optimize the delete. Thankfully, `delete 0` is fine. + if (parent instanceof AST_UnaryPrefix && parent.operator === "delete") { + return make_node_from_constant(0, self); + } + return make_node(AST_Undefined, self); + } + return self; +}); + +AST_Lambda.DEFMETHOD("contains_this", function() { + return walk(this, node => { + if (node instanceof AST_This) return walk_abort; + if ( + node !== this + && node instanceof AST_Scope + && !(node instanceof AST_Arrow) + ) { + return true; + } + }); +}); + +def_optimize(AST_Dot, function(self, compressor) { + const parent = compressor.parent(); + if (is_lhs(self, parent)) return self; + if (compressor.option("unsafe_proto") + && self.expression instanceof AST_Dot + && self.expression.property == "prototype") { + var exp = self.expression.expression; + if (is_undeclared_ref(exp)) switch (exp.name) { + case "Array": + self.expression = make_node(AST_Array, self.expression, { + elements: [] + }); + break; + case "Function": + self.expression = make_node(AST_Function, self.expression, { + argnames: [], + body: [] + }); + break; + case "Number": + self.expression = make_node(AST_Number, self.expression, { + value: 0 + }); + break; + case "Object": + self.expression = make_node(AST_Object, self.expression, { + properties: [] + }); + break; + case "RegExp": + self.expression = make_node(AST_RegExp, self.expression, { + value: { source: "t", flags: "" } + }); + break; + case "String": + self.expression = make_node(AST_String, self.expression, { + value: "" + }); + break; + } + } + if (!(parent instanceof AST_Call) || !has_annotation(parent, _NOINLINE)) { + const sub = self.flatten_object(self.property, compressor); + if (sub) return sub.optimize(compressor); + } + let ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +function literals_in_boolean_context(self, compressor) { + if (compressor.in_boolean_context()) { + return best_of(compressor, self, make_sequence(self, [ + self, + make_node(AST_True, self) + ]).optimize(compressor)); + } + return self; +} + +function inline_array_like_spread(elements) { + for (var i = 0; i < elements.length; i++) { + var el = elements[i]; + if (el instanceof AST_Expansion) { + var expr = el.expression; + if ( + expr instanceof AST_Array + && !expr.elements.some(elm => elm instanceof AST_Hole) + ) { + elements.splice(i, 1, ...expr.elements); + // Step back one, as the element at i is now new. + i--; + } + // In array-like spread, spreading a non-iterable value is TypeError. + // We therefore can’t optimize anything else, unlike with object spread. + } + } +} + +def_optimize(AST_Array, function(self, compressor) { + var optimized = literals_in_boolean_context(self, compressor); + if (optimized !== self) { + return optimized; + } + inline_array_like_spread(self.elements); + return self; +}); + +function inline_object_prop_spread(props, compressor) { + for (var i = 0; i < props.length; i++) { + var prop = props[i]; + if (prop instanceof AST_Expansion) { + const expr = prop.expression; + if ( + expr instanceof AST_Object + && expr.properties.every(prop => prop instanceof AST_ObjectKeyVal) + ) { + props.splice(i, 1, ...expr.properties); + // Step back one, as the property at i is now new. + i--; + } else if (expr instanceof AST_Constant + && !(expr instanceof AST_String)) { + // Unlike array-like spread, in object spread, spreading a + // non-iterable value silently does nothing; it is thus safe + // to remove. AST_String is the only iterable AST_Constant. + props.splice(i, 1); + i--; + } else if (is_nullish(expr, compressor)) { + // Likewise, null and undefined can be silently removed. + props.splice(i, 1); + i--; + } + } + } +} + +def_optimize(AST_Object, function(self, compressor) { + var optimized = literals_in_boolean_context(self, compressor); + if (optimized !== self) { + return optimized; + } + inline_object_prop_spread(self.properties, compressor); + return self; +}); + +def_optimize(AST_RegExp, literals_in_boolean_context); + +def_optimize(AST_Return, function(self, compressor) { + if (self.value && is_undefined(self.value, compressor)) { + self.value = null; + } + return self; +}); + +def_optimize(AST_Arrow, opt_AST_Lambda); + +def_optimize(AST_Function, function(self, compressor) { + self = opt_AST_Lambda(self, compressor); + if (compressor.option("unsafe_arrows") + && compressor.option("ecma") >= 2015 + && !self.name + && !self.is_generator + && !self.uses_arguments + && !self.pinned()) { + const uses_this = walk(self, node => { + if (node instanceof AST_This) return walk_abort; + }); + if (!uses_this) return make_node(AST_Arrow, self, self).optimize(compressor); + } + return self; +}); + +def_optimize(AST_Class, function(self) { + // HACK to avoid compress failure. + // AST_Class is not really an AST_Scope/AST_Block as it lacks a body. + return self; +}); + +def_optimize(AST_Yield, function(self, compressor) { + if (self.expression && !self.is_star && is_undefined(self.expression, compressor)) { + self.expression = null; + } + return self; +}); + +def_optimize(AST_TemplateString, function(self, compressor) { + if ( + !compressor.option("evaluate") + || compressor.parent() instanceof AST_PrefixedTemplateString + ) { + return self; + } + + var segments = []; + for (var i = 0; i < self.segments.length; i++) { + var segment = self.segments[i]; + if (segment instanceof AST_Node) { + var result = segment.evaluate(compressor); + // Evaluate to constant value + // Constant value shorter than ${segment} + if (result !== segment && (result + "").length <= segment.size() + "${}".length) { + // There should always be a previous and next segment if segment is a node + segments[segments.length - 1].value = segments[segments.length - 1].value + result + self.segments[++i].value; + continue; + } + // `before ${`innerBefore ${any} innerAfter`} after` => `before innerBefore ${any} innerAfter after` + // TODO: + // `before ${'test' + foo} after` => `before innerBefore ${any} innerAfter after` + // `before ${foo + 'test} after` => `before innerBefore ${any} innerAfter after` + if (segment instanceof AST_TemplateString) { + var inners = segment.segments; + segments[segments.length - 1].value += inners[0].value; + for (var j = 1; j < inners.length; j++) { + segment = inners[j]; + segments.push(segment); + } + continue; + } + } + segments.push(segment); + } + self.segments = segments; + + // `foo` => "foo" + if (segments.length == 1) { + return make_node(AST_String, self, segments[0]); + } + + if ( + segments.length === 3 + && segments[1] instanceof AST_Node + && ( + segments[1].is_string(compressor) + || segments[1].is_number(compressor) + || is_nullish(segments[1], compressor) + || compressor.option("unsafe") + ) + ) { + // `foo${bar}` => "foo" + bar + if (segments[2].value === "") { + return make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_String, self, { + value: segments[0].value, + }), + right: segments[1], + }); + } + // `${bar}baz` => bar + "baz" + if (segments[0].value === "") { + return make_node(AST_Binary, self, { + operator: "+", + left: segments[1], + right: make_node(AST_String, self, { + value: segments[2].value, + }), + }); + } + } + return self; +}); + +def_optimize(AST_PrefixedTemplateString, function(self) { + return self; +}); + +// ["p"]:1 ---> p:1 +// [42]:1 ---> 42:1 +function lift_key(self, compressor) { + if (!compressor.option("computed_props")) return self; + // save a comparison in the typical case + if (!(self.key instanceof AST_Constant)) return self; + // allow certain acceptable props as not all AST_Constants are true constants + if (self.key instanceof AST_String || self.key instanceof AST_Number) { + if (self.key.value === "__proto__") return self; + if (self.key.value == "constructor" + && compressor.parent() instanceof AST_Class) return self; + if (self instanceof AST_ObjectKeyVal) { + self.quote = self.key.quote; + self.key = self.key.value; + } else if (self instanceof AST_ClassProperty) { + self.quote = self.key.quote; + self.key = make_node(AST_SymbolClassProperty, self.key, { + name: self.key.value + }); + } else { + self.quote = self.key.quote; + self.key = make_node(AST_SymbolMethod, self.key, { + name: self.key.value + }); + } + } + return self; +} + +def_optimize(AST_ObjectProperty, lift_key); + +def_optimize(AST_ConciseMethod, function(self, compressor) { + lift_key(self, compressor); + // p(){return x;} ---> p:()=>x + if (compressor.option("arrows") + && compressor.parent() instanceof AST_Object + && !self.is_generator + && !self.value.uses_arguments + && !self.value.pinned() + && self.value.body.length == 1 + && self.value.body[0] instanceof AST_Return + && self.value.body[0].value + && !self.value.contains_this()) { + var arrow = make_node(AST_Arrow, self.value, self.value); + arrow.async = self.async; + arrow.is_generator = self.is_generator; + return make_node(AST_ObjectKeyVal, self, { + key: self.key instanceof AST_SymbolMethod ? self.key.name : self.key, + value: arrow, + quote: self.quote, + }); + } + return self; +}); + +def_optimize(AST_ObjectKeyVal, function(self, compressor) { + lift_key(self, compressor); + // p:function(){} ---> p(){} + // p:function*(){} ---> *p(){} + // p:async function(){} ---> async p(){} + // p:()=>{} ---> p(){} + // p:async()=>{} ---> async p(){} + var unsafe_methods = compressor.option("unsafe_methods"); + if (unsafe_methods + && compressor.option("ecma") >= 2015 + && (!(unsafe_methods instanceof RegExp) || unsafe_methods.test(self.key + ""))) { + var key = self.key; + var value = self.value; + var is_arrow_with_block = value instanceof AST_Arrow + && Array.isArray(value.body) + && !value.contains_this(); + if ((is_arrow_with_block || value instanceof AST_Function) && !value.name) { + return make_node(AST_ConciseMethod, self, { + async: value.async, + is_generator: value.is_generator, + key: key instanceof AST_Node ? key : make_node(AST_SymbolMethod, self, { + name: key, + }), + value: make_node(AST_Accessor, value, value), + quote: self.quote, + }); + } + } + return self; +}); + +def_optimize(AST_Destructuring, function(self, compressor) { + if (compressor.option("pure_getters") == true + && compressor.option("unused") + && !self.is_array + && Array.isArray(self.names) + && !is_destructuring_export_decl(compressor) + && !(self.names[self.names.length - 1] instanceof AST_Expansion)) { + var keep = []; + for (var i = 0; i < self.names.length; i++) { + var elem = self.names[i]; + if (!(elem instanceof AST_ObjectKeyVal + && typeof elem.key == "string" + && elem.value instanceof AST_SymbolDeclaration + && !should_retain(compressor, elem.value.definition()))) { + keep.push(elem); + } + } + if (keep.length != self.names.length) { + self.names = keep; + } + } + return self; + + function is_destructuring_export_decl(compressor) { + var ancestors = [/^VarDef$/, /^(Const|Let|Var)$/, /^Export$/]; + for (var a = 0, p = 0, len = ancestors.length; a < len; p++) { + var parent = compressor.parent(p); + if (!parent) return false; + if (a === 0 && parent.TYPE == "Destructuring") continue; + if (!ancestors[a].test(parent.TYPE)) { + return false; + } + a++; + } + return true; + } + + function should_retain(compressor, def) { + if (def.references.length) return true; + if (!def.global) return false; + if (compressor.toplevel.vars) { + if (compressor.top_retain) { + return compressor.top_retain(def); + } + return false; + } + return true; + } +}); + +export { + Compressor, +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/compress/inference.js b/node_modules/mathjs/examples/node_modules/terser/lib/compress/inference.js new file mode 100644 index 0000000..0b2c982 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/compress/inference.js @@ -0,0 +1,948 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Array, + AST_Arrow, + AST_Assign, + AST_Binary, + AST_Block, + AST_BlockStatement, + AST_Call, + AST_Case, + AST_Chain, + AST_Class, + AST_ClassProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Constant, + AST_Definitions, + AST_Dot, + AST_EmptyStatement, + AST_Expansion, + AST_False, + AST_Function, + AST_If, + AST_Import, + AST_Jump, + AST_LabeledStatement, + AST_Lambda, + AST_New, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_String, + AST_Sub, + AST_Switch, + AST_SwitchBranch, + AST_SymbolClassProperty, + AST_SymbolDeclaration, + AST_SymbolRef, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Toplevel, + AST_True, + AST_Try, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Undefined, + AST_VarDef, + + TreeTransformer, + walk, + walk_abort, + + _PURE +} from "../ast.js"; +import { + makePredicate, + return_true, + return_false, + return_null, + return_this, + make_node, + member, + noop, + has_annotation, + HOP +} from "../utils/index.js"; +import { make_node_from_constant, make_sequence, best_of_expression, read_property } from "./common.js"; + +import { INLINED, UNDEFINED, has_flag } from "./compressor-flags.js"; +import { pure_prop_access_globals, is_pure_native_fn, is_pure_native_method } from "./native-objects.js"; + +// Functions and methods to infer certain facts about expressions +// It's not always possible to be 100% sure about something just by static analysis, +// so `true` means yes, and `false` means maybe + +export const is_undeclared_ref = (node) => + node instanceof AST_SymbolRef && node.definition().undeclared; + +export const lazy_op = makePredicate("&& || ??"); +export const unary_side_effects = makePredicate("delete ++ --"); + +// methods to determine whether an expression has a boolean result type +(function(def_is_boolean) { + const unary_bool = makePredicate("! delete"); + const binary_bool = makePredicate("in instanceof == != === !== < <= >= >"); + def_is_boolean(AST_Node, return_false); + def_is_boolean(AST_UnaryPrefix, function() { + return unary_bool.has(this.operator); + }); + def_is_boolean(AST_Binary, function() { + return binary_bool.has(this.operator) + || lazy_op.has(this.operator) + && this.left.is_boolean() + && this.right.is_boolean(); + }); + def_is_boolean(AST_Conditional, function() { + return this.consequent.is_boolean() && this.alternative.is_boolean(); + }); + def_is_boolean(AST_Assign, function() { + return this.operator == "=" && this.right.is_boolean(); + }); + def_is_boolean(AST_Sequence, function() { + return this.tail_node().is_boolean(); + }); + def_is_boolean(AST_True, return_true); + def_is_boolean(AST_False, return_true); +})(function(node, func) { + node.DEFMETHOD("is_boolean", func); +}); + +// methods to determine if an expression has a numeric result type +(function(def_is_number) { + def_is_number(AST_Node, return_false); + def_is_number(AST_Number, return_true); + const unary = makePredicate("+ - ~ ++ --"); + def_is_number(AST_Unary, function() { + return unary.has(this.operator); + }); + const numeric_ops = makePredicate("- * / % & | ^ << >> >>>"); + def_is_number(AST_Binary, function(compressor) { + return numeric_ops.has(this.operator) || this.operator == "+" + && this.left.is_number(compressor) + && this.right.is_number(compressor); + }); + def_is_number(AST_Assign, function(compressor) { + return numeric_ops.has(this.operator.slice(0, -1)) + || this.operator == "=" && this.right.is_number(compressor); + }); + def_is_number(AST_Sequence, function(compressor) { + return this.tail_node().is_number(compressor); + }); + def_is_number(AST_Conditional, function(compressor) { + return this.consequent.is_number(compressor) && this.alternative.is_number(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("is_number", func); +}); + +// methods to determine if an expression has a string result type +(function(def_is_string) { + def_is_string(AST_Node, return_false); + def_is_string(AST_String, return_true); + def_is_string(AST_TemplateString, return_true); + def_is_string(AST_UnaryPrefix, function() { + return this.operator == "typeof"; + }); + def_is_string(AST_Binary, function(compressor) { + return this.operator == "+" && + (this.left.is_string(compressor) || this.right.is_string(compressor)); + }); + def_is_string(AST_Assign, function(compressor) { + return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor); + }); + def_is_string(AST_Sequence, function(compressor) { + return this.tail_node().is_string(compressor); + }); + def_is_string(AST_Conditional, function(compressor) { + return this.consequent.is_string(compressor) && this.alternative.is_string(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("is_string", func); +}); + +export function is_undefined(node, compressor) { + return ( + has_flag(node, UNDEFINED) + || node instanceof AST_Undefined + || node instanceof AST_UnaryPrefix + && node.operator == "void" + && !node.expression.has_side_effects(compressor) + ); +} + +// Is the node explicitly null or undefined. +function is_null_or_undefined(node, compressor) { + let fixed; + return ( + node instanceof AST_Null + || is_undefined(node, compressor) + || ( + node instanceof AST_SymbolRef + && (fixed = node.definition().fixed) instanceof AST_Node + && is_nullish(fixed, compressor) + ) + ); +} + +// Find out if this expression is optionally chained from a base-point that we +// can statically analyze as null or undefined. +export function is_nullish_shortcircuited(node, compressor) { + if (node instanceof AST_PropAccess || node instanceof AST_Call) { + return ( + (node.optional && is_null_or_undefined(node.expression, compressor)) + || is_nullish_shortcircuited(node.expression, compressor) + ); + } + if (node instanceof AST_Chain) return is_nullish_shortcircuited(node.expression, compressor); + return false; +} + +// Find out if something is == null, or can short circuit into nullish. +// Used to optimize ?. and ?? +export function is_nullish(node, compressor) { + if (is_null_or_undefined(node, compressor)) return true; + return is_nullish_shortcircuited(node, compressor); +} + +// Determine if expression might cause side effects +// If there's a possibility that a node may change something when it's executed, this returns true +(function(def_has_side_effects) { + def_has_side_effects(AST_Node, return_true); + + def_has_side_effects(AST_EmptyStatement, return_false); + def_has_side_effects(AST_Constant, return_false); + def_has_side_effects(AST_This, return_false); + + function any(list, compressor) { + for (var i = list.length; --i >= 0;) + if (list[i].has_side_effects(compressor)) + return true; + return false; + } + + def_has_side_effects(AST_Block, function(compressor) { + return any(this.body, compressor); + }); + def_has_side_effects(AST_Call, function(compressor) { + if ( + !this.is_callee_pure(compressor) + && (!this.expression.is_call_pure(compressor) + || this.expression.has_side_effects(compressor)) + ) { + return true; + } + return any(this.args, compressor); + }); + def_has_side_effects(AST_Switch, function(compressor) { + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def_has_side_effects(AST_Case, function(compressor) { + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def_has_side_effects(AST_Try, function(compressor) { + return any(this.body, compressor) + || this.bcatch && this.bcatch.has_side_effects(compressor) + || this.bfinally && this.bfinally.has_side_effects(compressor); + }); + def_has_side_effects(AST_If, function(compressor) { + return this.condition.has_side_effects(compressor) + || this.body && this.body.has_side_effects(compressor) + || this.alternative && this.alternative.has_side_effects(compressor); + }); + def_has_side_effects(AST_LabeledStatement, function(compressor) { + return this.body.has_side_effects(compressor); + }); + def_has_side_effects(AST_SimpleStatement, function(compressor) { + return this.body.has_side_effects(compressor); + }); + def_has_side_effects(AST_Lambda, return_false); + def_has_side_effects(AST_Class, function (compressor) { + if (this.extends && this.extends.has_side_effects(compressor)) { + return true; + } + return any(this.properties, compressor); + }); + def_has_side_effects(AST_Binary, function(compressor) { + return this.left.has_side_effects(compressor) + || this.right.has_side_effects(compressor); + }); + def_has_side_effects(AST_Assign, return_true); + def_has_side_effects(AST_Conditional, function(compressor) { + return this.condition.has_side_effects(compressor) + || this.consequent.has_side_effects(compressor) + || this.alternative.has_side_effects(compressor); + }); + def_has_side_effects(AST_Unary, function(compressor) { + return unary_side_effects.has(this.operator) + || this.expression.has_side_effects(compressor); + }); + def_has_side_effects(AST_SymbolRef, function(compressor) { + return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name); + }); + def_has_side_effects(AST_SymbolClassProperty, return_false); + def_has_side_effects(AST_SymbolDeclaration, return_false); + def_has_side_effects(AST_Object, function(compressor) { + return any(this.properties, compressor); + }); + def_has_side_effects(AST_ObjectProperty, function(compressor) { + return ( + this.computed_key() && this.key.has_side_effects(compressor) + || this.value && this.value.has_side_effects(compressor) + ); + }); + def_has_side_effects(AST_ClassProperty, function(compressor) { + return ( + this.computed_key() && this.key.has_side_effects(compressor) + || this.static && this.value && this.value.has_side_effects(compressor) + ); + }); + def_has_side_effects(AST_ConciseMethod, function(compressor) { + return this.computed_key() && this.key.has_side_effects(compressor); + }); + def_has_side_effects(AST_ObjectGetter, function(compressor) { + return this.computed_key() && this.key.has_side_effects(compressor); + }); + def_has_side_effects(AST_ObjectSetter, function(compressor) { + return this.computed_key() && this.key.has_side_effects(compressor); + }); + def_has_side_effects(AST_Array, function(compressor) { + return any(this.elements, compressor); + }); + def_has_side_effects(AST_Dot, function(compressor) { + if (is_nullish(this, compressor)) return false; + return !this.optional && this.expression.may_throw_on_access(compressor) + || this.expression.has_side_effects(compressor); + }); + def_has_side_effects(AST_Sub, function(compressor) { + if (is_nullish(this, compressor)) return false; + + return !this.optional && this.expression.may_throw_on_access(compressor) + || this.expression.has_side_effects(compressor) + || this.property.has_side_effects(compressor); + }); + def_has_side_effects(AST_Chain, function (compressor) { + return this.expression.has_side_effects(compressor); + }); + def_has_side_effects(AST_Sequence, function(compressor) { + return any(this.expressions, compressor); + }); + def_has_side_effects(AST_Definitions, function(compressor) { + return any(this.definitions, compressor); + }); + def_has_side_effects(AST_VarDef, function() { + return this.value; + }); + def_has_side_effects(AST_TemplateSegment, return_false); + def_has_side_effects(AST_TemplateString, function(compressor) { + return any(this.segments, compressor); + }); +})(function(node, func) { + node.DEFMETHOD("has_side_effects", func); +}); + +// determine if expression may throw +(function(def_may_throw) { + def_may_throw(AST_Node, return_true); + + def_may_throw(AST_Constant, return_false); + def_may_throw(AST_EmptyStatement, return_false); + def_may_throw(AST_Lambda, return_false); + def_may_throw(AST_SymbolDeclaration, return_false); + def_may_throw(AST_This, return_false); + + function any(list, compressor) { + for (var i = list.length; --i >= 0;) + if (list[i].may_throw(compressor)) + return true; + return false; + } + + def_may_throw(AST_Class, function(compressor) { + if (this.extends && this.extends.may_throw(compressor)) return true; + return any(this.properties, compressor); + }); + + def_may_throw(AST_Array, function(compressor) { + return any(this.elements, compressor); + }); + def_may_throw(AST_Assign, function(compressor) { + if (this.right.may_throw(compressor)) return true; + if (!compressor.has_directive("use strict") + && this.operator == "=" + && this.left instanceof AST_SymbolRef) { + return false; + } + return this.left.may_throw(compressor); + }); + def_may_throw(AST_Binary, function(compressor) { + return this.left.may_throw(compressor) + || this.right.may_throw(compressor); + }); + def_may_throw(AST_Block, function(compressor) { + return any(this.body, compressor); + }); + def_may_throw(AST_Call, function(compressor) { + if (is_nullish(this, compressor)) return false; + if (any(this.args, compressor)) return true; + if (this.is_callee_pure(compressor)) return false; + if (this.expression.may_throw(compressor)) return true; + return !(this.expression instanceof AST_Lambda) + || any(this.expression.body, compressor); + }); + def_may_throw(AST_Case, function(compressor) { + return this.expression.may_throw(compressor) + || any(this.body, compressor); + }); + def_may_throw(AST_Conditional, function(compressor) { + return this.condition.may_throw(compressor) + || this.consequent.may_throw(compressor) + || this.alternative.may_throw(compressor); + }); + def_may_throw(AST_Definitions, function(compressor) { + return any(this.definitions, compressor); + }); + def_may_throw(AST_If, function(compressor) { + return this.condition.may_throw(compressor) + || this.body && this.body.may_throw(compressor) + || this.alternative && this.alternative.may_throw(compressor); + }); + def_may_throw(AST_LabeledStatement, function(compressor) { + return this.body.may_throw(compressor); + }); + def_may_throw(AST_Object, function(compressor) { + return any(this.properties, compressor); + }); + def_may_throw(AST_ObjectProperty, function(compressor) { + // TODO key may throw too + return this.value ? this.value.may_throw(compressor) : false; + }); + def_may_throw(AST_ClassProperty, function(compressor) { + return ( + this.computed_key() && this.key.may_throw(compressor) + || this.static && this.value && this.value.may_throw(compressor) + ); + }); + def_may_throw(AST_ConciseMethod, function(compressor) { + return this.computed_key() && this.key.may_throw(compressor); + }); + def_may_throw(AST_ObjectGetter, function(compressor) { + return this.computed_key() && this.key.may_throw(compressor); + }); + def_may_throw(AST_ObjectSetter, function(compressor) { + return this.computed_key() && this.key.may_throw(compressor); + }); + def_may_throw(AST_Return, function(compressor) { + return this.value && this.value.may_throw(compressor); + }); + def_may_throw(AST_Sequence, function(compressor) { + return any(this.expressions, compressor); + }); + def_may_throw(AST_SimpleStatement, function(compressor) { + return this.body.may_throw(compressor); + }); + def_may_throw(AST_Dot, function(compressor) { + if (is_nullish(this, compressor)) return false; + return !this.optional && this.expression.may_throw_on_access(compressor) + || this.expression.may_throw(compressor); + }); + def_may_throw(AST_Sub, function(compressor) { + if (is_nullish(this, compressor)) return false; + return !this.optional && this.expression.may_throw_on_access(compressor) + || this.expression.may_throw(compressor) + || this.property.may_throw(compressor); + }); + def_may_throw(AST_Chain, function(compressor) { + return this.expression.may_throw(compressor); + }); + def_may_throw(AST_Switch, function(compressor) { + return this.expression.may_throw(compressor) + || any(this.body, compressor); + }); + def_may_throw(AST_SymbolRef, function(compressor) { + return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name); + }); + def_may_throw(AST_SymbolClassProperty, return_false); + def_may_throw(AST_Try, function(compressor) { + return this.bcatch ? this.bcatch.may_throw(compressor) : any(this.body, compressor) + || this.bfinally && this.bfinally.may_throw(compressor); + }); + def_may_throw(AST_Unary, function(compressor) { + if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) + return false; + return this.expression.may_throw(compressor); + }); + def_may_throw(AST_VarDef, function(compressor) { + if (!this.value) return false; + return this.value.may_throw(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("may_throw", func); +}); + +// determine if expression is constant +(function(def_is_constant_expression) { + function all_refs_local(scope) { + let result = true; + walk(this, node => { + if (node instanceof AST_SymbolRef) { + if (has_flag(this, INLINED)) { + result = false; + return walk_abort; + } + var def = node.definition(); + if ( + member(def, this.enclosed) + && !this.variables.has(def.name) + ) { + if (scope) { + var scope_def = scope.find_variable(node); + if (def.undeclared ? !scope_def : scope_def === def) { + result = "f"; + return true; + } + } + result = false; + return walk_abort; + } + return true; + } + if (node instanceof AST_This && this instanceof AST_Arrow) { + // TODO check arguments too! + result = false; + return walk_abort; + } + }); + return result; + } + + def_is_constant_expression(AST_Node, return_false); + def_is_constant_expression(AST_Constant, return_true); + def_is_constant_expression(AST_Class, function(scope) { + if (this.extends && !this.extends.is_constant_expression(scope)) { + return false; + } + + for (const prop of this.properties) { + if (prop.computed_key() && !prop.key.is_constant_expression(scope)) { + return false; + } + if (prop.static && prop.value && !prop.value.is_constant_expression(scope)) { + return false; + } + } + + return all_refs_local.call(this, scope); + }); + def_is_constant_expression(AST_Lambda, all_refs_local); + def_is_constant_expression(AST_Unary, function() { + return this.expression.is_constant_expression(); + }); + def_is_constant_expression(AST_Binary, function() { + return this.left.is_constant_expression() + && this.right.is_constant_expression(); + }); + def_is_constant_expression(AST_Array, function() { + return this.elements.every((l) => l.is_constant_expression()); + }); + def_is_constant_expression(AST_Object, function() { + return this.properties.every((l) => l.is_constant_expression()); + }); + def_is_constant_expression(AST_ObjectProperty, function() { + return !!(!(this.key instanceof AST_Node) && this.value && this.value.is_constant_expression()); + }); +})(function(node, func) { + node.DEFMETHOD("is_constant_expression", func); +}); + + +// may_throw_on_access() +// returns true if this node may be null, undefined or contain `AST_Accessor` +(function(def_may_throw_on_access) { + AST_Node.DEFMETHOD("may_throw_on_access", function(compressor) { + return !compressor.option("pure_getters") + || this._dot_throw(compressor); + }); + + function is_strict(compressor) { + return /strict/.test(compressor.option("pure_getters")); + } + + def_may_throw_on_access(AST_Node, is_strict); + def_may_throw_on_access(AST_Null, return_true); + def_may_throw_on_access(AST_Undefined, return_true); + def_may_throw_on_access(AST_Constant, return_false); + def_may_throw_on_access(AST_Array, return_false); + def_may_throw_on_access(AST_Object, function(compressor) { + if (!is_strict(compressor)) return false; + for (var i = this.properties.length; --i >=0;) + if (this.properties[i]._dot_throw(compressor)) return true; + return false; + }); + // Do not be as strict with classes as we are with objects. + // Hopefully the community is not going to abuse static getters and setters. + // https://github.com/terser/terser/issues/724#issuecomment-643655656 + def_may_throw_on_access(AST_Class, return_false); + def_may_throw_on_access(AST_ObjectProperty, return_false); + def_may_throw_on_access(AST_ObjectGetter, return_true); + def_may_throw_on_access(AST_Expansion, function(compressor) { + return this.expression._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Function, return_false); + def_may_throw_on_access(AST_Arrow, return_false); + def_may_throw_on_access(AST_UnaryPostfix, return_false); + def_may_throw_on_access(AST_UnaryPrefix, function() { + return this.operator == "void"; + }); + def_may_throw_on_access(AST_Binary, function(compressor) { + return (this.operator == "&&" || this.operator == "||" || this.operator == "??") + && (this.left._dot_throw(compressor) || this.right._dot_throw(compressor)); + }); + def_may_throw_on_access(AST_Assign, function(compressor) { + if (this.logical) return true; + + return this.operator == "=" + && this.right._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Conditional, function(compressor) { + return this.consequent._dot_throw(compressor) + || this.alternative._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Dot, function(compressor) { + if (!is_strict(compressor)) return false; + + if (this.property == "prototype") { + return !( + this.expression instanceof AST_Function + || this.expression instanceof AST_Class + ); + } + return true; + }); + def_may_throw_on_access(AST_Chain, function(compressor) { + return this.expression._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Sequence, function(compressor) { + return this.tail_node()._dot_throw(compressor); + }); + def_may_throw_on_access(AST_SymbolRef, function(compressor) { + if (this.name === "arguments") return false; + if (has_flag(this, UNDEFINED)) return true; + if (!is_strict(compressor)) return false; + if (is_undeclared_ref(this) && this.is_declared(compressor)) return false; + if (this.is_immutable()) return false; + var fixed = this.fixed_value(); + return !fixed || fixed._dot_throw(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("_dot_throw", func); +}); + +export function is_lhs(node, parent) { + if (parent instanceof AST_Unary && unary_side_effects.has(parent.operator)) return parent.expression; + if (parent instanceof AST_Assign && parent.left === node) return node; +} + +(function(def_find_defs) { + function to_node(value, orig) { + if (value instanceof AST_Node) { + if (!(value instanceof AST_Constant)) { + // Value may be a function, an array including functions and even a complex assign / block expression, + // so it should never be shared in different places. + // Otherwise wrong information may be used in the compression phase + value = value.clone(true); + } + return make_node(value.CTOR, orig, value); + } + if (Array.isArray(value)) return make_node(AST_Array, orig, { + elements: value.map(function(value) { + return to_node(value, orig); + }) + }); + if (value && typeof value == "object") { + var props = []; + for (var key in value) if (HOP(value, key)) { + props.push(make_node(AST_ObjectKeyVal, orig, { + key: key, + value: to_node(value[key], orig) + })); + } + return make_node(AST_Object, orig, { + properties: props + }); + } + return make_node_from_constant(value, orig); + } + + AST_Toplevel.DEFMETHOD("resolve_defines", function(compressor) { + if (!compressor.option("global_defs")) return this; + this.figure_out_scope({ ie8: compressor.option("ie8") }); + return this.transform(new TreeTransformer(function(node) { + var def = node._find_defs(compressor, ""); + if (!def) return; + var level = 0, child = node, parent; + while (parent = this.parent(level++)) { + if (!(parent instanceof AST_PropAccess)) break; + if (parent.expression !== child) break; + child = parent; + } + if (is_lhs(child, parent)) { + return; + } + return def; + })); + }); + def_find_defs(AST_Node, noop); + def_find_defs(AST_Chain, function(compressor, suffix) { + return this.expression._find_defs(compressor, suffix); + }); + def_find_defs(AST_Dot, function(compressor, suffix) { + return this.expression._find_defs(compressor, "." + this.property + suffix); + }); + def_find_defs(AST_SymbolDeclaration, function() { + if (!this.global()) return; + }); + def_find_defs(AST_SymbolRef, function(compressor, suffix) { + if (!this.global()) return; + var defines = compressor.option("global_defs"); + var name = this.name + suffix; + if (HOP(defines, name)) return to_node(defines[name], this); + }); +})(function(node, func) { + node.DEFMETHOD("_find_defs", func); +}); + +// method to negate an expression +(function(def_negate) { + function basic_negation(exp) { + return make_node(AST_UnaryPrefix, exp, { + operator: "!", + expression: exp + }); + } + function best(orig, alt, first_in_statement) { + var negated = basic_negation(orig); + if (first_in_statement) { + var stat = make_node(AST_SimpleStatement, alt, { + body: alt + }); + return best_of_expression(negated, stat) === stat ? alt : negated; + } + return best_of_expression(negated, alt); + } + def_negate(AST_Node, function() { + return basic_negation(this); + }); + def_negate(AST_Statement, function() { + throw new Error("Cannot negate a statement"); + }); + def_negate(AST_Function, function() { + return basic_negation(this); + }); + def_negate(AST_Arrow, function() { + return basic_negation(this); + }); + def_negate(AST_UnaryPrefix, function() { + if (this.operator == "!") + return this.expression; + return basic_negation(this); + }); + def_negate(AST_Sequence, function(compressor) { + var expressions = this.expressions.slice(); + expressions.push(expressions.pop().negate(compressor)); + return make_sequence(this, expressions); + }); + def_negate(AST_Conditional, function(compressor, first_in_statement) { + var self = this.clone(); + self.consequent = self.consequent.negate(compressor); + self.alternative = self.alternative.negate(compressor); + return best(this, self, first_in_statement); + }); + def_negate(AST_Binary, function(compressor, first_in_statement) { + var self = this.clone(), op = this.operator; + if (compressor.option("unsafe_comps")) { + switch (op) { + case "<=" : self.operator = ">" ; return self; + case "<" : self.operator = ">=" ; return self; + case ">=" : self.operator = "<" ; return self; + case ">" : self.operator = "<=" ; return self; + } + } + switch (op) { + case "==" : self.operator = "!="; return self; + case "!=" : self.operator = "=="; return self; + case "===": self.operator = "!=="; return self; + case "!==": self.operator = "==="; return self; + case "&&": + self.operator = "||"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + case "||": + self.operator = "&&"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + } + return basic_negation(this); + }); +})(function(node, func) { + node.DEFMETHOD("negate", function(compressor, first_in_statement) { + return func.call(this, compressor, first_in_statement); + }); +}); + +// Is the callee of this function pure? +var global_pure_fns = makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError"); +AST_Call.DEFMETHOD("is_callee_pure", function(compressor) { + if (compressor.option("unsafe")) { + var expr = this.expression; + var first_arg = (this.args && this.args[0] && this.args[0].evaluate(compressor)); + if ( + expr.expression && expr.expression.name === "hasOwnProperty" && + (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared) + ) { + return false; + } + if (is_undeclared_ref(expr) && global_pure_fns.has(expr.name)) return true; + if ( + expr instanceof AST_Dot + && is_undeclared_ref(expr.expression) + && is_pure_native_fn(expr.expression.name, expr.property) + ) { + return true; + } + } + return !!has_annotation(this, _PURE) || !compressor.pure_funcs(this); +}); + +// If I call this, is it a pure function? +AST_Node.DEFMETHOD("is_call_pure", return_false); +AST_Dot.DEFMETHOD("is_call_pure", function(compressor) { + if (!compressor.option("unsafe")) return; + const expr = this.expression; + + let native_obj; + if (expr instanceof AST_Array) { + native_obj = "Array"; + } else if (expr.is_boolean()) { + native_obj = "Boolean"; + } else if (expr.is_number(compressor)) { + native_obj = "Number"; + } else if (expr instanceof AST_RegExp) { + native_obj = "RegExp"; + } else if (expr.is_string(compressor)) { + native_obj = "String"; + } else if (!this.may_throw_on_access(compressor)) { + native_obj = "Object"; + } + return native_obj != null && is_pure_native_method(native_obj, this.property); +}); + +// tell me if a statement aborts +export const aborts = (thing) => thing && thing.aborts(); + +(function(def_aborts) { + def_aborts(AST_Statement, return_null); + def_aborts(AST_Jump, return_this); + function block_aborts() { + for (var i = 0; i < this.body.length; i++) { + if (aborts(this.body[i])) { + return this.body[i]; + } + } + return null; + } + def_aborts(AST_Import, function() { return null; }); + def_aborts(AST_BlockStatement, block_aborts); + def_aborts(AST_SwitchBranch, block_aborts); + def_aborts(AST_If, function() { + return this.alternative && aborts(this.body) && aborts(this.alternative) && this; + }); +})(function(node, func) { + node.DEFMETHOD("aborts", func); +}); + +export function is_modified(compressor, tw, node, value, level, immutable) { + var parent = tw.parent(level); + var lhs = is_lhs(node, parent); + if (lhs) return lhs; + if (!immutable + && parent instanceof AST_Call + && parent.expression === node + && !(value instanceof AST_Arrow) + && !(value instanceof AST_Class) + && !parent.is_callee_pure(compressor) + && (!(value instanceof AST_Function) + || !(parent instanceof AST_New) && value.contains_this())) { + return true; + } + if (parent instanceof AST_Array) { + return is_modified(compressor, tw, parent, parent, level + 1); + } + if (parent instanceof AST_ObjectKeyVal && node === parent.value) { + var obj = tw.parent(level + 1); + return is_modified(compressor, tw, obj, obj, level + 2); + } + if (parent instanceof AST_PropAccess && parent.expression === node) { + var prop = read_property(value, parent.property); + return !immutable && is_modified(compressor, tw, parent, prop, level + 1); + } +} diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/compress/native-objects.js b/node_modules/mathjs/examples/node_modules/terser/lib/compress/native-objects.js new file mode 100644 index 0000000..3d81a03 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/compress/native-objects.js @@ -0,0 +1,184 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { makePredicate } from "../utils/index.js"; + +// Lists of native methods, useful for `unsafe` option which assumes they exist. +// Note: Lots of methods and functions are missing here, in case they aren't pure +// or not available in all JS environments. + +function make_nested_lookup(obj) { + const out = new Map(); + for (var key of Object.keys(obj)) { + out.set(key, makePredicate(obj[key])); + } + + const does_have = (global_name, fname) => { + const inner_map = out.get(global_name); + return inner_map != null && inner_map.has(fname); + }; + return does_have; +} + +// Objects which are safe to access without throwing or causing a side effect. +// Usually we'd check the `unsafe` option first but these are way too common for that +export const pure_prop_access_globals = new Set([ + "Number", + "String", + "Array", + "Object", + "Function", + "Promise", +]); + +const object_methods = [ + "constructor", + "toString", + "valueOf", +]; + +export const is_pure_native_method = make_nested_lookup({ + Array: [ + "indexOf", + "join", + "lastIndexOf", + "slice", + ...object_methods, + ], + Boolean: object_methods, + Function: object_methods, + Number: [ + "toExponential", + "toFixed", + "toPrecision", + ...object_methods, + ], + Object: object_methods, + RegExp: [ + "test", + ...object_methods, + ], + String: [ + "charAt", + "charCodeAt", + "concat", + "indexOf", + "italics", + "lastIndexOf", + "match", + "replace", + "search", + "slice", + "split", + "substr", + "substring", + "toLowerCase", + "toUpperCase", + "trim", + ...object_methods, + ], +}); + +export const is_pure_native_fn = make_nested_lookup({ + Array: [ + "isArray", + ], + Math: [ + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "exp", + "floor", + "log", + "round", + "sin", + "sqrt", + "tan", + "atan2", + "pow", + "max", + "min", + ], + Number: [ + "isFinite", + "isNaN", + ], + Object: [ + "create", + "getOwnPropertyDescriptor", + "getOwnPropertyNames", + "getPrototypeOf", + "isExtensible", + "isFrozen", + "isSealed", + "hasOwn", + "keys", + ], + String: [ + "fromCharCode", + ], +}); + +// Known numeric values which come with JS environments +export const is_pure_native_value = make_nested_lookup({ + Math: [ + "E", + "LN10", + "LN2", + "LOG2E", + "LOG10E", + "PI", + "SQRT1_2", + "SQRT2", + ], + Number: [ + "MAX_VALUE", + "MIN_VALUE", + "NaN", + "NEGATIVE_INFINITY", + "POSITIVE_INFINITY", + ], +}); diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/compress/reduce-vars.js b/node_modules/mathjs/examples/node_modules/terser/lib/compress/reduce-vars.js new file mode 100644 index 0000000..3764845 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/compress/reduce-vars.js @@ -0,0 +1,675 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Accessor, + AST_Array, + AST_Assign, + AST_Await, + AST_Binary, + AST_Block, + AST_Call, + AST_Case, + AST_Chain, + AST_Class, + AST_ClassExpression, + AST_Conditional, + AST_Default, + AST_Defun, + AST_Destructuring, + AST_Do, + AST_Exit, + AST_Expansion, + AST_For, + AST_ForIn, + AST_If, + AST_LabeledStatement, + AST_Lambda, + AST_New, + AST_Node, + AST_Number, + AST_ObjectKeyVal, + AST_PropAccess, + AST_Sequence, + AST_SimpleStatement, + AST_Symbol, + AST_SymbolCatch, + AST_SymbolConst, + AST_SymbolDefun, + AST_SymbolFunarg, + AST_SymbolLambda, + AST_SymbolRef, + AST_This, + AST_Toplevel, + AST_Try, + AST_Unary, + AST_UnaryPrefix, + AST_Undefined, + AST_VarDef, + AST_While, + AST_Yield, + + walk, + walk_body, + + _INLINE, + _NOINLINE, + _PURE +} from "../ast.js"; +import { HOP, make_node, noop } from "../utils/index.js"; + +import { lazy_op, is_modified } from "./inference.js"; +import { INLINED, clear_flag } from "./compressor-flags.js"; +import { read_property, has_break_or_continue, is_recursive_ref } from "./common.js"; + +// Define the method AST_Node#reduce_vars, which goes through the AST in +// execution order to perform basic flow analysis + +function def_reduce_vars(node, func) { + node.DEFMETHOD("reduce_vars", func); +} + +def_reduce_vars(AST_Node, noop); + +function reset_def(compressor, def) { + def.assignments = 0; + def.chained = false; + def.direct_access = false; + def.escaped = 0; + def.recursive_refs = 0; + def.references = []; + def.single_use = undefined; + if (def.scope.pinned()) { + def.fixed = false; + } else if (def.orig[0] instanceof AST_SymbolConst || !compressor.exposed(def)) { + def.fixed = def.init; + } else { + def.fixed = false; + } +} + +function reset_variables(tw, compressor, node) { + node.variables.forEach(function(def) { + reset_def(compressor, def); + if (def.fixed === null) { + tw.defs_to_safe_ids.set(def.id, tw.safe_ids); + mark(tw, def, true); + } else if (def.fixed) { + tw.loop_ids.set(def.id, tw.in_loop); + mark(tw, def, true); + } + }); +} + +function reset_block_variables(compressor, node) { + if (node.block_scope) node.block_scope.variables.forEach((def) => { + reset_def(compressor, def); + }); +} + +function push(tw) { + tw.safe_ids = Object.create(tw.safe_ids); +} + +function pop(tw) { + tw.safe_ids = Object.getPrototypeOf(tw.safe_ids); +} + +function mark(tw, def, safe) { + tw.safe_ids[def.id] = safe; +} + +function safe_to_read(tw, def) { + if (def.single_use == "m") return false; + if (tw.safe_ids[def.id]) { + if (def.fixed == null) { + var orig = def.orig[0]; + if (orig instanceof AST_SymbolFunarg || orig.name == "arguments") return false; + def.fixed = make_node(AST_Undefined, orig); + } + return true; + } + return def.fixed instanceof AST_Defun; +} + +function safe_to_assign(tw, def, scope, value) { + if (def.fixed === undefined) return true; + let def_safe_ids; + if (def.fixed === null + && (def_safe_ids = tw.defs_to_safe_ids.get(def.id)) + ) { + def_safe_ids[def.id] = false; + tw.defs_to_safe_ids.delete(def.id); + return true; + } + if (!HOP(tw.safe_ids, def.id)) return false; + if (!safe_to_read(tw, def)) return false; + if (def.fixed === false) return false; + if (def.fixed != null && (!value || def.references.length > def.assignments)) return false; + if (def.fixed instanceof AST_Defun) { + return value instanceof AST_Node && def.fixed.parent_scope === scope; + } + return def.orig.every((sym) => { + return !(sym instanceof AST_SymbolConst + || sym instanceof AST_SymbolDefun + || sym instanceof AST_SymbolLambda); + }); +} + +function ref_once(tw, compressor, def) { + return compressor.option("unused") + && !def.scope.pinned() + && def.references.length - def.recursive_refs == 1 + && tw.loop_ids.get(def.id) === tw.in_loop; +} + +function is_immutable(value) { + if (!value) return false; + return value.is_constant() + || value instanceof AST_Lambda + || value instanceof AST_This; +} + +// A definition "escapes" when its value can leave the point of use. +// Example: `a = b || c` +// In this example, "b" and "c" are escaping, because they're going into "a" +// +// def.escaped is != 0 when it escapes. +// +// When greater than 1, it means that N chained properties will be read off +// of that def before an escape occurs. This is useful for evaluating +// property accesses, where you need to know when to stop. +function mark_escaped(tw, d, scope, node, value, level = 0, depth = 1) { + var parent = tw.parent(level); + if (value) { + if (value.is_constant()) return; + if (value instanceof AST_ClassExpression) return; + } + + if ( + parent instanceof AST_Assign && (parent.operator === "=" || parent.logical) && node === parent.right + || parent instanceof AST_Call && (node !== parent.expression || parent instanceof AST_New) + || parent instanceof AST_Exit && node === parent.value && node.scope !== d.scope + || parent instanceof AST_VarDef && node === parent.value + || parent instanceof AST_Yield && node === parent.value && node.scope !== d.scope + ) { + if (depth > 1 && !(value && value.is_constant_expression(scope))) depth = 1; + if (!d.escaped || d.escaped > depth) d.escaped = depth; + return; + } else if ( + parent instanceof AST_Array + || parent instanceof AST_Await + || parent instanceof AST_Binary && lazy_op.has(parent.operator) + || parent instanceof AST_Conditional && node !== parent.condition + || parent instanceof AST_Expansion + || parent instanceof AST_Sequence && node === parent.tail_node() + ) { + mark_escaped(tw, d, scope, parent, parent, level + 1, depth); + } else if (parent instanceof AST_ObjectKeyVal && node === parent.value) { + var obj = tw.parent(level + 1); + + mark_escaped(tw, d, scope, obj, obj, level + 2, depth); + } else if (parent instanceof AST_PropAccess && node === parent.expression) { + value = read_property(value, parent.property); + + mark_escaped(tw, d, scope, parent, value, level + 1, depth + 1); + if (value) return; + } + + if (level > 0) return; + if (parent instanceof AST_Sequence && node !== parent.tail_node()) return; + if (parent instanceof AST_SimpleStatement) return; + + d.direct_access = true; +} + +const suppress = node => walk(node, node => { + if (!(node instanceof AST_Symbol)) return; + var d = node.definition(); + if (!d) return; + if (node instanceof AST_SymbolRef) d.references.push(node); + d.fixed = false; +}); + +def_reduce_vars(AST_Accessor, function(tw, descend, compressor) { + push(tw); + reset_variables(tw, compressor, this); + descend(); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Assign, function(tw, descend, compressor) { + var node = this; + if (node.left instanceof AST_Destructuring) { + suppress(node.left); + return; + } + + const finish_walk = () => { + if (node.logical) { + node.left.walk(tw); + + push(tw); + node.right.walk(tw); + pop(tw); + + return true; + } + }; + + var sym = node.left; + if (!(sym instanceof AST_SymbolRef)) return finish_walk(); + + var def = sym.definition(); + var safe = safe_to_assign(tw, def, sym.scope, node.right); + def.assignments++; + if (!safe) return finish_walk(); + + var fixed = def.fixed; + if (!fixed && node.operator != "=" && !node.logical) return finish_walk(); + + var eq = node.operator == "="; + var value = eq ? node.right : node; + if (is_modified(compressor, tw, node, value, 0)) return finish_walk(); + + def.references.push(sym); + + if (!node.logical) { + if (!eq) def.chained = true; + + def.fixed = eq ? function() { + return node.right; + } : function() { + return make_node(AST_Binary, node, { + operator: node.operator.slice(0, -1), + left: fixed instanceof AST_Node ? fixed : fixed(), + right: node.right + }); + }; + } + + if (node.logical) { + mark(tw, def, false); + push(tw); + node.right.walk(tw); + pop(tw); + return true; + } + + mark(tw, def, false); + node.right.walk(tw); + mark(tw, def, true); + + mark_escaped(tw, def, sym.scope, node, value, 0, 1); + + return true; +}); + +def_reduce_vars(AST_Binary, function(tw) { + if (!lazy_op.has(this.operator)) return; + this.left.walk(tw); + push(tw); + this.right.walk(tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Block, function(tw, descend, compressor) { + reset_block_variables(compressor, this); +}); + +def_reduce_vars(AST_Case, function(tw) { + push(tw); + this.expression.walk(tw); + pop(tw); + push(tw); + walk_body(this, tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Class, function(tw, descend) { + clear_flag(this, INLINED); + push(tw); + descend(); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Conditional, function(tw) { + this.condition.walk(tw); + push(tw); + this.consequent.walk(tw); + pop(tw); + push(tw); + this.alternative.walk(tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Chain, function(tw, descend) { + // Chains' conditions apply left-to-right, cumulatively. + // If we walk normally we don't go in that order because we would pop before pushing again + // Solution: AST_PropAccess and AST_Call push when they are optional, and never pop. + // Then we pop everything when they are done being walked. + const safe_ids = tw.safe_ids; + + descend(); + + // Unroll back to start + tw.safe_ids = safe_ids; + return true; +}); + +def_reduce_vars(AST_Call, function (tw) { + this.expression.walk(tw); + + if (this.optional) { + // Never pop -- it's popped at AST_Chain above + push(tw); + } + + for (const arg of this.args) arg.walk(tw); + + return true; +}); + +def_reduce_vars(AST_PropAccess, function (tw) { + if (!this.optional) return; + + this.expression.walk(tw); + + // Never pop -- it's popped at AST_Chain above + push(tw); + + if (this.property instanceof AST_Node) this.property.walk(tw); + + return true; +}); + +def_reduce_vars(AST_Default, function(tw, descend) { + push(tw); + descend(); + pop(tw); + return true; +}); + +function mark_lambda(tw, descend, compressor) { + clear_flag(this, INLINED); + push(tw); + reset_variables(tw, compressor, this); + if (this.uses_arguments) { + descend(); + pop(tw); + return; + } + var iife; + if (!this.name + && (iife = tw.parent()) instanceof AST_Call + && iife.expression === this + && !iife.args.some(arg => arg instanceof AST_Expansion) + && this.argnames.every(arg_name => arg_name instanceof AST_Symbol) + ) { + // Virtually turn IIFE parameters into variable definitions: + // (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})() + // So existing transformation rules can work on them. + this.argnames.forEach((arg, i) => { + if (!arg.definition) return; + var d = arg.definition(); + // Avoid setting fixed when there's more than one origin for a variable value + if (d.orig.length > 1) return; + if (d.fixed === undefined && (!this.uses_arguments || tw.has_directive("use strict"))) { + d.fixed = function() { + return iife.args[i] || make_node(AST_Undefined, iife); + }; + tw.loop_ids.set(d.id, tw.in_loop); + mark(tw, d, true); + } else { + d.fixed = false; + } + }); + } + descend(); + pop(tw); + return true; +} + +def_reduce_vars(AST_Lambda, mark_lambda); + +def_reduce_vars(AST_Do, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + this.body.walk(tw); + if (has_break_or_continue(this)) { + pop(tw); + push(tw); + } + this.condition.walk(tw); + pop(tw); + tw.in_loop = saved_loop; + return true; +}); + +def_reduce_vars(AST_For, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + if (this.init) this.init.walk(tw); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + if (this.condition) this.condition.walk(tw); + this.body.walk(tw); + if (this.step) { + if (has_break_or_continue(this)) { + pop(tw); + push(tw); + } + this.step.walk(tw); + } + pop(tw); + tw.in_loop = saved_loop; + return true; +}); + +def_reduce_vars(AST_ForIn, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + suppress(this.init); + this.object.walk(tw); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + this.body.walk(tw); + pop(tw); + tw.in_loop = saved_loop; + return true; +}); + +def_reduce_vars(AST_If, function(tw) { + this.condition.walk(tw); + push(tw); + this.body.walk(tw); + pop(tw); + if (this.alternative) { + push(tw); + this.alternative.walk(tw); + pop(tw); + } + return true; +}); + +def_reduce_vars(AST_LabeledStatement, function(tw) { + push(tw); + this.body.walk(tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_SymbolCatch, function() { + this.definition().fixed = false; +}); + +def_reduce_vars(AST_SymbolRef, function(tw, descend, compressor) { + var d = this.definition(); + d.references.push(this); + if (d.references.length == 1 + && !d.fixed + && d.orig[0] instanceof AST_SymbolDefun) { + tw.loop_ids.set(d.id, tw.in_loop); + } + var fixed_value; + if (d.fixed === undefined || !safe_to_read(tw, d)) { + d.fixed = false; + } else if (d.fixed) { + fixed_value = this.fixed_value(); + if ( + fixed_value instanceof AST_Lambda + && is_recursive_ref(tw, d) + ) { + d.recursive_refs++; + } else if (fixed_value + && !compressor.exposed(d) + && ref_once(tw, compressor, d) + ) { + d.single_use = + fixed_value instanceof AST_Lambda && !fixed_value.pinned() + || fixed_value instanceof AST_Class + || d.scope === this.scope && fixed_value.is_constant_expression(); + } else { + d.single_use = false; + } + if (is_modified(compressor, tw, this, fixed_value, 0, is_immutable(fixed_value))) { + if (d.single_use) { + d.single_use = "m"; + } else { + d.fixed = false; + } + } + } + mark_escaped(tw, d, this.scope, this, fixed_value, 0, 1); +}); + +def_reduce_vars(AST_Toplevel, function(tw, descend, compressor) { + this.globals.forEach(function(def) { + reset_def(compressor, def); + }); + reset_variables(tw, compressor, this); +}); + +def_reduce_vars(AST_Try, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + push(tw); + walk_body(this, tw); + pop(tw); + if (this.bcatch) { + push(tw); + this.bcatch.walk(tw); + pop(tw); + } + if (this.bfinally) this.bfinally.walk(tw); + return true; +}); + +def_reduce_vars(AST_Unary, function(tw) { + var node = this; + if (node.operator !== "++" && node.operator !== "--") return; + var exp = node.expression; + if (!(exp instanceof AST_SymbolRef)) return; + var def = exp.definition(); + var safe = safe_to_assign(tw, def, exp.scope, true); + def.assignments++; + if (!safe) return; + var fixed = def.fixed; + if (!fixed) return; + def.references.push(exp); + def.chained = true; + def.fixed = function() { + return make_node(AST_Binary, node, { + operator: node.operator.slice(0, -1), + left: make_node(AST_UnaryPrefix, node, { + operator: "+", + expression: fixed instanceof AST_Node ? fixed : fixed() + }), + right: make_node(AST_Number, node, { + value: 1 + }) + }); + }; + mark(tw, def, true); + return true; +}); + +def_reduce_vars(AST_VarDef, function(tw, descend) { + var node = this; + if (node.name instanceof AST_Destructuring) { + suppress(node.name); + return; + } + var d = node.name.definition(); + if (node.value) { + if (safe_to_assign(tw, d, node.name.scope, node.value)) { + d.fixed = function() { + return node.value; + }; + tw.loop_ids.set(d.id, tw.in_loop); + mark(tw, d, false); + descend(); + mark(tw, d, true); + return true; + } else { + d.fixed = false; + } + } +}); + +def_reduce_vars(AST_While, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + descend(); + pop(tw); + tw.in_loop = saved_loop; + return true; +}); diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/compress/tighten-body.js b/node_modules/mathjs/examples/node_modules/terser/lib/compress/tighten-body.js new file mode 100644 index 0000000..151383e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/compress/tighten-body.js @@ -0,0 +1,1461 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Array, + AST_Arrow, + AST_Assign, + AST_Await, + AST_Binary, + AST_Block, + AST_BlockStatement, + AST_Break, + AST_Call, + AST_Case, + AST_Catch, + AST_Chain, + AST_Class, + AST_Conditional, + AST_Const, + AST_Constant, + AST_Continue, + AST_Debugger, + AST_Default, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Dot, + AST_DWLoop, + AST_EmptyStatement, + AST_Exit, + AST_Expansion, + AST_Export, + AST_Finally, + AST_For, + AST_ForIn, + AST_If, + AST_Import, + AST_IterationStatement, + AST_Lambda, + AST_Let, + AST_LoopControl, + AST_Node, + AST_Number, + AST_Object, + AST_ObjectKeyVal, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Sub, + AST_Switch, + AST_Symbol, + AST_SymbolConst, + AST_SymbolDeclaration, + AST_SymbolDefun, + AST_SymbolFunarg, + AST_SymbolLambda, + AST_SymbolLet, + AST_SymbolRef, + AST_SymbolVar, + AST_This, + AST_Try, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Undefined, + AST_Var, + AST_VarDef, + AST_With, + AST_Yield, + + TreeTransformer, + TreeWalker, + walk, + walk_abort, + + _NOINLINE +} from "../ast.js"; +import { + make_node, + MAP, + member, + remove, + has_annotation +} from "../utils/index.js"; + +import { pure_prop_access_globals } from "./native-objects.js"; +import { + lazy_op, + unary_side_effects, + is_modified, + is_lhs, + aborts +} from "./inference.js"; +import { WRITE_ONLY, clear_flag } from "./compressor-flags.js"; +import { + make_sequence, + merge_sequence, + maintain_this_binding, + is_func_expr, + is_identifier_atom, + is_ref_of, + can_be_evicted_from_block, + as_statement_array, +} from "./common.js"; + +function loop_body(x) { + if (x instanceof AST_IterationStatement) { + return x.body instanceof AST_BlockStatement ? x.body : x; + } + return x; +} + +function is_lhs_read_only(lhs) { + if (lhs instanceof AST_This) return true; + if (lhs instanceof AST_SymbolRef) return lhs.definition().orig[0] instanceof AST_SymbolLambda; + if (lhs instanceof AST_PropAccess) { + lhs = lhs.expression; + if (lhs instanceof AST_SymbolRef) { + if (lhs.is_immutable()) return false; + lhs = lhs.fixed_value(); + } + if (!lhs) return true; + if (lhs instanceof AST_RegExp) return false; + if (lhs instanceof AST_Constant) return true; + return is_lhs_read_only(lhs); + } + return false; +} + +// Remove code which we know is unreachable. +export function trim_unreachable_code(compressor, stat, target) { + walk(stat, node => { + if (node instanceof AST_Var) { + node.remove_initializers(); + target.push(node); + return true; + } + if ( + node instanceof AST_Defun + && (node === stat || !compressor.has_directive("use strict")) + ) { + target.push(node === stat ? node : make_node(AST_Var, node, { + definitions: [ + make_node(AST_VarDef, node, { + name: make_node(AST_SymbolVar, node.name, node.name), + value: null + }) + ] + })); + return true; + } + if (node instanceof AST_Export || node instanceof AST_Import) { + target.push(node); + return true; + } + if (node instanceof AST_Scope) { + return true; + } + }); +} + +// Tighten a bunch of statements together, and perform statement-level optimization. +export function tighten_body(statements, compressor) { + var in_loop, in_try; + var scope = compressor.find_parent(AST_Scope).get_defun_scope(); + find_loop_scope_try(); + var CHANGED, max_iter = 10; + do { + CHANGED = false; + eliminate_spurious_blocks(statements); + if (compressor.option("dead_code")) { + eliminate_dead_code(statements, compressor); + } + if (compressor.option("if_return")) { + handle_if_return(statements, compressor); + } + if (compressor.sequences_limit > 0) { + sequencesize(statements, compressor); + sequencesize_2(statements, compressor); + } + if (compressor.option("join_vars")) { + join_consecutive_vars(statements); + } + if (compressor.option("collapse_vars")) { + collapse(statements, compressor); + } + } while (CHANGED && max_iter-- > 0); + + function find_loop_scope_try() { + var node = compressor.self(), level = 0; + do { + if (node instanceof AST_Catch || node instanceof AST_Finally) { + level++; + } else if (node instanceof AST_IterationStatement) { + in_loop = true; + } else if (node instanceof AST_Scope) { + scope = node; + break; + } else if (node instanceof AST_Try) { + in_try = true; + } + } while (node = compressor.parent(level++)); + } + + // Search from right to left for assignment-like expressions: + // - `var a = x;` + // - `a = x;` + // - `++a` + // For each candidate, scan from left to right for first usage, then try + // to fold assignment into the site for compression. + // Will not attempt to collapse assignments into or past code blocks + // which are not sequentially executed, e.g. loops and conditionals. + function collapse(statements, compressor) { + if (scope.pinned()) + return statements; + var args; + var candidates = []; + var stat_index = statements.length; + var scanner = new TreeTransformer(function (node) { + if (abort) + return node; + // Skip nodes before `candidate` as quickly as possible + if (!hit) { + if (node !== hit_stack[hit_index]) + return node; + hit_index++; + if (hit_index < hit_stack.length) + return handle_custom_scan_order(node); + hit = true; + stop_after = find_stop(node, 0); + if (stop_after === node) + abort = true; + return node; + } + // Stop immediately if these node types are encountered + var parent = scanner.parent(); + if (node instanceof AST_Assign + && (node.logical || node.operator != "=" && lhs.equivalent_to(node.left)) + || node instanceof AST_Await + || node instanceof AST_Call && lhs instanceof AST_PropAccess && lhs.equivalent_to(node.expression) + || node instanceof AST_Debugger + || node instanceof AST_Destructuring + || node instanceof AST_Expansion + && node.expression instanceof AST_Symbol + && ( + node.expression instanceof AST_This + || node.expression.definition().references.length > 1 + ) + || node instanceof AST_IterationStatement && !(node instanceof AST_For) + || node instanceof AST_LoopControl + || node instanceof AST_Try + || node instanceof AST_With + || node instanceof AST_Yield + || node instanceof AST_Export + || node instanceof AST_Class + || parent instanceof AST_For && node !== parent.init + || !replace_all + && ( + node instanceof AST_SymbolRef + && !node.is_declared(compressor) + && !pure_prop_access_globals.has(node) + ) + || node instanceof AST_SymbolRef + && parent instanceof AST_Call + && has_annotation(parent, _NOINLINE) + ) { + abort = true; + return node; + } + // Stop only if candidate is found within conditional branches + if (!stop_if_hit && (!lhs_local || !replace_all) + && (parent instanceof AST_Binary && lazy_op.has(parent.operator) && parent.left !== node + || parent instanceof AST_Conditional && parent.condition !== node + || parent instanceof AST_If && parent.condition !== node)) { + stop_if_hit = parent; + } + // Replace variable with assignment when found + if (can_replace + && !(node instanceof AST_SymbolDeclaration) + && lhs.equivalent_to(node) + && !shadows(node.scope, lvalues) + ) { + if (stop_if_hit) { + abort = true; + return node; + } + if (is_lhs(node, parent)) { + if (value_def) + replaced++; + return node; + } else { + replaced++; + if (value_def && candidate instanceof AST_VarDef) + return node; + } + CHANGED = abort = true; + if (candidate instanceof AST_UnaryPostfix) { + return make_node(AST_UnaryPrefix, candidate, candidate); + } + if (candidate instanceof AST_VarDef) { + var def = candidate.name.definition(); + var value = candidate.value; + if (def.references.length - def.replaced == 1 && !compressor.exposed(def)) { + def.replaced++; + if (funarg && is_identifier_atom(value)) { + return value.transform(compressor); + } else { + return maintain_this_binding(parent, node, value); + } + } + return make_node(AST_Assign, candidate, { + operator: "=", + logical: false, + left: make_node(AST_SymbolRef, candidate.name, candidate.name), + right: value + }); + } + clear_flag(candidate, WRITE_ONLY); + return candidate; + } + // These node types have child nodes that execute sequentially, + // but are otherwise not safe to scan into or beyond them. + var sym; + if (node instanceof AST_Call + || node instanceof AST_Exit + && (side_effects || lhs instanceof AST_PropAccess || may_modify(lhs)) + || node instanceof AST_PropAccess + && (side_effects || node.expression.may_throw_on_access(compressor)) + || node instanceof AST_SymbolRef + && ((lvalues.has(node.name) && lvalues.get(node.name).modified) || side_effects && may_modify(node)) + || node instanceof AST_VarDef && node.value + && (lvalues.has(node.name.name) || side_effects && may_modify(node.name)) + || (sym = is_lhs(node.left, node)) + && (sym instanceof AST_PropAccess || lvalues.has(sym.name)) + || may_throw + && (in_try ? node.has_side_effects(compressor) : side_effects_external(node))) { + stop_after = node; + if (node instanceof AST_Scope) + abort = true; + } + return handle_custom_scan_order(node); + }, function (node) { + if (abort) + return; + if (stop_after === node) + abort = true; + if (stop_if_hit === node) + stop_if_hit = null; + }); + + var multi_replacer = new TreeTransformer(function (node) { + if (abort) + return node; + // Skip nodes before `candidate` as quickly as possible + if (!hit) { + if (node !== hit_stack[hit_index]) + return node; + hit_index++; + if (hit_index < hit_stack.length) + return; + hit = true; + return node; + } + // Replace variable when found + if (node instanceof AST_SymbolRef + && node.name == def.name) { + if (!--replaced) + abort = true; + if (is_lhs(node, multi_replacer.parent())) + return node; + def.replaced++; + value_def.replaced--; + return candidate.value; + } + // Skip (non-executed) functions and (leading) default case in switch statements + if (node instanceof AST_Default || node instanceof AST_Scope) + return node; + }); + + while (--stat_index >= 0) { + // Treat parameters as collapsible in IIFE, i.e. + // function(a, b){ ... }(x()); + // would be translated into equivalent assignments: + // var a = x(), b = undefined; + if (stat_index == 0 && compressor.option("unused")) + extract_args(); + // Find collapsible assignments + var hit_stack = []; + extract_candidates(statements[stat_index]); + while (candidates.length > 0) { + hit_stack = candidates.pop(); + var hit_index = 0; + var candidate = hit_stack[hit_stack.length - 1]; + var value_def = null; + var stop_after = null; + var stop_if_hit = null; + var lhs = get_lhs(candidate); + if (!lhs || is_lhs_read_only(lhs) || lhs.has_side_effects(compressor)) + continue; + // Locate symbols which may execute code outside of scanning range + var lvalues = get_lvalues(candidate); + var lhs_local = is_lhs_local(lhs); + if (lhs instanceof AST_SymbolRef) { + lvalues.set(lhs.name, { def: lhs.definition(), modified: false }); + } + var side_effects = value_has_side_effects(candidate); + var replace_all = replace_all_symbols(); + var may_throw = candidate.may_throw(compressor); + var funarg = candidate.name instanceof AST_SymbolFunarg; + var hit = funarg; + var abort = false, replaced = 0, can_replace = !args || !hit; + if (!can_replace) { + for (var j = compressor.self().argnames.lastIndexOf(candidate.name) + 1; !abort && j < args.length; j++) { + args[j].transform(scanner); + } + can_replace = true; + } + for (var i = stat_index; !abort && i < statements.length; i++) { + statements[i].transform(scanner); + } + if (value_def) { + var def = candidate.name.definition(); + if (abort && def.references.length - def.replaced > replaced) + replaced = false; + else { + abort = false; + hit_index = 0; + hit = funarg; + for (var i = stat_index; !abort && i < statements.length; i++) { + statements[i].transform(multi_replacer); + } + value_def.single_use = false; + } + } + if (replaced && !remove_candidate(candidate)) + statements.splice(stat_index, 1); + } + } + + function handle_custom_scan_order(node) { + // Skip (non-executed) functions + if (node instanceof AST_Scope) + return node; + + // Scan case expressions first in a switch statement + if (node instanceof AST_Switch) { + node.expression = node.expression.transform(scanner); + for (var i = 0, len = node.body.length; !abort && i < len; i++) { + var branch = node.body[i]; + if (branch instanceof AST_Case) { + if (!hit) { + if (branch !== hit_stack[hit_index]) + continue; + hit_index++; + } + branch.expression = branch.expression.transform(scanner); + if (!replace_all) + break; + } + } + abort = true; + return node; + } + } + + function redefined_within_scope(def, scope) { + if (def.global) + return false; + let cur_scope = def.scope; + while (cur_scope && cur_scope !== scope) { + if (cur_scope.variables.has(def.name)) { + return true; + } + cur_scope = cur_scope.parent_scope; + } + return false; + } + + function has_overlapping_symbol(fn, arg, fn_strict) { + var found = false, scan_this = !(fn instanceof AST_Arrow); + arg.walk(new TreeWalker(function (node, descend) { + if (found) + return true; + if (node instanceof AST_SymbolRef && (fn.variables.has(node.name) || redefined_within_scope(node.definition(), fn))) { + var s = node.definition().scope; + if (s !== scope) + while (s = s.parent_scope) { + if (s === scope) + return true; + } + return found = true; + } + if ((fn_strict || scan_this) && node instanceof AST_This) { + return found = true; + } + if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) { + var prev = scan_this; + scan_this = false; + descend(); + scan_this = prev; + return true; + } + })); + return found; + } + + function extract_args() { + var iife, fn = compressor.self(); + if (is_func_expr(fn) + && !fn.name + && !fn.uses_arguments + && !fn.pinned() + && (iife = compressor.parent()) instanceof AST_Call + && iife.expression === fn + && iife.args.every((arg) => !(arg instanceof AST_Expansion))) { + var fn_strict = compressor.has_directive("use strict"); + if (fn_strict && !member(fn_strict, fn.body)) + fn_strict = false; + var len = fn.argnames.length; + args = iife.args.slice(len); + var names = new Set(); + for (var i = len; --i >= 0;) { + var sym = fn.argnames[i]; + var arg = iife.args[i]; + // The following two line fix is a duplicate of the fix at + // https://github.com/terser/terser/commit/011d3eb08cefe6922c7d1bdfa113fc4aeaca1b75 + // This might mean that these two pieces of code (one here in collapse_vars and another in reduce_vars + // Might be doing the exact same thing. + const def = sym.definition && sym.definition(); + const is_reassigned = def && def.orig.length > 1; + if (is_reassigned) + continue; + args.unshift(make_node(AST_VarDef, sym, { + name: sym, + value: arg + })); + if (names.has(sym.name)) + continue; + names.add(sym.name); + if (sym instanceof AST_Expansion) { + var elements = iife.args.slice(i); + if (elements.every((arg) => !has_overlapping_symbol(fn, arg, fn_strict) + )) { + candidates.unshift([make_node(AST_VarDef, sym, { + name: sym.expression, + value: make_node(AST_Array, iife, { + elements: elements + }) + })]); + } + } else { + if (!arg) { + arg = make_node(AST_Undefined, sym).transform(compressor); + } else if (arg instanceof AST_Lambda && arg.pinned() + || has_overlapping_symbol(fn, arg, fn_strict)) { + arg = null; + } + if (arg) + candidates.unshift([make_node(AST_VarDef, sym, { + name: sym, + value: arg + })]); + } + } + } + } + + function extract_candidates(expr) { + hit_stack.push(expr); + if (expr instanceof AST_Assign) { + if (!expr.left.has_side_effects(compressor) + && !(expr.right instanceof AST_Chain)) { + candidates.push(hit_stack.slice()); + } + extract_candidates(expr.right); + } else if (expr instanceof AST_Binary) { + extract_candidates(expr.left); + extract_candidates(expr.right); + } else if (expr instanceof AST_Call && !has_annotation(expr, _NOINLINE)) { + extract_candidates(expr.expression); + expr.args.forEach(extract_candidates); + } else if (expr instanceof AST_Case) { + extract_candidates(expr.expression); + } else if (expr instanceof AST_Conditional) { + extract_candidates(expr.condition); + extract_candidates(expr.consequent); + extract_candidates(expr.alternative); + } else if (expr instanceof AST_Definitions) { + var len = expr.definitions.length; + // limit number of trailing variable definitions for consideration + var i = len - 200; + if (i < 0) + i = 0; + for (; i < len; i++) { + extract_candidates(expr.definitions[i]); + } + } else if (expr instanceof AST_DWLoop) { + extract_candidates(expr.condition); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_Exit) { + if (expr.value) + extract_candidates(expr.value); + } else if (expr instanceof AST_For) { + if (expr.init) + extract_candidates(expr.init); + if (expr.condition) + extract_candidates(expr.condition); + if (expr.step) + extract_candidates(expr.step); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_ForIn) { + extract_candidates(expr.object); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_If) { + extract_candidates(expr.condition); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + if (expr.alternative && !(expr.alternative instanceof AST_Block)) { + extract_candidates(expr.alternative); + } + } else if (expr instanceof AST_Sequence) { + expr.expressions.forEach(extract_candidates); + } else if (expr instanceof AST_SimpleStatement) { + extract_candidates(expr.body); + } else if (expr instanceof AST_Switch) { + extract_candidates(expr.expression); + expr.body.forEach(extract_candidates); + } else if (expr instanceof AST_Unary) { + if (expr.operator == "++" || expr.operator == "--") { + candidates.push(hit_stack.slice()); + } + } else if (expr instanceof AST_VarDef) { + if (expr.value && !(expr.value instanceof AST_Chain)) { + candidates.push(hit_stack.slice()); + extract_candidates(expr.value); + } + } + hit_stack.pop(); + } + + function find_stop(node, level, write_only) { + var parent = scanner.parent(level); + if (parent instanceof AST_Assign) { + if (write_only + && !parent.logical + && !(parent.left instanceof AST_PropAccess + || lvalues.has(parent.left.name))) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_Binary) { + if (write_only && (!lazy_op.has(parent.operator) || parent.left === node)) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_Call) + return node; + if (parent instanceof AST_Case) + return node; + if (parent instanceof AST_Conditional) { + if (write_only && parent.condition === node) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_Definitions) { + return find_stop(parent, level + 1, true); + } + if (parent instanceof AST_Exit) { + return write_only ? find_stop(parent, level + 1, write_only) : node; + } + if (parent instanceof AST_If) { + if (write_only && parent.condition === node) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_IterationStatement) + return node; + if (parent instanceof AST_Sequence) { + return find_stop(parent, level + 1, parent.tail_node() !== node); + } + if (parent instanceof AST_SimpleStatement) { + return find_stop(parent, level + 1, true); + } + if (parent instanceof AST_Switch) + return node; + if (parent instanceof AST_VarDef) + return node; + return null; + } + + function mangleable_var(var_def) { + var value = var_def.value; + if (!(value instanceof AST_SymbolRef)) + return; + if (value.name == "arguments") + return; + var def = value.definition(); + if (def.undeclared) + return; + return value_def = def; + } + + function get_lhs(expr) { + if (expr instanceof AST_Assign && expr.logical) { + return false; + } else if (expr instanceof AST_VarDef && expr.name instanceof AST_SymbolDeclaration) { + var def = expr.name.definition(); + if (!member(expr.name, def.orig)) + return; + var referenced = def.references.length - def.replaced; + if (!referenced) + return; + var declared = def.orig.length - def.eliminated; + if (declared > 1 && !(expr.name instanceof AST_SymbolFunarg) + || (referenced > 1 ? mangleable_var(expr) : !compressor.exposed(def))) { + return make_node(AST_SymbolRef, expr.name, expr.name); + } + } else { + const lhs = expr instanceof AST_Assign + ? expr.left + : expr.expression; + return !is_ref_of(lhs, AST_SymbolConst) + && !is_ref_of(lhs, AST_SymbolLet) && lhs; + } + } + + function get_rvalue(expr) { + if (expr instanceof AST_Assign) { + return expr.right; + } else { + return expr.value; + } + } + + function get_lvalues(expr) { + var lvalues = new Map(); + if (expr instanceof AST_Unary) + return lvalues; + var tw = new TreeWalker(function (node) { + var sym = node; + while (sym instanceof AST_PropAccess) + sym = sym.expression; + if (sym instanceof AST_SymbolRef) { + const prev = lvalues.get(sym.name); + if (!prev || !prev.modified) { + lvalues.set(sym.name, { + def: sym.definition(), + modified: is_modified(compressor, tw, node, node, 0) + }); + } + } + }); + get_rvalue(expr).walk(tw); + return lvalues; + } + + function remove_candidate(expr) { + if (expr.name instanceof AST_SymbolFunarg) { + var iife = compressor.parent(), argnames = compressor.self().argnames; + var index = argnames.indexOf(expr.name); + if (index < 0) { + iife.args.length = Math.min(iife.args.length, argnames.length - 1); + } else { + var args = iife.args; + if (args[index]) + args[index] = make_node(AST_Number, args[index], { + value: 0 + }); + } + return true; + } + var found = false; + return statements[stat_index].transform(new TreeTransformer(function (node, descend, in_list) { + if (found) + return node; + if (node === expr || node.body === expr) { + found = true; + if (node instanceof AST_VarDef) { + node.value = node.name instanceof AST_SymbolConst + ? make_node(AST_Undefined, node.value) // `const` always needs value. + : null; + return node; + } + return in_list ? MAP.skip : null; + } + }, function (node) { + if (node instanceof AST_Sequence) + switch (node.expressions.length) { + case 0: return null; + case 1: return node.expressions[0]; + } + })); + } + + function is_lhs_local(lhs) { + while (lhs instanceof AST_PropAccess) + lhs = lhs.expression; + return lhs instanceof AST_SymbolRef + && lhs.definition().scope === scope + && !(in_loop + && (lvalues.has(lhs.name) + || candidate instanceof AST_Unary + || (candidate instanceof AST_Assign + && !candidate.logical + && candidate.operator != "="))); + } + + function value_has_side_effects(expr) { + if (expr instanceof AST_Unary) + return unary_side_effects.has(expr.operator); + return get_rvalue(expr).has_side_effects(compressor); + } + + function replace_all_symbols() { + if (side_effects) + return false; + if (value_def) + return true; + if (lhs instanceof AST_SymbolRef) { + var def = lhs.definition(); + if (def.references.length - def.replaced == (candidate instanceof AST_VarDef ? 1 : 2)) { + return true; + } + } + return false; + } + + function may_modify(sym) { + if (!sym.definition) + return true; // AST_Destructuring + var def = sym.definition(); + if (def.orig.length == 1 && def.orig[0] instanceof AST_SymbolDefun) + return false; + if (def.scope.get_defun_scope() !== scope) + return true; + return !def.references.every((ref) => { + var s = ref.scope.get_defun_scope(); + // "block" scope within AST_Catch + if (s.TYPE == "Scope") + s = s.parent_scope; + return s === scope; + }); + } + + function side_effects_external(node, lhs) { + if (node instanceof AST_Assign) + return side_effects_external(node.left, true); + if (node instanceof AST_Unary) + return side_effects_external(node.expression, true); + if (node instanceof AST_VarDef) + return node.value && side_effects_external(node.value); + if (lhs) { + if (node instanceof AST_Dot) + return side_effects_external(node.expression, true); + if (node instanceof AST_Sub) + return side_effects_external(node.expression, true); + if (node instanceof AST_SymbolRef) + return node.definition().scope !== scope; + } + return false; + } + + function shadows(newScope, lvalues) { + for (const {def} of lvalues.values()) { + let current = newScope; + while (current && current !== def.scope) { + let nested_def = current.variables.get(def.name); + if (nested_def && nested_def !== def) return true; + current = current.parent_scope; + } + } + return false; + } + } + + function eliminate_spurious_blocks(statements) { + var seen_dirs = []; + for (var i = 0; i < statements.length;) { + var stat = statements[i]; + if (stat instanceof AST_BlockStatement && stat.body.every(can_be_evicted_from_block)) { + CHANGED = true; + eliminate_spurious_blocks(stat.body); + statements.splice(i, 1, ...stat.body); + i += stat.body.length; + } else if (stat instanceof AST_EmptyStatement) { + CHANGED = true; + statements.splice(i, 1); + } else if (stat instanceof AST_Directive) { + if (seen_dirs.indexOf(stat.value) < 0) { + i++; + seen_dirs.push(stat.value); + } else { + CHANGED = true; + statements.splice(i, 1); + } + } else + i++; + } + } + + function handle_if_return(statements, compressor) { + var self = compressor.self(); + var multiple_if_returns = has_multiple_if_returns(statements); + var in_lambda = self instanceof AST_Lambda; + for (var i = statements.length; --i >= 0;) { + var stat = statements[i]; + var j = next_index(i); + var next = statements[j]; + + if (in_lambda && !next && stat instanceof AST_Return) { + if (!stat.value) { + CHANGED = true; + statements.splice(i, 1); + continue; + } + if (stat.value instanceof AST_UnaryPrefix && stat.value.operator == "void") { + CHANGED = true; + statements[i] = make_node(AST_SimpleStatement, stat, { + body: stat.value.expression + }); + continue; + } + } + + if (stat instanceof AST_If) { + var ab = aborts(stat.body); + if (can_merge_flow(ab)) { + if (ab.label) { + remove(ab.label.thedef.references, ab); + } + CHANGED = true; + stat = stat.clone(); + stat.condition = stat.condition.negate(compressor); + var body = as_statement_array_with_return(stat.body, ab); + stat.body = make_node(AST_BlockStatement, stat, { + body: as_statement_array(stat.alternative).concat(extract_functions()) + }); + stat.alternative = make_node(AST_BlockStatement, stat, { + body: body + }); + statements[i] = stat.transform(compressor); + continue; + } + + var ab = aborts(stat.alternative); + if (can_merge_flow(ab)) { + if (ab.label) { + remove(ab.label.thedef.references, ab); + } + CHANGED = true; + stat = stat.clone(); + stat.body = make_node(AST_BlockStatement, stat.body, { + body: as_statement_array(stat.body).concat(extract_functions()) + }); + var body = as_statement_array_with_return(stat.alternative, ab); + stat.alternative = make_node(AST_BlockStatement, stat.alternative, { + body: body + }); + statements[i] = stat.transform(compressor); + continue; + } + } + + if (stat instanceof AST_If && stat.body instanceof AST_Return) { + var value = stat.body.value; + //--- + // pretty silly case, but: + // if (foo()) return; return; ==> foo(); return; + if (!value && !stat.alternative + && (in_lambda && !next || next instanceof AST_Return && !next.value)) { + CHANGED = true; + statements[i] = make_node(AST_SimpleStatement, stat.condition, { + body: stat.condition + }); + continue; + } + //--- + // if (foo()) return x; return y; ==> return foo() ? x : y; + if (value && !stat.alternative && next instanceof AST_Return && next.value) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = next; + statements[i] = stat.transform(compressor); + statements.splice(j, 1); + continue; + } + //--- + // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined; + if (value && !stat.alternative + && (!next && in_lambda && multiple_if_returns + || next instanceof AST_Return)) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = next || make_node(AST_Return, stat, { + value: null + }); + statements[i] = stat.transform(compressor); + if (next) + statements.splice(j, 1); + continue; + } + //--- + // if (a) return b; if (c) return d; e; ==> return a ? b : c ? d : void e; + // + // if sequences is not enabled, this can lead to an endless loop (issue #866). + // however, with sequences on this helps producing slightly better output for + // the example code. + var prev = statements[prev_index(i)]; + if (compressor.option("sequences") && in_lambda && !stat.alternative + && prev instanceof AST_If && prev.body instanceof AST_Return + && next_index(j) == statements.length && next instanceof AST_SimpleStatement) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = make_node(AST_BlockStatement, next, { + body: [ + next, + make_node(AST_Return, next, { + value: null + }) + ] + }); + statements[i] = stat.transform(compressor); + statements.splice(j, 1); + continue; + } + } + } + + function has_multiple_if_returns(statements) { + var n = 0; + for (var i = statements.length; --i >= 0;) { + var stat = statements[i]; + if (stat instanceof AST_If && stat.body instanceof AST_Return) { + if (++n > 1) + return true; + } + } + return false; + } + + function is_return_void(value) { + return !value || value instanceof AST_UnaryPrefix && value.operator == "void"; + } + + function can_merge_flow(ab) { + if (!ab) + return false; + for (var j = i + 1, len = statements.length; j < len; j++) { + var stat = statements[j]; + if (stat instanceof AST_Const || stat instanceof AST_Let) + return false; + } + var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null; + return ab instanceof AST_Return && in_lambda && is_return_void(ab.value) + || ab instanceof AST_Continue && self === loop_body(lct) + || ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct; + } + + function extract_functions() { + var tail = statements.slice(i + 1); + statements.length = i + 1; + return tail.filter(function (stat) { + if (stat instanceof AST_Defun) { + statements.push(stat); + return false; + } + return true; + }); + } + + function as_statement_array_with_return(node, ab) { + var body = as_statement_array(node).slice(0, -1); + if (ab.value) { + body.push(make_node(AST_SimpleStatement, ab.value, { + body: ab.value.expression + })); + } + return body; + } + + function next_index(i) { + for (var j = i + 1, len = statements.length; j < len; j++) { + var stat = statements[j]; + if (!(stat instanceof AST_Var && declarations_only(stat))) { + break; + } + } + return j; + } + + function prev_index(i) { + for (var j = i; --j >= 0;) { + var stat = statements[j]; + if (!(stat instanceof AST_Var && declarations_only(stat))) { + break; + } + } + return j; + } + } + + function eliminate_dead_code(statements, compressor) { + var has_quit; + var self = compressor.self(); + for (var i = 0, n = 0, len = statements.length; i < len; i++) { + var stat = statements[i]; + if (stat instanceof AST_LoopControl) { + var lct = compressor.loopcontrol_target(stat); + if (stat instanceof AST_Break + && !(lct instanceof AST_IterationStatement) + && loop_body(lct) === self + || stat instanceof AST_Continue + && loop_body(lct) === self) { + if (stat.label) { + remove(stat.label.thedef.references, stat); + } + } else { + statements[n++] = stat; + } + } else { + statements[n++] = stat; + } + if (aborts(stat)) { + has_quit = statements.slice(i + 1); + break; + } + } + statements.length = n; + CHANGED = n != len; + if (has_quit) + has_quit.forEach(function (stat) { + trim_unreachable_code(compressor, stat, statements); + }); + } + + function declarations_only(node) { + return node.definitions.every((var_def) => !var_def.value + ); + } + + function sequencesize(statements, compressor) { + if (statements.length < 2) + return; + var seq = [], n = 0; + function push_seq() { + if (!seq.length) + return; + var body = make_sequence(seq[0], seq); + statements[n++] = make_node(AST_SimpleStatement, body, { body: body }); + seq = []; + } + for (var i = 0, len = statements.length; i < len; i++) { + var stat = statements[i]; + if (stat instanceof AST_SimpleStatement) { + if (seq.length >= compressor.sequences_limit) + push_seq(); + var body = stat.body; + if (seq.length > 0) + body = body.drop_side_effect_free(compressor); + if (body) + merge_sequence(seq, body); + } else if (stat instanceof AST_Definitions && declarations_only(stat) + || stat instanceof AST_Defun) { + statements[n++] = stat; + } else { + push_seq(); + statements[n++] = stat; + } + } + push_seq(); + statements.length = n; + if (n != len) + CHANGED = true; + } + + function to_simple_statement(block, decls) { + if (!(block instanceof AST_BlockStatement)) + return block; + var stat = null; + for (var i = 0, len = block.body.length; i < len; i++) { + var line = block.body[i]; + if (line instanceof AST_Var && declarations_only(line)) { + decls.push(line); + } else if (stat) { + return false; + } else { + stat = line; + } + } + return stat; + } + + function sequencesize_2(statements, compressor) { + function cons_seq(right) { + n--; + CHANGED = true; + var left = prev.body; + return make_sequence(left, [left, right]).transform(compressor); + } + var n = 0, prev; + for (var i = 0; i < statements.length; i++) { + var stat = statements[i]; + if (prev) { + if (stat instanceof AST_Exit) { + stat.value = cons_seq(stat.value || make_node(AST_Undefined, stat).transform(compressor)); + } else if (stat instanceof AST_For) { + if (!(stat.init instanceof AST_Definitions)) { + const abort = walk(prev.body, node => { + if (node instanceof AST_Scope) + return true; + if (node instanceof AST_Binary + && node.operator === "in") { + return walk_abort; + } + }); + if (!abort) { + if (stat.init) + stat.init = cons_seq(stat.init); + else { + stat.init = prev.body; + n--; + CHANGED = true; + } + } + } + } else if (stat instanceof AST_ForIn) { + if (!(stat.init instanceof AST_Const) && !(stat.init instanceof AST_Let)) { + stat.object = cons_seq(stat.object); + } + } else if (stat instanceof AST_If) { + stat.condition = cons_seq(stat.condition); + } else if (stat instanceof AST_Switch) { + stat.expression = cons_seq(stat.expression); + } else if (stat instanceof AST_With) { + stat.expression = cons_seq(stat.expression); + } + } + if (compressor.option("conditionals") && stat instanceof AST_If) { + var decls = []; + var body = to_simple_statement(stat.body, decls); + var alt = to_simple_statement(stat.alternative, decls); + if (body !== false && alt !== false && decls.length > 0) { + var len = decls.length; + decls.push(make_node(AST_If, stat, { + condition: stat.condition, + body: body || make_node(AST_EmptyStatement, stat.body), + alternative: alt + })); + decls.unshift(n, 1); + [].splice.apply(statements, decls); + i += len; + n += len + 1; + prev = null; + CHANGED = true; + continue; + } + } + statements[n++] = stat; + prev = stat instanceof AST_SimpleStatement ? stat : null; + } + statements.length = n; + } + + function join_object_assignments(defn, body) { + if (!(defn instanceof AST_Definitions)) + return; + var def = defn.definitions[defn.definitions.length - 1]; + if (!(def.value instanceof AST_Object)) + return; + var exprs; + if (body instanceof AST_Assign && !body.logical) { + exprs = [body]; + } else if (body instanceof AST_Sequence) { + exprs = body.expressions.slice(); + } + if (!exprs) + return; + var trimmed = false; + do { + var node = exprs[0]; + if (!(node instanceof AST_Assign)) + break; + if (node.operator != "=") + break; + if (!(node.left instanceof AST_PropAccess)) + break; + var sym = node.left.expression; + if (!(sym instanceof AST_SymbolRef)) + break; + if (def.name.name != sym.name) + break; + if (!node.right.is_constant_expression(scope)) + break; + var prop = node.left.property; + if (prop instanceof AST_Node) { + prop = prop.evaluate(compressor); + } + if (prop instanceof AST_Node) + break; + prop = "" + prop; + var diff = compressor.option("ecma") < 2015 + && compressor.has_directive("use strict") ? function (node) { + return node.key != prop && (node.key && node.key.name != prop); + } : function (node) { + return node.key && node.key.name != prop; + }; + if (!def.value.properties.every(diff)) + break; + var p = def.value.properties.filter(function (p) { return p.key === prop; })[0]; + if (!p) { + def.value.properties.push(make_node(AST_ObjectKeyVal, node, { + key: prop, + value: node.right + })); + } else { + p.value = new AST_Sequence({ + start: p.start, + expressions: [p.value.clone(), node.right.clone()], + end: p.end + }); + } + exprs.shift(); + trimmed = true; + } while (exprs.length); + return trimmed && exprs; + } + + function join_consecutive_vars(statements) { + var defs; + for (var i = 0, j = -1, len = statements.length; i < len; i++) { + var stat = statements[i]; + var prev = statements[j]; + if (stat instanceof AST_Definitions) { + if (prev && prev.TYPE == stat.TYPE) { + prev.definitions = prev.definitions.concat(stat.definitions); + CHANGED = true; + } else if (defs && defs.TYPE == stat.TYPE && declarations_only(stat)) { + defs.definitions = defs.definitions.concat(stat.definitions); + CHANGED = true; + } else { + statements[++j] = stat; + defs = stat; + } + } else if (stat instanceof AST_Exit) { + stat.value = extract_object_assignments(stat.value); + } else if (stat instanceof AST_For) { + var exprs = join_object_assignments(prev, stat.init); + if (exprs) { + CHANGED = true; + stat.init = exprs.length ? make_sequence(stat.init, exprs) : null; + statements[++j] = stat; + } else if (prev instanceof AST_Var && (!stat.init || stat.init.TYPE == prev.TYPE)) { + if (stat.init) { + prev.definitions = prev.definitions.concat(stat.init.definitions); + } + stat.init = prev; + statements[j] = stat; + CHANGED = true; + } else if (defs && stat.init && defs.TYPE == stat.init.TYPE && declarations_only(stat.init)) { + defs.definitions = defs.definitions.concat(stat.init.definitions); + stat.init = null; + statements[++j] = stat; + CHANGED = true; + } else { + statements[++j] = stat; + } + } else if (stat instanceof AST_ForIn) { + stat.object = extract_object_assignments(stat.object); + } else if (stat instanceof AST_If) { + stat.condition = extract_object_assignments(stat.condition); + } else if (stat instanceof AST_SimpleStatement) { + var exprs = join_object_assignments(prev, stat.body); + if (exprs) { + CHANGED = true; + if (!exprs.length) + continue; + stat.body = make_sequence(stat.body, exprs); + } + statements[++j] = stat; + } else if (stat instanceof AST_Switch) { + stat.expression = extract_object_assignments(stat.expression); + } else if (stat instanceof AST_With) { + stat.expression = extract_object_assignments(stat.expression); + } else { + statements[++j] = stat; + } + } + statements.length = j + 1; + + function extract_object_assignments(value) { + statements[++j] = stat; + var exprs = join_object_assignments(prev, value); + if (exprs) { + CHANGED = true; + if (exprs.length) { + return make_sequence(value, exprs); + } else if (value instanceof AST_Sequence) { + return value.tail_node().left; + } else { + return value.left; + } + } + return value; + } + } +} diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/equivalent-to.js b/node_modules/mathjs/examples/node_modules/terser/lib/equivalent-to.js new file mode 100644 index 0000000..0597621 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/equivalent-to.js @@ -0,0 +1,313 @@ +import { + AST_Array, + AST_Atom, + AST_Await, + AST_BigInt, + AST_Binary, + AST_Block, + AST_Call, + AST_Catch, + AST_Chain, + AST_Class, + AST_ClassProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Debugger, + AST_Definitions, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DotHash, + AST_EmptyStatement, + AST_Expansion, + AST_Export, + AST_Finally, + AST_For, + AST_ForIn, + AST_ForOf, + AST_If, + AST_Import, + AST_ImportMeta, + AST_Jump, + AST_LabeledStatement, + AST_Lambda, + AST_LoopControl, + AST_NameMapping, + AST_NewTarget, + AST_Node, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PrefixedTemplateString, + AST_PropAccess, + AST_RegExp, + AST_Sequence, + AST_SimpleStatement, + AST_String, + AST_Super, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Toplevel, + AST_Try, + AST_Unary, + AST_VarDef, + AST_While, + AST_With, + AST_Yield +} from "./ast.js"; + +const shallow_cmp = (node1, node2) => { + return ( + node1 === null && node2 === null + || node1.TYPE === node2.TYPE && node1.shallow_cmp(node2) + ); +}; + +export const equivalent_to = (tree1, tree2) => { + if (!shallow_cmp(tree1, tree2)) return false; + const walk_1_state = [tree1]; + const walk_2_state = [tree2]; + + const walk_1_push = walk_1_state.push.bind(walk_1_state); + const walk_2_push = walk_2_state.push.bind(walk_2_state); + + while (walk_1_state.length && walk_2_state.length) { + const node_1 = walk_1_state.pop(); + const node_2 = walk_2_state.pop(); + + if (!shallow_cmp(node_1, node_2)) return false; + + node_1._children_backwards(walk_1_push); + node_2._children_backwards(walk_2_push); + + if (walk_1_state.length !== walk_2_state.length) { + // Different number of children + return false; + } + } + + return walk_1_state.length == 0 && walk_2_state.length == 0; +}; + +// Creates a shallow compare function +const mkshallow = (props) => { + const comparisons = Object + .keys(props) + .map(key => { + if (props[key] === "eq") { + return `this.${key} === other.${key}`; + } else if (props[key] === "exist") { + return `(this.${key} == null ? other.${key} == null : this.${key} === other.${key})`; + } else { + throw new Error(`mkshallow: Unexpected instruction: ${props[key]}`); + } + }) + .join(" && "); + + return new Function("other", "return " + comparisons); +}; + +const pass_through = () => true; + +AST_Node.prototype.shallow_cmp = function () { + throw new Error("did not find a shallow_cmp function for " + this.constructor.name); +}; + +AST_Debugger.prototype.shallow_cmp = pass_through; + +AST_Directive.prototype.shallow_cmp = mkshallow({ value: "eq" }); + +AST_SimpleStatement.prototype.shallow_cmp = pass_through; + +AST_Block.prototype.shallow_cmp = pass_through; + +AST_EmptyStatement.prototype.shallow_cmp = pass_through; + +AST_LabeledStatement.prototype.shallow_cmp = mkshallow({ "label.name": "eq" }); + +AST_Do.prototype.shallow_cmp = pass_through; + +AST_While.prototype.shallow_cmp = pass_through; + +AST_For.prototype.shallow_cmp = mkshallow({ + init: "exist", + condition: "exist", + step: "exist" +}); + +AST_ForIn.prototype.shallow_cmp = pass_through; + +AST_ForOf.prototype.shallow_cmp = pass_through; + +AST_With.prototype.shallow_cmp = pass_through; + +AST_Toplevel.prototype.shallow_cmp = pass_through; + +AST_Expansion.prototype.shallow_cmp = pass_through; + +AST_Lambda.prototype.shallow_cmp = mkshallow({ + is_generator: "eq", + async: "eq" +}); + +AST_Destructuring.prototype.shallow_cmp = mkshallow({ + is_array: "eq" +}); + +AST_PrefixedTemplateString.prototype.shallow_cmp = pass_through; + +AST_TemplateString.prototype.shallow_cmp = pass_through; + +AST_TemplateSegment.prototype.shallow_cmp = mkshallow({ + "value": "eq" +}); + +AST_Jump.prototype.shallow_cmp = pass_through; + +AST_LoopControl.prototype.shallow_cmp = pass_through; + +AST_Await.prototype.shallow_cmp = pass_through; + +AST_Yield.prototype.shallow_cmp = mkshallow({ + is_star: "eq" +}); + +AST_If.prototype.shallow_cmp = mkshallow({ + alternative: "exist" +}); + +AST_Switch.prototype.shallow_cmp = pass_through; + +AST_SwitchBranch.prototype.shallow_cmp = pass_through; + +AST_Try.prototype.shallow_cmp = mkshallow({ + bcatch: "exist", + bfinally: "exist" +}); + +AST_Catch.prototype.shallow_cmp = mkshallow({ + argname: "exist" +}); + +AST_Finally.prototype.shallow_cmp = pass_through; + +AST_Definitions.prototype.shallow_cmp = pass_through; + +AST_VarDef.prototype.shallow_cmp = mkshallow({ + value: "exist" +}); + +AST_NameMapping.prototype.shallow_cmp = pass_through; + +AST_Import.prototype.shallow_cmp = mkshallow({ + imported_name: "exist", + imported_names: "exist" +}); + +AST_ImportMeta.prototype.shallow_cmp = pass_through; + +AST_Export.prototype.shallow_cmp = mkshallow({ + exported_definition: "exist", + exported_value: "exist", + exported_names: "exist", + module_name: "eq", + is_default: "eq", +}); + +AST_Call.prototype.shallow_cmp = pass_through; + +AST_Sequence.prototype.shallow_cmp = pass_through; + +AST_PropAccess.prototype.shallow_cmp = pass_through; + +AST_Chain.prototype.shallow_cmp = pass_through; + +AST_Dot.prototype.shallow_cmp = mkshallow({ + property: "eq" +}); + +AST_DotHash.prototype.shallow_cmp = mkshallow({ + property: "eq" +}); + +AST_Unary.prototype.shallow_cmp = mkshallow({ + operator: "eq" +}); + +AST_Binary.prototype.shallow_cmp = mkshallow({ + operator: "eq" +}); + +AST_Conditional.prototype.shallow_cmp = pass_through; + +AST_Array.prototype.shallow_cmp = pass_through; + +AST_Object.prototype.shallow_cmp = pass_through; + +AST_ObjectProperty.prototype.shallow_cmp = pass_through; + +AST_ObjectKeyVal.prototype.shallow_cmp = mkshallow({ + key: "eq" +}); + +AST_ObjectSetter.prototype.shallow_cmp = mkshallow({ + static: "eq" +}); + +AST_ObjectGetter.prototype.shallow_cmp = mkshallow({ + static: "eq" +}); + +AST_ConciseMethod.prototype.shallow_cmp = mkshallow({ + static: "eq", + is_generator: "eq", + async: "eq", +}); + +AST_Class.prototype.shallow_cmp = mkshallow({ + name: "exist", + extends: "exist", +}); + +AST_ClassProperty.prototype.shallow_cmp = mkshallow({ + static: "eq" +}); + +AST_Symbol.prototype.shallow_cmp = mkshallow({ + name: "eq" +}); + +AST_NewTarget.prototype.shallow_cmp = pass_through; + +AST_This.prototype.shallow_cmp = pass_through; + +AST_Super.prototype.shallow_cmp = pass_through; + +AST_String.prototype.shallow_cmp = mkshallow({ + value: "eq" +}); + +AST_Number.prototype.shallow_cmp = mkshallow({ + value: "eq" +}); + +AST_BigInt.prototype.shallow_cmp = mkshallow({ + value: "eq" +}); + +AST_RegExp.prototype.shallow_cmp = function (other) { + return ( + this.value.flags === other.value.flags + && this.value.source === other.value.source + ); +}; + +AST_Atom.prototype.shallow_cmp = pass_through; diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/minify.js b/node_modules/mathjs/examples/node_modules/terser/lib/minify.js new file mode 100644 index 0000000..82d9ca3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/minify.js @@ -0,0 +1,335 @@ +"use strict"; +/* eslint-env browser, es6, node */ + +import { + defaults, + map_from_object, + map_to_object, + HOP, +} from "./utils/index.js"; +import { AST_Toplevel, AST_Node } from "./ast.js"; +import { parse } from "./parse.js"; +import { OutputStream } from "./output.js"; +import { Compressor } from "./compress/index.js"; +import { base54 } from "./scope.js"; +import { SourceMap } from "./sourcemap.js"; +import { + mangle_properties, + mangle_private_properties, + reserve_quoted_keys, +} from "./propmangle.js"; + +var to_ascii = typeof atob == "undefined" ? function(b64) { + return Buffer.from(b64, "base64").toString(); +} : atob; +var to_base64 = typeof btoa == "undefined" ? function(str) { + return Buffer.from(str).toString("base64"); +} : btoa; + +function read_source_map(code) { + var match = /(?:^|[^.])\/\/# sourceMappingURL=data:application\/json(;[\w=-]*)?;base64,([+/0-9A-Za-z]*=*)\s*$/.exec(code); + if (!match) { + console.warn("inline source map not found"); + return null; + } + return to_ascii(match[2]); +} + +function set_shorthand(name, options, keys) { + if (options[name]) { + keys.forEach(function(key) { + if (options[key]) { + if (typeof options[key] != "object") options[key] = {}; + if (!(name in options[key])) options[key][name] = options[name]; + } + }); + } +} + +function init_cache(cache) { + if (!cache) return; + if (!("props" in cache)) { + cache.props = new Map(); + } else if (!(cache.props instanceof Map)) { + cache.props = map_from_object(cache.props); + } +} + +function cache_to_json(cache) { + return { + props: map_to_object(cache.props) + }; +} + +function log_input(files, options, fs, debug_folder) { + if (!(fs && fs.writeFileSync && fs.mkdirSync)) { + return; + } + + try { + fs.mkdirSync(debug_folder); + } catch (e) { + if (e.code !== "EEXIST") throw e; + } + + const log_path = `${debug_folder}/terser-debug-${(Math.random() * 9999999) | 0}.log`; + + options = options || {}; + + const options_str = JSON.stringify(options, (_key, thing) => { + if (typeof thing === "function") return "[Function " + thing.toString() + "]"; + if (thing instanceof RegExp) return "[RegExp " + thing.toString() + "]"; + return thing; + }, 4); + + const files_str = (file) => { + if (typeof file === "object" && options.parse && options.parse.spidermonkey) { + return JSON.stringify(file, null, 2); + } else if (typeof file === "object") { + return Object.keys(file) + .map((key) => key + ": " + files_str(file[key])) + .join("\n\n"); + } else if (typeof file === "string") { + return "```\n" + file + "\n```"; + } else { + return file; // What do? + } + }; + + fs.writeFileSync(log_path, "Options: \n" + options_str + "\n\nInput files:\n\n" + files_str(files) + "\n"); +} + +async function minify(files, options, _fs_module) { + if ( + _fs_module + && typeof process === "object" + && process.env + && typeof process.env.TERSER_DEBUG_DIR === "string" + ) { + log_input(files, options, _fs_module, process.env.TERSER_DEBUG_DIR); + } + + options = defaults(options, { + compress: {}, + ecma: undefined, + enclose: false, + ie8: false, + keep_classnames: undefined, + keep_fnames: false, + mangle: {}, + module: false, + nameCache: null, + output: null, + format: null, + parse: {}, + rename: undefined, + safari10: false, + sourceMap: false, + spidermonkey: false, + timings: false, + toplevel: false, + warnings: false, + wrap: false, + }, true); + + var timings = options.timings && { + start: Date.now() + }; + if (options.keep_classnames === undefined) { + options.keep_classnames = options.keep_fnames; + } + if (options.rename === undefined) { + options.rename = options.compress && options.mangle; + } + if (options.output && options.format) { + throw new Error("Please only specify either output or format option, preferrably format."); + } + options.format = options.format || options.output || {}; + set_shorthand("ecma", options, [ "parse", "compress", "format" ]); + set_shorthand("ie8", options, [ "compress", "mangle", "format" ]); + set_shorthand("keep_classnames", options, [ "compress", "mangle" ]); + set_shorthand("keep_fnames", options, [ "compress", "mangle" ]); + set_shorthand("module", options, [ "parse", "compress", "mangle" ]); + set_shorthand("safari10", options, [ "mangle", "format" ]); + set_shorthand("toplevel", options, [ "compress", "mangle" ]); + set_shorthand("warnings", options, [ "compress" ]); // legacy + var quoted_props; + if (options.mangle) { + options.mangle = defaults(options.mangle, { + cache: options.nameCache && (options.nameCache.vars || {}), + eval: false, + ie8: false, + keep_classnames: false, + keep_fnames: false, + module: false, + nth_identifier: base54, + properties: false, + reserved: [], + safari10: false, + toplevel: false, + }, true); + if (options.mangle.properties) { + if (typeof options.mangle.properties != "object") { + options.mangle.properties = {}; + } + if (options.mangle.properties.keep_quoted) { + quoted_props = options.mangle.properties.reserved; + if (!Array.isArray(quoted_props)) quoted_props = []; + options.mangle.properties.reserved = quoted_props; + } + if (options.nameCache && !("cache" in options.mangle.properties)) { + options.mangle.properties.cache = options.nameCache.props || {}; + } + } + init_cache(options.mangle.cache); + init_cache(options.mangle.properties.cache); + } + if (options.sourceMap) { + options.sourceMap = defaults(options.sourceMap, { + asObject: false, + content: null, + filename: null, + includeSources: false, + root: null, + url: null, + }, true); + } + if (timings) timings.parse = Date.now(); + var toplevel; + if (files instanceof AST_Toplevel) { + toplevel = files; + } else { + if (typeof files == "string" || (options.parse.spidermonkey && !Array.isArray(files))) { + files = [ files ]; + } + options.parse = options.parse || {}; + options.parse.toplevel = null; + + if (options.parse.spidermonkey) { + options.parse.toplevel = AST_Node.from_mozilla_ast(Object.keys(files).reduce(function(toplevel, name) { + if (!toplevel) return files[name]; + toplevel.body = toplevel.body.concat(files[name].body); + return toplevel; + }, null)); + } else { + delete options.parse.spidermonkey; + + for (var name in files) if (HOP(files, name)) { + options.parse.filename = name; + options.parse.toplevel = parse(files[name], options.parse); + if (options.sourceMap && options.sourceMap.content == "inline") { + if (Object.keys(files).length > 1) + throw new Error("inline source map only works with singular input"); + options.sourceMap.content = read_source_map(files[name]); + } + } + } + + toplevel = options.parse.toplevel; + } + if (quoted_props && options.mangle.properties.keep_quoted !== "strict") { + reserve_quoted_keys(toplevel, quoted_props); + } + if (options.wrap) { + toplevel = toplevel.wrap_commonjs(options.wrap); + } + if (options.enclose) { + toplevel = toplevel.wrap_enclose(options.enclose); + } + if (timings) timings.rename = Date.now(); + // disable rename on harmony due to expand_names bug in for-of loops + // https://github.com/mishoo/UglifyJS2/issues/2794 + if (0 && options.rename) { + toplevel.figure_out_scope(options.mangle); + toplevel.expand_names(options.mangle); + } + if (timings) timings.compress = Date.now(); + if (options.compress) { + toplevel = new Compressor(options.compress, { + mangle_options: options.mangle + }).compress(toplevel); + } + if (timings) timings.scope = Date.now(); + if (options.mangle) toplevel.figure_out_scope(options.mangle); + if (timings) timings.mangle = Date.now(); + if (options.mangle) { + toplevel.compute_char_frequency(options.mangle); + toplevel.mangle_names(options.mangle); + toplevel = mangle_private_properties(toplevel, options.mangle); + } + if (timings) timings.properties = Date.now(); + if (options.mangle && options.mangle.properties) { + toplevel = mangle_properties(toplevel, options.mangle.properties); + } + if (timings) timings.format = Date.now(); + var result = {}; + if (options.format.ast) { + result.ast = toplevel; + } + if (options.format.spidermonkey) { + result.ast = toplevel.to_mozilla_ast(); + } + if (!HOP(options.format, "code") || options.format.code) { + if (options.sourceMap) { + options.format.source_map = await SourceMap({ + file: options.sourceMap.filename, + orig: options.sourceMap.content, + root: options.sourceMap.root + }); + if (options.sourceMap.includeSources) { + if (files instanceof AST_Toplevel) { + throw new Error("original source content unavailable"); + } else for (var name in files) if (HOP(files, name)) { + options.format.source_map.get().setSourceContent(name, files[name]); + } + } + } + delete options.format.ast; + delete options.format.code; + delete options.format.spidermonkey; + var stream = OutputStream(options.format); + toplevel.print(stream); + result.code = stream.get(); + if (options.sourceMap) { + if(options.sourceMap.asObject) { + result.map = options.format.source_map.get().toJSON(); + } else { + result.map = options.format.source_map.toString(); + } + if (options.sourceMap.url == "inline") { + var sourceMap = typeof result.map === "object" ? JSON.stringify(result.map) : result.map; + result.code += "\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + to_base64(sourceMap); + } else if (options.sourceMap.url) { + result.code += "\n//# sourceMappingURL=" + options.sourceMap.url; + } + } + } + if (options.nameCache && options.mangle) { + if (options.mangle.cache) options.nameCache.vars = cache_to_json(options.mangle.cache); + if (options.mangle.properties && options.mangle.properties.cache) { + options.nameCache.props = cache_to_json(options.mangle.properties.cache); + } + } + if (options.format && options.format.source_map) { + options.format.source_map.destroy(); + } + if (timings) { + timings.end = Date.now(); + result.timings = { + parse: 1e-3 * (timings.rename - timings.parse), + rename: 1e-3 * (timings.compress - timings.rename), + compress: 1e-3 * (timings.scope - timings.compress), + scope: 1e-3 * (timings.mangle - timings.scope), + mangle: 1e-3 * (timings.properties - timings.mangle), + properties: 1e-3 * (timings.format - timings.properties), + format: 1e-3 * (timings.end - timings.format), + total: 1e-3 * (timings.end - timings.start) + }; + } + return result; +} + +export { + minify, + to_ascii, +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/mozilla-ast.js b/node_modules/mathjs/examples/node_modules/terser/lib/mozilla-ast.js new file mode 100644 index 0000000..b790e55 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/mozilla-ast.js @@ -0,0 +1,1376 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import * as ast from "./ast.js"; +import { make_node } from "./utils/index.js"; +import { + AST_Accessor, + AST_Array, + AST_Arrow, + AST_Assign, + AST_Atom, + AST_Await, + AST_BigInt, + AST_Binary, + AST_Block, + AST_BlockStatement, + AST_Boolean, + AST_Break, + AST_Call, + AST_Case, + AST_Catch, + AST_Chain, + AST_Class, + AST_ClassExpression, + AST_ClassProperty, + AST_ClassPrivateProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Const, + AST_Constant, + AST_Continue, + AST_Debugger, + AST_Default, + AST_DefaultAssign, + AST_DefClass, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DotHash, + AST_EmptyStatement, + AST_Expansion, + AST_Export, + AST_False, + AST_Finally, + AST_For, + AST_ForIn, + AST_ForOf, + AST_Function, + AST_Hole, + AST_If, + AST_Import, + AST_ImportMeta, + AST_Label, + AST_LabeledStatement, + AST_LabelRef, + AST_Lambda, + AST_Let, + AST_NameMapping, + AST_New, + AST_NewTarget, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PrefixedTemplateString, + AST_PrivateGetter, + AST_PrivateMethod, + AST_PrivateSetter, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_String, + AST_Sub, + AST_Super, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_SymbolCatch, + AST_SymbolClass, + AST_SymbolClassProperty, + AST_SymbolConst, + AST_SymbolDefClass, + AST_SymbolDefun, + AST_SymbolExport, + AST_SymbolExportForeign, + AST_SymbolFunarg, + AST_SymbolImport, + AST_SymbolImportForeign, + AST_SymbolLambda, + AST_SymbolLet, + AST_SymbolMethod, + AST_SymbolRef, + AST_SymbolVar, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Throw, + AST_Token, + AST_Toplevel, + AST_True, + AST_Try, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Var, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, +} from "./ast.js"; +import { is_basic_identifier_string } from "./parse.js"; + +(function() { + + var normalize_directives = function(body) { + var in_directive = true; + + for (var i = 0; i < body.length; i++) { + if (in_directive && body[i] instanceof AST_Statement && body[i].body instanceof AST_String) { + body[i] = new AST_Directive({ + start: body[i].start, + end: body[i].end, + value: body[i].body.value + }); + } else if (in_directive && !(body[i] instanceof AST_Statement && body[i].body instanceof AST_String)) { + in_directive = false; + } + } + + return body; + }; + + const assert_clause_from_moz = (assertions) => { + if (assertions && assertions.length > 0) { + return new AST_Object({ + start: my_start_token(assertions), + end: my_end_token(assertions), + properties: assertions.map((assertion_kv) => + new AST_ObjectKeyVal({ + start: my_start_token(assertion_kv), + end: my_end_token(assertion_kv), + key: assertion_kv.key.name || assertion_kv.key.value, + value: from_moz(assertion_kv.value) + }) + ) + }); + } + return null; + }; + + var MOZ_TO_ME = { + Program: function(M) { + return new AST_Toplevel({ + start: my_start_token(M), + end: my_end_token(M), + body: normalize_directives(M.body.map(from_moz)) + }); + }, + ArrayPattern: function(M) { + return new AST_Destructuring({ + start: my_start_token(M), + end: my_end_token(M), + names: M.elements.map(function(elm) { + if (elm === null) { + return new AST_Hole(); + } + return from_moz(elm); + }), + is_array: true + }); + }, + ObjectPattern: function(M) { + return new AST_Destructuring({ + start: my_start_token(M), + end: my_end_token(M), + names: M.properties.map(from_moz), + is_array: false + }); + }, + AssignmentPattern: function(M) { + return new AST_DefaultAssign({ + start: my_start_token(M), + end: my_end_token(M), + left: from_moz(M.left), + operator: "=", + right: from_moz(M.right) + }); + }, + SpreadElement: function(M) { + return new AST_Expansion({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument) + }); + }, + RestElement: function(M) { + return new AST_Expansion({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument) + }); + }, + TemplateElement: function(M) { + return new AST_TemplateSegment({ + start: my_start_token(M), + end: my_end_token(M), + value: M.value.cooked, + raw: M.value.raw + }); + }, + TemplateLiteral: function(M) { + var segments = []; + for (var i = 0; i < M.quasis.length; i++) { + segments.push(from_moz(M.quasis[i])); + if (M.expressions[i]) { + segments.push(from_moz(M.expressions[i])); + } + } + return new AST_TemplateString({ + start: my_start_token(M), + end: my_end_token(M), + segments: segments + }); + }, + TaggedTemplateExpression: function(M) { + return new AST_PrefixedTemplateString({ + start: my_start_token(M), + end: my_end_token(M), + template_string: from_moz(M.quasi), + prefix: from_moz(M.tag) + }); + }, + FunctionDeclaration: function(M) { + return new AST_Defun({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + is_generator: M.generator, + async: M.async, + body: normalize_directives(from_moz(M.body).body) + }); + }, + FunctionExpression: function(M) { + return new AST_Function({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + is_generator: M.generator, + async: M.async, + body: normalize_directives(from_moz(M.body).body) + }); + }, + ArrowFunctionExpression: function(M) { + const body = M.body.type === "BlockStatement" + ? from_moz(M.body).body + : [make_node(AST_Return, {}, { value: from_moz(M.body) })]; + return new AST_Arrow({ + start: my_start_token(M), + end: my_end_token(M), + argnames: M.params.map(from_moz), + body, + async: M.async, + }); + }, + ExpressionStatement: function(M) { + return new AST_SimpleStatement({ + start: my_start_token(M), + end: my_end_token(M), + body: from_moz(M.expression) + }); + }, + TryStatement: function(M) { + var handlers = M.handlers || [M.handler]; + if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) { + throw new Error("Multiple catch clauses are not supported."); + } + return new AST_Try({ + start : my_start_token(M), + end : my_end_token(M), + body : from_moz(M.block).body, + bcatch : from_moz(handlers[0]), + bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null + }); + }, + Property: function(M) { + var key = M.key; + var args = { + start : my_start_token(key || M.value), + end : my_end_token(M.value), + key : key.type == "Identifier" ? key.name : key.value, + value : from_moz(M.value) + }; + if (M.computed) { + args.key = from_moz(M.key); + } + if (M.method) { + args.is_generator = M.value.generator; + args.async = M.value.async; + if (!M.computed) { + args.key = new AST_SymbolMethod({ name: args.key }); + } else { + args.key = from_moz(M.key); + } + return new AST_ConciseMethod(args); + } + if (M.kind == "init") { + if (key.type != "Identifier" && key.type != "Literal") { + args.key = from_moz(key); + } + return new AST_ObjectKeyVal(args); + } + if (typeof args.key === "string" || typeof args.key === "number") { + args.key = new AST_SymbolMethod({ + name: args.key + }); + } + args.value = new AST_Accessor(args.value); + if (M.kind == "get") return new AST_ObjectGetter(args); + if (M.kind == "set") return new AST_ObjectSetter(args); + if (M.kind == "method") { + args.async = M.value.async; + args.is_generator = M.value.generator; + args.quote = M.computed ? "\"" : null; + return new AST_ConciseMethod(args); + } + }, + MethodDefinition: function(M) { + var args = { + start : my_start_token(M), + end : my_end_token(M), + key : M.computed ? from_moz(M.key) : new AST_SymbolMethod({ name: M.key.name || M.key.value }), + value : from_moz(M.value), + static : M.static, + }; + if (M.kind == "get") { + return new AST_ObjectGetter(args); + } + if (M.kind == "set") { + return new AST_ObjectSetter(args); + } + args.is_generator = M.value.generator; + args.async = M.value.async; + return new AST_ConciseMethod(args); + }, + FieldDefinition: function(M) { + let key; + if (M.computed) { + key = from_moz(M.key); + } else { + if (M.key.type !== "Identifier") throw new Error("Non-Identifier key in FieldDefinition"); + key = from_moz(M.key); + } + return new AST_ClassProperty({ + start : my_start_token(M), + end : my_end_token(M), + key, + value : from_moz(M.value), + static : M.static, + }); + }, + PropertyDefinition: function(M) { + let key; + if (M.computed) { + key = from_moz(M.key); + } else { + if (M.key.type !== "Identifier") throw new Error("Non-Identifier key in PropertyDefinition"); + key = from_moz(M.key); + } + + return new AST_ClassProperty({ + start : my_start_token(M), + end : my_end_token(M), + key, + value : from_moz(M.value), + static : M.static, + }); + }, + ArrayExpression: function(M) { + return new AST_Array({ + start : my_start_token(M), + end : my_end_token(M), + elements : M.elements.map(function(elem) { + return elem === null ? new AST_Hole() : from_moz(elem); + }) + }); + }, + ObjectExpression: function(M) { + return new AST_Object({ + start : my_start_token(M), + end : my_end_token(M), + properties : M.properties.map(function(prop) { + if (prop.type === "SpreadElement") { + return from_moz(prop); + } + prop.type = "Property"; + return from_moz(prop); + }) + }); + }, + SequenceExpression: function(M) { + return new AST_Sequence({ + start : my_start_token(M), + end : my_end_token(M), + expressions: M.expressions.map(from_moz) + }); + }, + MemberExpression: function(M) { + return new (M.computed ? AST_Sub : AST_Dot)({ + start : my_start_token(M), + end : my_end_token(M), + property : M.computed ? from_moz(M.property) : M.property.name, + expression : from_moz(M.object), + optional : M.optional || false + }); + }, + ChainExpression: function(M) { + return new AST_Chain({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.expression) + }); + }, + SwitchCase: function(M) { + return new (M.test ? AST_Case : AST_Default)({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.test), + body : M.consequent.map(from_moz) + }); + }, + VariableDeclaration: function(M) { + return new (M.kind === "const" ? AST_Const : + M.kind === "let" ? AST_Let : AST_Var)({ + start : my_start_token(M), + end : my_end_token(M), + definitions : M.declarations.map(from_moz) + }); + }, + + ImportDeclaration: function(M) { + var imported_name = null; + var imported_names = null; + M.specifiers.forEach(function (specifier) { + if (specifier.type === "ImportSpecifier") { + if (!imported_names) { imported_names = []; } + imported_names.push(new AST_NameMapping({ + start: my_start_token(specifier), + end: my_end_token(specifier), + foreign_name: from_moz(specifier.imported), + name: from_moz(specifier.local) + })); + } else if (specifier.type === "ImportDefaultSpecifier") { + imported_name = from_moz(specifier.local); + } else if (specifier.type === "ImportNamespaceSpecifier") { + if (!imported_names) { imported_names = []; } + imported_names.push(new AST_NameMapping({ + start: my_start_token(specifier), + end: my_end_token(specifier), + foreign_name: new AST_SymbolImportForeign({ name: "*" }), + name: from_moz(specifier.local) + })); + } + }); + return new AST_Import({ + start : my_start_token(M), + end : my_end_token(M), + imported_name: imported_name, + imported_names : imported_names, + module_name : from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + ExportAllDeclaration: function(M) { + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_names: [ + new AST_NameMapping({ + name: new AST_SymbolExportForeign({ name: "*" }), + foreign_name: new AST_SymbolExportForeign({ name: "*" }) + }) + ], + module_name: from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + ExportNamedDeclaration: function(M) { + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_definition: from_moz(M.declaration), + exported_names: M.specifiers && M.specifiers.length ? M.specifiers.map(function (specifier) { + return new AST_NameMapping({ + foreign_name: from_moz(specifier.exported), + name: from_moz(specifier.local) + }); + }) : null, + module_name: from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + ExportDefaultDeclaration: function(M) { + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_value: from_moz(M.declaration), + is_default: true + }); + }, + Literal: function(M) { + var val = M.value, args = { + start : my_start_token(M), + end : my_end_token(M) + }; + var rx = M.regex; + if (rx && rx.pattern) { + // RegExpLiteral as per ESTree AST spec + args.value = { + source: rx.pattern, + flags: rx.flags + }; + return new AST_RegExp(args); + } else if (rx) { + // support legacy RegExp + const rx_source = M.raw || val; + const match = rx_source.match(/^\/(.*)\/(\w*)$/); + if (!match) throw new Error("Invalid regex source " + rx_source); + const [_, source, flags] = match; + args.value = { source, flags }; + return new AST_RegExp(args); + } + if (val === null) return new AST_Null(args); + switch (typeof val) { + case "string": + args.value = val; + return new AST_String(args); + case "number": + args.value = val; + args.raw = M.raw || val.toString(); + return new AST_Number(args); + case "boolean": + return new (val ? AST_True : AST_False)(args); + } + }, + MetaProperty: function(M) { + if (M.meta.name === "new" && M.property.name === "target") { + return new AST_NewTarget({ + start: my_start_token(M), + end: my_end_token(M) + }); + } else if (M.meta.name === "import" && M.property.name === "meta") { + return new AST_ImportMeta({ + start: my_start_token(M), + end: my_end_token(M) + }); + } + }, + Identifier: function(M) { + var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; + return new ( p.type == "LabeledStatement" ? AST_Label + : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : p.kind == "let" ? AST_SymbolLet : AST_SymbolVar) + : /Import.*Specifier/.test(p.type) ? (p.local === M ? AST_SymbolImport : AST_SymbolImportForeign) + : p.type == "ExportSpecifier" ? (p.local === M ? AST_SymbolExport : AST_SymbolExportForeign) + : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) + : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) + : p.type == "ArrowFunctionExpression" ? (p.params.includes(M)) ? AST_SymbolFunarg : AST_SymbolRef + : p.type == "ClassExpression" ? (p.id === M ? AST_SymbolClass : AST_SymbolRef) + : p.type == "Property" ? (p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolMethod) + : p.type == "PropertyDefinition" || p.type === "FieldDefinition" ? (p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolClassProperty) + : p.type == "ClassDeclaration" ? (p.id === M ? AST_SymbolDefClass : AST_SymbolRef) + : p.type == "MethodDefinition" ? (p.computed ? AST_SymbolRef : AST_SymbolMethod) + : p.type == "CatchClause" ? AST_SymbolCatch + : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef + : AST_SymbolRef)({ + start : my_start_token(M), + end : my_end_token(M), + name : M.name + }); + }, + BigIntLiteral(M) { + return new AST_BigInt({ + start : my_start_token(M), + end : my_end_token(M), + value : M.value + }); + } + }; + + MOZ_TO_ME.UpdateExpression = + MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) { + var prefix = "prefix" in M ? M.prefix + : M.type == "UnaryExpression" ? true : false; + return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ + start : my_start_token(M), + end : my_end_token(M), + operator : M.operator, + expression : from_moz(M.argument) + }); + }; + + MOZ_TO_ME.ClassDeclaration = + MOZ_TO_ME.ClassExpression = function From_Moz_Class(M) { + return new (M.type === "ClassDeclaration" ? AST_DefClass : AST_ClassExpression)({ + start : my_start_token(M), + end : my_end_token(M), + name : from_moz(M.id), + extends : from_moz(M.superClass), + properties: M.body.body.map(from_moz) + }); + }; + + map("EmptyStatement", AST_EmptyStatement); + map("BlockStatement", AST_BlockStatement, "body@body"); + map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"); + map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"); + map("BreakStatement", AST_Break, "label>label"); + map("ContinueStatement", AST_Continue, "label>label"); + map("WithStatement", AST_With, "object>expression, body>body"); + map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"); + map("ReturnStatement", AST_Return, "argument>value"); + map("ThrowStatement", AST_Throw, "argument>value"); + map("WhileStatement", AST_While, "test>condition, body>body"); + map("DoWhileStatement", AST_Do, "test>condition, body>body"); + map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"); + map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"); + map("ForOfStatement", AST_ForOf, "left>init, right>object, body>body, await=await"); + map("AwaitExpression", AST_Await, "argument>expression"); + map("YieldExpression", AST_Yield, "argument>expression, delegate=is_star"); + map("DebuggerStatement", AST_Debugger); + map("VariableDeclarator", AST_VarDef, "id>name, init>value"); + map("CatchClause", AST_Catch, "param>argname, body%body"); + + map("ThisExpression", AST_This); + map("Super", AST_Super); + map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"); + map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"); + map("NewExpression", AST_New, "callee>expression, arguments@args"); + map("CallExpression", AST_Call, "callee>expression, optional=optional, arguments@args"); + + def_to_moz(AST_Toplevel, function To_Moz_Program(M) { + return to_moz_scope("Program", M); + }); + + def_to_moz(AST_Expansion, function To_Moz_Spread(M) { + return { + type: to_moz_in_destructuring() ? "RestElement" : "SpreadElement", + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_PrefixedTemplateString, function To_Moz_TaggedTemplateExpression(M) { + return { + type: "TaggedTemplateExpression", + tag: to_moz(M.prefix), + quasi: to_moz(M.template_string) + }; + }); + + def_to_moz(AST_TemplateString, function To_Moz_TemplateLiteral(M) { + var quasis = []; + var expressions = []; + for (var i = 0; i < M.segments.length; i++) { + if (i % 2 !== 0) { + expressions.push(to_moz(M.segments[i])); + } else { + quasis.push({ + type: "TemplateElement", + value: { + raw: M.segments[i].raw, + cooked: M.segments[i].value + }, + tail: i === M.segments.length - 1 + }); + } + } + return { + type: "TemplateLiteral", + quasis: quasis, + expressions: expressions + }; + }); + + def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) { + return { + type: "FunctionDeclaration", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + generator: M.is_generator, + async: M.async, + body: to_moz_scope("BlockStatement", M) + }; + }); + + def_to_moz(AST_Function, function To_Moz_FunctionExpression(M, parent) { + var is_generator = parent.is_generator !== undefined ? + parent.is_generator : M.is_generator; + return { + type: "FunctionExpression", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + generator: is_generator, + async: M.async, + body: to_moz_scope("BlockStatement", M) + }; + }); + + def_to_moz(AST_Arrow, function To_Moz_ArrowFunctionExpression(M) { + var body = { + type: "BlockStatement", + body: M.body.map(to_moz) + }; + return { + type: "ArrowFunctionExpression", + params: M.argnames.map(to_moz), + async: M.async, + body: body + }; + }); + + def_to_moz(AST_Destructuring, function To_Moz_ObjectPattern(M) { + if (M.is_array) { + return { + type: "ArrayPattern", + elements: M.names.map(to_moz) + }; + } + return { + type: "ObjectPattern", + properties: M.names.map(to_moz) + }; + }); + + def_to_moz(AST_Directive, function To_Moz_Directive(M) { + return { + type: "ExpressionStatement", + expression: { + type: "Literal", + value: M.value, + raw: M.print_to_string() + }, + directive: M.value + }; + }); + + def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) { + return { + type: "ExpressionStatement", + expression: to_moz(M.body) + }; + }); + + def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) { + return { + type: "SwitchCase", + test: to_moz(M.expression), + consequent: M.body.map(to_moz) + }; + }); + + def_to_moz(AST_Try, function To_Moz_TryStatement(M) { + return { + type: "TryStatement", + block: to_moz_block(M), + handler: to_moz(M.bcatch), + guardedHandlers: [], + finalizer: to_moz(M.bfinally) + }; + }); + + def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { + return { + type: "CatchClause", + param: to_moz(M.argname), + guard: null, + body: to_moz_block(M) + }; + }); + + def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) { + return { + type: "VariableDeclaration", + kind: + M instanceof AST_Const ? "const" : + M instanceof AST_Let ? "let" : "var", + declarations: M.definitions.map(to_moz) + }; + }); + + const assert_clause_to_moz = assert_clause => { + const assertions = []; + if (assert_clause) { + for (const { key, value } of assert_clause.properties) { + const key_moz = is_basic_identifier_string(key) + ? { type: "Identifier", name: key } + : { type: "Literal", value: key, raw: JSON.stringify(key) }; + assertions.push({ + type: "ImportAttribute", + key: key_moz, + value: to_moz(value) + }); + } + } + return assertions; + }; + + def_to_moz(AST_Export, function To_Moz_ExportDeclaration(M) { + if (M.exported_names) { + if (M.exported_names[0].name.name === "*") { + return { + type: "ExportAllDeclaration", + source: to_moz(M.module_name), + assertions: assert_clause_to_moz(M.assert_clause) + }; + } + return { + type: "ExportNamedDeclaration", + specifiers: M.exported_names.map(function (name_mapping) { + return { + type: "ExportSpecifier", + exported: to_moz(name_mapping.foreign_name), + local: to_moz(name_mapping.name) + }; + }), + declaration: to_moz(M.exported_definition), + source: to_moz(M.module_name), + assertions: assert_clause_to_moz(M.assert_clause) + }; + } + return { + type: M.is_default ? "ExportDefaultDeclaration" : "ExportNamedDeclaration", + declaration: to_moz(M.exported_value || M.exported_definition) + }; + }); + + def_to_moz(AST_Import, function To_Moz_ImportDeclaration(M) { + var specifiers = []; + if (M.imported_name) { + specifiers.push({ + type: "ImportDefaultSpecifier", + local: to_moz(M.imported_name) + }); + } + if (M.imported_names && M.imported_names[0].foreign_name.name === "*") { + specifiers.push({ + type: "ImportNamespaceSpecifier", + local: to_moz(M.imported_names[0].name) + }); + } else if (M.imported_names) { + M.imported_names.forEach(function(name_mapping) { + specifiers.push({ + type: "ImportSpecifier", + local: to_moz(name_mapping.name), + imported: to_moz(name_mapping.foreign_name) + }); + }); + } + return { + type: "ImportDeclaration", + specifiers: specifiers, + source: to_moz(M.module_name), + assertions: assert_clause_to_moz(M.assert_clause) + }; + }); + + def_to_moz(AST_ImportMeta, function To_Moz_MetaProperty() { + return { + type: "MetaProperty", + meta: { + type: "Identifier", + name: "import" + }, + property: { + type: "Identifier", + name: "meta" + } + }; + }); + + def_to_moz(AST_Sequence, function To_Moz_SequenceExpression(M) { + return { + type: "SequenceExpression", + expressions: M.expressions.map(to_moz) + }; + }); + + def_to_moz(AST_DotHash, function To_Moz_PrivateMemberExpression(M) { + return { + type: "MemberExpression", + object: to_moz(M.expression), + computed: false, + property: { + type: "PrivateIdentifier", + name: M.property + }, + optional: M.optional + }; + }); + + def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) { + var isComputed = M instanceof AST_Sub; + return { + type: "MemberExpression", + object: to_moz(M.expression), + computed: isComputed, + property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}, + optional: M.optional + }; + }); + + def_to_moz(AST_Chain, function To_Moz_ChainExpression(M) { + return { + type: "ChainExpression", + expression: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Unary, function To_Moz_Unary(M) { + return { + type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression", + operator: M.operator, + prefix: M instanceof AST_UnaryPrefix, + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { + if (M.operator == "=" && to_moz_in_destructuring()) { + return { + type: "AssignmentPattern", + left: to_moz(M.left), + right: to_moz(M.right) + }; + } + + const type = M.operator == "&&" || M.operator == "||" || M.operator === "??" + ? "LogicalExpression" + : "BinaryExpression"; + + return { + type, + left: to_moz(M.left), + operator: M.operator, + right: to_moz(M.right) + }; + }); + + def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) { + return { + type: "ArrayExpression", + elements: M.elements.map(to_moz) + }; + }); + + def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) { + return { + type: "ObjectExpression", + properties: M.properties.map(to_moz) + }; + }); + + def_to_moz(AST_ObjectProperty, function To_Moz_Property(M, parent) { + var key = M.key instanceof AST_Node ? to_moz(M.key) : { + type: "Identifier", + value: M.key + }; + if (typeof M.key === "number") { + key = { + type: "Literal", + value: Number(M.key) + }; + } + if (typeof M.key === "string") { + key = { + type: "Identifier", + name: M.key + }; + } + var kind; + var string_or_num = typeof M.key === "string" || typeof M.key === "number"; + var computed = string_or_num ? false : !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef; + if (M instanceof AST_ObjectKeyVal) { + kind = "init"; + computed = !string_or_num; + } else + if (M instanceof AST_ObjectGetter) { + kind = "get"; + } else + if (M instanceof AST_ObjectSetter) { + kind = "set"; + } + if (M instanceof AST_PrivateGetter || M instanceof AST_PrivateSetter) { + const kind = M instanceof AST_PrivateGetter ? "get" : "set"; + return { + type: "MethodDefinition", + computed: false, + kind: kind, + static: M.static, + key: { + type: "PrivateIdentifier", + name: M.key.name + }, + value: to_moz(M.value) + }; + } + if (M instanceof AST_ClassPrivateProperty) { + return { + type: "PropertyDefinition", + key: { + type: "PrivateIdentifier", + name: M.key.name + }, + value: to_moz(M.value), + computed: false, + static: M.static + }; + } + if (M instanceof AST_ClassProperty) { + return { + type: "PropertyDefinition", + key, + value: to_moz(M.value), + computed, + static: M.static + }; + } + if (parent instanceof AST_Class) { + return { + type: "MethodDefinition", + computed: computed, + kind: kind, + static: M.static, + key: to_moz(M.key), + value: to_moz(M.value) + }; + } + return { + type: "Property", + computed: computed, + kind: kind, + key: key, + value: to_moz(M.value) + }; + }); + + def_to_moz(AST_ConciseMethod, function To_Moz_MethodDefinition(M, parent) { + if (parent instanceof AST_Object) { + return { + type: "Property", + computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef, + kind: "init", + method: true, + shorthand: false, + key: to_moz(M.key), + value: to_moz(M.value) + }; + } + + const key = M instanceof AST_PrivateMethod + ? { + type: "PrivateIdentifier", + name: M.key.name + } + : to_moz(M.key); + + return { + type: "MethodDefinition", + kind: M.key === "constructor" ? "constructor" : "method", + key, + value: to_moz(M.value), + computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef, + static: M.static, + }; + }); + + def_to_moz(AST_Class, function To_Moz_Class(M) { + var type = M instanceof AST_ClassExpression ? "ClassExpression" : "ClassDeclaration"; + return { + type: type, + superClass: to_moz(M.extends), + id: M.name ? to_moz(M.name) : null, + body: { + type: "ClassBody", + body: M.properties.map(to_moz) + } + }; + }); + + def_to_moz(AST_NewTarget, function To_Moz_MetaProperty() { + return { + type: "MetaProperty", + meta: { + type: "Identifier", + name: "new" + }, + property: { + type: "Identifier", + name: "target" + } + }; + }); + + def_to_moz(AST_Symbol, function To_Moz_Identifier(M, parent) { + if (M instanceof AST_SymbolMethod && parent.quote) { + return { + type: "Literal", + value: M.name + }; + } + var def = M.definition(); + return { + type: "Identifier", + name: def ? def.mangled_name || def.name : M.name + }; + }); + + def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) { + const pattern = M.value.source; + const flags = M.value.flags; + return { + type: "Literal", + value: null, + raw: M.print_to_string(), + regex: { pattern, flags } + }; + }); + + def_to_moz(AST_Constant, function To_Moz_Literal(M) { + var value = M.value; + return { + type: "Literal", + value: value, + raw: M.raw || M.print_to_string() + }; + }); + + def_to_moz(AST_Atom, function To_Moz_Atom(M) { + return { + type: "Identifier", + name: String(M.value) + }; + }); + + def_to_moz(AST_BigInt, M => ({ + type: "BigIntLiteral", + value: M.value + })); + + AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null; }); + + AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast); + AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast); + + /* -----[ tools ]----- */ + + function my_start_token(moznode) { + var loc = moznode.loc, start = loc && loc.start; + var range = moznode.range; + return new AST_Token( + "", + "", + start && start.line || 0, + start && start.column || 0, + range ? range [0] : moznode.start, + false, + [], + [], + loc && loc.source, + ); + } + + function my_end_token(moznode) { + var loc = moznode.loc, end = loc && loc.end; + var range = moznode.range; + return new AST_Token( + "", + "", + end && end.line || 0, + end && end.column || 0, + range ? range [0] : moznode.end, + false, + [], + [], + loc && loc.source, + ); + } + + function map(moztype, mytype, propmap) { + var moz_to_me = "function From_Moz_" + moztype + "(M){\n"; + moz_to_me += "return new U2." + mytype.name + "({\n" + + "start: my_start_token(M),\n" + + "end: my_end_token(M)"; + + var me_to_moz = "function To_Moz_" + moztype + "(M){\n"; + me_to_moz += "return {\n" + + "type: " + JSON.stringify(moztype); + + if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop) { + var m = /([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(prop); + if (!m) throw new Error("Can't understand property map: " + prop); + var moz = m[1], how = m[2], my = m[3]; + moz_to_me += ",\n" + my + ": "; + me_to_moz += ",\n" + moz + ": "; + switch (how) { + case "@": + moz_to_me += "M." + moz + ".map(from_moz)"; + me_to_moz += "M." + my + ".map(to_moz)"; + break; + case ">": + moz_to_me += "from_moz(M." + moz + ")"; + me_to_moz += "to_moz(M." + my + ")"; + break; + case "=": + moz_to_me += "M." + moz; + me_to_moz += "M." + my; + break; + case "%": + moz_to_me += "from_moz(M." + moz + ").body"; + me_to_moz += "to_moz_block(M)"; + break; + default: + throw new Error("Can't understand operator in propmap: " + prop); + } + }); + + moz_to_me += "\n})\n}"; + me_to_moz += "\n}\n}"; + + moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")( + ast, my_start_token, my_end_token, from_moz + ); + me_to_moz = new Function("to_moz", "to_moz_block", "to_moz_scope", "return(" + me_to_moz + ")")( + to_moz, to_moz_block, to_moz_scope + ); + MOZ_TO_ME[moztype] = moz_to_me; + def_to_moz(mytype, me_to_moz); + } + + var FROM_MOZ_STACK = null; + + function from_moz(node) { + FROM_MOZ_STACK.push(node); + var ret = node != null ? MOZ_TO_ME[node.type](node) : null; + FROM_MOZ_STACK.pop(); + return ret; + } + + AST_Node.from_mozilla_ast = function(node) { + var save_stack = FROM_MOZ_STACK; + FROM_MOZ_STACK = []; + var ast = from_moz(node); + FROM_MOZ_STACK = save_stack; + return ast; + }; + + function set_moz_loc(mynode, moznode) { + var start = mynode.start; + var end = mynode.end; + if (!(start && end)) { + return moznode; + } + if (start.pos != null && end.endpos != null) { + moznode.range = [start.pos, end.endpos]; + } + if (start.line) { + moznode.loc = { + start: {line: start.line, column: start.col}, + end: end.endline ? {line: end.endline, column: end.endcol} : null + }; + if (start.file) { + moznode.loc.source = start.file; + } + } + return moznode; + } + + function def_to_moz(mytype, handler) { + mytype.DEFMETHOD("to_mozilla_ast", function(parent) { + return set_moz_loc(this, handler(this, parent)); + }); + } + + var TO_MOZ_STACK = null; + + function to_moz(node) { + if (TO_MOZ_STACK === null) { TO_MOZ_STACK = []; } + TO_MOZ_STACK.push(node); + var ast = node != null ? node.to_mozilla_ast(TO_MOZ_STACK[TO_MOZ_STACK.length - 2]) : null; + TO_MOZ_STACK.pop(); + if (TO_MOZ_STACK.length === 0) { TO_MOZ_STACK = null; } + return ast; + } + + function to_moz_in_destructuring() { + var i = TO_MOZ_STACK.length; + while (i--) { + if (TO_MOZ_STACK[i] instanceof AST_Destructuring) { + return true; + } + } + return false; + } + + function to_moz_block(node) { + return { + type: "BlockStatement", + body: node.body.map(to_moz) + }; + } + + function to_moz_scope(type, node) { + var body = node.body.map(to_moz); + if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) { + body.unshift(to_moz(new AST_EmptyStatement(node.body[0]))); + } + return { + type: type, + body: body + }; + } +})(); diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/output.js b/node_modules/mathjs/examples/node_modules/terser/lib/output.js new file mode 100644 index 0000000..05d3e62 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/output.js @@ -0,0 +1,2347 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +import { + defaults, + makePredicate, + noop, + regexp_source_fix, + sort_regexp_flags, + return_false, + return_true, +} from "./utils/index.js"; +import { first_in_statement, left_is_object } from "./utils/first_in_statement.js"; +import { + AST_Array, + AST_Arrow, + AST_Assign, + AST_Await, + AST_BigInt, + AST_Binary, + AST_BlockStatement, + AST_Break, + AST_Call, + AST_Case, + AST_Catch, + AST_Chain, + AST_Class, + AST_ClassExpression, + AST_ClassPrivateProperty, + AST_ClassProperty, + AST_ConciseMethod, + AST_PrivateGetter, + AST_PrivateMethod, + AST_PrivateSetter, + AST_Conditional, + AST_Const, + AST_Constant, + AST_Continue, + AST_Debugger, + AST_Default, + AST_DefaultAssign, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DotHash, + AST_EmptyStatement, + AST_Exit, + AST_Expansion, + AST_Export, + AST_Finally, + AST_For, + AST_ForIn, + AST_ForOf, + AST_Function, + AST_Hole, + AST_If, + AST_Import, + AST_ImportMeta, + AST_Jump, + AST_LabeledStatement, + AST_Lambda, + AST_Let, + AST_LoopControl, + AST_NameMapping, + AST_New, + AST_NewTarget, + AST_Node, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PrefixedTemplateString, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_StatementWithBody, + AST_String, + AST_Sub, + AST_Super, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_SymbolClassProperty, + AST_SymbolMethod, + AST_SymbolRef, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Throw, + AST_Toplevel, + AST_Try, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Var, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, + TreeWalker, + walk, + walk_abort +} from "./ast.js"; +import { + get_full_char_code, + get_full_char, + is_identifier_char, + is_basic_identifier_string, + is_identifier_string, + PRECEDENCE, + ALL_RESERVED_WORDS, +} from "./parse.js"; + +const EXPECT_DIRECTIVE = /^$|[;{][\s\n]*$/; +const CODE_LINE_BREAK = 10; +const CODE_SPACE = 32; + +const r_annotation = /[@#]__(PURE|INLINE|NOINLINE)__/g; + +function is_some_comments(comment) { + // multiline comment + return ( + (comment.type === "comment2" || comment.type === "comment1") + && /@preserve|@copyright|@lic|@cc_on|^\**!/i.test(comment.value) + ); +} + +class Rope { + constructor() { + this.committed = ""; + this.current = ""; + } + + append(str) { + this.current += str; + } + + insertAt(char, index) { + const { committed, current } = this; + if (index < committed.length) { + this.committed = committed.slice(0, index) + char + committed.slice(index); + } else if (index === committed.length) { + this.committed += char; + } else { + index -= committed.length; + this.committed += current.slice(0, index) + char; + this.current = current.slice(index); + } + } + + charAt(index) { + const { committed } = this; + if (index < committed.length) return committed[index]; + return this.current[index - committed.length]; + } + + curLength() { + return this.current.length; + } + + length() { + return this.committed.length + this.current.length; + } + + toString() { + return this.committed + this.current; + } +} + +function OutputStream(options) { + + var readonly = !options; + options = defaults(options, { + ascii_only : false, + beautify : false, + braces : false, + comments : "some", + ecma : 5, + ie8 : false, + indent_level : 4, + indent_start : 0, + inline_script : true, + keep_numbers : false, + keep_quoted_props : false, + max_line_len : false, + preamble : null, + preserve_annotations : false, + quote_keys : false, + quote_style : 0, + safari10 : false, + semicolons : true, + shebang : true, + shorthand : undefined, + source_map : null, + webkit : false, + width : 80, + wrap_iife : false, + wrap_func_args : true, + }, true); + + if (options.shorthand === undefined) + options.shorthand = options.ecma > 5; + + // Convert comment option to RegExp if neccessary and set up comments filter + var comment_filter = return_false; // Default case, throw all comments away + if (options.comments) { + let comments = options.comments; + if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) { + var regex_pos = options.comments.lastIndexOf("/"); + comments = new RegExp( + options.comments.substr(1, regex_pos - 1), + options.comments.substr(regex_pos + 1) + ); + } + if (comments instanceof RegExp) { + comment_filter = function(comment) { + return comment.type != "comment5" && comments.test(comment.value); + }; + } else if (typeof comments === "function") { + comment_filter = function(comment) { + return comment.type != "comment5" && comments(this, comment); + }; + } else if (comments === "some") { + comment_filter = is_some_comments; + } else { // NOTE includes "all" option + comment_filter = return_true; + } + } + + var indentation = 0; + var current_col = 0; + var current_line = 1; + var current_pos = 0; + var OUTPUT = new Rope(); + let printed_comments = new Set(); + + var to_utf8 = options.ascii_only ? function(str, identifier = false, regexp = false) { + if (options.ecma >= 2015 && !options.safari10 && !regexp) { + str = str.replace(/[\ud800-\udbff][\udc00-\udfff]/g, function(ch) { + var code = get_full_char_code(ch, 0).toString(16); + return "\\u{" + code + "}"; + }); + } + return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) { + var code = ch.charCodeAt(0).toString(16); + if (code.length <= 2 && !identifier) { + while (code.length < 2) code = "0" + code; + return "\\x" + code; + } else { + while (code.length < 4) code = "0" + code; + return "\\u" + code; + } + }); + } : function(str) { + return str.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g, function(match, lone) { + if (lone) { + return "\\u" + lone.charCodeAt(0).toString(16); + } + return match; + }); + }; + + function make_string(str, quote) { + var dq = 0, sq = 0; + str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, + function(s, i) { + switch (s) { + case '"': ++dq; return '"'; + case "'": ++sq; return "'"; + case "\\": return "\\\\"; + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\t": return "\\t"; + case "\b": return "\\b"; + case "\f": return "\\f"; + case "\x0B": return options.ie8 ? "\\x0B" : "\\v"; + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + case "\ufeff": return "\\ufeff"; + case "\0": + return /[0-9]/.test(get_full_char(str, i+1)) ? "\\x00" : "\\0"; + } + return s; + }); + function quote_single() { + return "'" + str.replace(/\x27/g, "\\'") + "'"; + } + function quote_double() { + return '"' + str.replace(/\x22/g, '\\"') + '"'; + } + function quote_template() { + return "`" + str.replace(/`/g, "\\`") + "`"; + } + str = to_utf8(str); + if (quote === "`") return quote_template(); + switch (options.quote_style) { + case 1: + return quote_single(); + case 2: + return quote_double(); + case 3: + return quote == "'" ? quote_single() : quote_double(); + default: + return dq > sq ? quote_single() : quote_double(); + } + } + + function encode_string(str, quote) { + var ret = make_string(str, quote); + if (options.inline_script) { + ret = ret.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2"); + ret = ret.replace(/\x3c!--/g, "\\x3c!--"); + ret = ret.replace(/--\x3e/g, "--\\x3e"); + } + return ret; + } + + function make_name(name) { + name = name.toString(); + name = to_utf8(name, true); + return name; + } + + function make_indent(back) { + return " ".repeat(options.indent_start + indentation - back * options.indent_level); + } + + /* -----[ beautification/minification ]----- */ + + var has_parens = false; + var might_need_space = false; + var might_need_semicolon = false; + var might_add_newline = 0; + var need_newline_indented = false; + var need_space = false; + var newline_insert = -1; + var last = ""; + var mapping_token, mapping_name, mappings = options.source_map && []; + + var do_add_mapping = mappings ? function() { + mappings.forEach(function(mapping) { + try { + let { name, token } = mapping; + if (token.type == "name" || token.type === "privatename") { + name = token.value; + } else if (name instanceof AST_Symbol) { + name = token.type === "string" ? token.value : name.name; + } + options.source_map.add( + mapping.token.file, + mapping.line, mapping.col, + mapping.token.line, mapping.token.col, + is_basic_identifier_string(name) ? name : undefined + ); + } catch(ex) { + // Ignore bad mapping + } + }); + mappings = []; + } : noop; + + var ensure_line_len = options.max_line_len ? function() { + if (current_col > options.max_line_len) { + if (might_add_newline) { + OUTPUT.insertAt("\n", might_add_newline); + const curLength = OUTPUT.curLength(); + if (mappings) { + var delta = curLength - current_col; + mappings.forEach(function(mapping) { + mapping.line++; + mapping.col += delta; + }); + } + current_line++; + current_pos++; + current_col = curLength; + } + } + if (might_add_newline) { + might_add_newline = 0; + do_add_mapping(); + } + } : noop; + + var requireSemicolonChars = makePredicate("( [ + * / - , . `"); + + function print(str) { + str = String(str); + var ch = get_full_char(str, 0); + if (need_newline_indented && ch) { + need_newline_indented = false; + if (ch !== "\n") { + print("\n"); + indent(); + } + } + if (need_space && ch) { + need_space = false; + if (!/[\s;})]/.test(ch)) { + space(); + } + } + newline_insert = -1; + var prev = last.charAt(last.length - 1); + if (might_need_semicolon) { + might_need_semicolon = false; + + if (prev === ":" && ch === "}" || (!ch || !";}".includes(ch)) && prev !== ";") { + if (options.semicolons || requireSemicolonChars.has(ch)) { + OUTPUT.append(";"); + current_col++; + current_pos++; + } else { + ensure_line_len(); + if (current_col > 0) { + OUTPUT.append("\n"); + current_pos++; + current_line++; + current_col = 0; + } + + if (/^\s+$/.test(str)) { + // reset the semicolon flag, since we didn't print one + // now and might still have to later + might_need_semicolon = true; + } + } + + if (!options.beautify) + might_need_space = false; + } + } + + if (might_need_space) { + if ((is_identifier_char(prev) + && (is_identifier_char(ch) || ch == "\\")) + || (ch == "/" && ch == prev) + || ((ch == "+" || ch == "-") && ch == last) + ) { + OUTPUT.append(" "); + current_col++; + current_pos++; + } + might_need_space = false; + } + + if (mapping_token) { + mappings.push({ + token: mapping_token, + name: mapping_name, + line: current_line, + col: current_col + }); + mapping_token = false; + if (!might_add_newline) do_add_mapping(); + } + + OUTPUT.append(str); + has_parens = str[str.length - 1] == "("; + current_pos += str.length; + var a = str.split(/\r?\n/), n = a.length - 1; + current_line += n; + current_col += a[0].length; + if (n > 0) { + ensure_line_len(); + current_col = a[n].length; + } + last = str; + } + + var star = function() { + print("*"); + }; + + var space = options.beautify ? function() { + print(" "); + } : function() { + might_need_space = true; + }; + + var indent = options.beautify ? function(half) { + if (options.beautify) { + print(make_indent(half ? 0.5 : 0)); + } + } : noop; + + var with_indent = options.beautify ? function(col, cont) { + if (col === true) col = next_indent(); + var save_indentation = indentation; + indentation = col; + var ret = cont(); + indentation = save_indentation; + return ret; + } : function(col, cont) { return cont(); }; + + var newline = options.beautify ? function() { + if (newline_insert < 0) return print("\n"); + if (OUTPUT.charAt(newline_insert) != "\n") { + OUTPUT.insertAt("\n", newline_insert); + current_pos++; + current_line++; + } + newline_insert++; + } : options.max_line_len ? function() { + ensure_line_len(); + might_add_newline = OUTPUT.length(); + } : noop; + + var semicolon = options.beautify ? function() { + print(";"); + } : function() { + might_need_semicolon = true; + }; + + function force_semicolon() { + might_need_semicolon = false; + print(";"); + } + + function next_indent() { + return indentation + options.indent_level; + } + + function with_block(cont) { + var ret; + print("{"); + newline(); + with_indent(next_indent(), function() { + ret = cont(); + }); + indent(); + print("}"); + return ret; + } + + function with_parens(cont) { + print("("); + //XXX: still nice to have that for argument lists + //var ret = with_indent(current_col, cont); + var ret = cont(); + print(")"); + return ret; + } + + function with_square(cont) { + print("["); + //var ret = with_indent(current_col, cont); + var ret = cont(); + print("]"); + return ret; + } + + function comma() { + print(","); + space(); + } + + function colon() { + print(":"); + space(); + } + + var add_mapping = mappings ? function(token, name) { + mapping_token = token; + mapping_name = name; + } : noop; + + function get() { + if (might_add_newline) { + ensure_line_len(); + } + return OUTPUT.toString(); + } + + function has_nlb() { + const output = OUTPUT.toString(); + let n = output.length - 1; + while (n >= 0) { + const code = output.charCodeAt(n); + if (code === CODE_LINE_BREAK) { + return true; + } + + if (code !== CODE_SPACE) { + return false; + } + n--; + } + return true; + } + + function filter_comment(comment) { + if (!options.preserve_annotations) { + comment = comment.replace(r_annotation, " "); + } + if (/^\s*$/.test(comment)) { + return ""; + } + return comment.replace(/(<\s*\/\s*)(script)/i, "<\\/$2"); + } + + function prepend_comments(node) { + var self = this; + var start = node.start; + if (!start) return; + var printed_comments = self.printed_comments; + + // There cannot be a newline between return and its value. + const return_with_value = node instanceof AST_Exit && node.value; + + if ( + start.comments_before + && printed_comments.has(start.comments_before) + ) { + if (return_with_value) { + start.comments_before = []; + } else { + return; + } + } + + var comments = start.comments_before; + if (!comments) { + comments = start.comments_before = []; + } + printed_comments.add(comments); + + if (return_with_value) { + var tw = new TreeWalker(function(node) { + var parent = tw.parent(); + if (parent instanceof AST_Exit + || parent instanceof AST_Binary && parent.left === node + || parent.TYPE == "Call" && parent.expression === node + || parent instanceof AST_Conditional && parent.condition === node + || parent instanceof AST_Dot && parent.expression === node + || parent instanceof AST_Sequence && parent.expressions[0] === node + || parent instanceof AST_Sub && parent.expression === node + || parent instanceof AST_UnaryPostfix) { + if (!node.start) return; + var text = node.start.comments_before; + if (text && !printed_comments.has(text)) { + printed_comments.add(text); + comments = comments.concat(text); + } + } else { + return true; + } + }); + tw.push(node); + node.value.walk(tw); + } + + if (current_pos == 0) { + if (comments.length > 0 && options.shebang && comments[0].type === "comment5" + && !printed_comments.has(comments[0])) { + print("#!" + comments.shift().value + "\n"); + indent(); + } + var preamble = options.preamble; + if (preamble) { + print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n")); + } + } + + comments = comments.filter(comment_filter, node).filter(c => !printed_comments.has(c)); + if (comments.length == 0) return; + var last_nlb = has_nlb(); + comments.forEach(function(c, i) { + printed_comments.add(c); + if (!last_nlb) { + if (c.nlb) { + print("\n"); + indent(); + last_nlb = true; + } else if (i > 0) { + space(); + } + } + + if (/comment[134]/.test(c.type)) { + var value = filter_comment(c.value); + if (value) { + print("//" + value + "\n"); + indent(); + } + last_nlb = true; + } else if (c.type == "comment2") { + var value = filter_comment(c.value); + if (value) { + print("/*" + value + "*/"); + } + last_nlb = false; + } + }); + if (!last_nlb) { + if (start.nlb) { + print("\n"); + indent(); + } else { + space(); + } + } + } + + function append_comments(node, tail) { + var self = this; + var token = node.end; + if (!token) return; + var printed_comments = self.printed_comments; + var comments = token[tail ? "comments_before" : "comments_after"]; + if (!comments || printed_comments.has(comments)) return; + if (!(node instanceof AST_Statement || comments.every((c) => + !/comment[134]/.test(c.type) + ))) return; + printed_comments.add(comments); + var insert = OUTPUT.length(); + comments.filter(comment_filter, node).forEach(function(c, i) { + if (printed_comments.has(c)) return; + printed_comments.add(c); + need_space = false; + if (need_newline_indented) { + print("\n"); + indent(); + need_newline_indented = false; + } else if (c.nlb && (i > 0 || !has_nlb())) { + print("\n"); + indent(); + } else if (i > 0 || !tail) { + space(); + } + if (/comment[134]/.test(c.type)) { + const value = filter_comment(c.value); + if (value) { + print("//" + value); + } + need_newline_indented = true; + } else if (c.type == "comment2") { + const value = filter_comment(c.value); + if (value) { + print("/*" + value + "*/"); + } + need_space = true; + } + }); + if (OUTPUT.length() > insert) newline_insert = insert; + } + + var stack = []; + return { + get : get, + toString : get, + indent : indent, + in_directive : false, + use_asm : null, + active_scope : null, + indentation : function() { return indentation; }, + current_width : function() { return current_col - indentation; }, + should_break : function() { return options.width && this.current_width() >= options.width; }, + has_parens : function() { return has_parens; }, + newline : newline, + print : print, + star : star, + space : space, + comma : comma, + colon : colon, + last : function() { return last; }, + semicolon : semicolon, + force_semicolon : force_semicolon, + to_utf8 : to_utf8, + print_name : function(name) { print(make_name(name)); }, + print_string : function(str, quote, escape_directive) { + var encoded = encode_string(str, quote); + if (escape_directive === true && !encoded.includes("\\")) { + // Insert semicolons to break directive prologue + if (!EXPECT_DIRECTIVE.test(OUTPUT.toString())) { + force_semicolon(); + } + force_semicolon(); + } + print(encoded); + }, + print_template_string_chars: function(str) { + var encoded = encode_string(str, "`").replace(/\${/g, "\\${"); + return print(encoded.substr(1, encoded.length - 2)); + }, + encode_string : encode_string, + next_indent : next_indent, + with_indent : with_indent, + with_block : with_block, + with_parens : with_parens, + with_square : with_square, + add_mapping : add_mapping, + option : function(opt) { return options[opt]; }, + printed_comments: printed_comments, + prepend_comments: readonly ? noop : prepend_comments, + append_comments : readonly || comment_filter === return_false ? noop : append_comments, + line : function() { return current_line; }, + col : function() { return current_col; }, + pos : function() { return current_pos; }, + push_node : function(node) { stack.push(node); }, + pop_node : function() { return stack.pop(); }, + parent : function(n) { + return stack[stack.length - 2 - (n || 0)]; + } + }; + +} + +/* -----[ code generators ]----- */ + +(function() { + + /* -----[ utils ]----- */ + + function DEFPRINT(nodetype, generator) { + nodetype.DEFMETHOD("_codegen", generator); + } + + AST_Node.DEFMETHOD("print", function(output, force_parens) { + var self = this, generator = self._codegen; + if (self instanceof AST_Scope) { + output.active_scope = self; + } else if (!output.use_asm && self instanceof AST_Directive && self.value == "use asm") { + output.use_asm = output.active_scope; + } + function doit() { + output.prepend_comments(self); + self.add_source_map(output); + generator(self, output); + output.append_comments(self); + } + output.push_node(self); + if (force_parens || self.needs_parens(output)) { + output.with_parens(doit); + } else { + doit(); + } + output.pop_node(); + if (self === output.use_asm) { + output.use_asm = null; + } + }); + AST_Node.DEFMETHOD("_print", AST_Node.prototype.print); + + AST_Node.DEFMETHOD("print_to_string", function(options) { + var output = OutputStream(options); + this.print(output); + return output.get(); + }); + + /* -----[ PARENTHESES ]----- */ + + function PARENS(nodetype, func) { + if (Array.isArray(nodetype)) { + nodetype.forEach(function(nodetype) { + PARENS(nodetype, func); + }); + } else { + nodetype.DEFMETHOD("needs_parens", func); + } + } + + PARENS(AST_Node, return_false); + + // a function expression needs parens around it when it's provably + // the first token to appear in a statement. + PARENS(AST_Function, function(output) { + if (!output.has_parens() && first_in_statement(output)) { + return true; + } + + if (output.option("webkit")) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + return true; + } + } + + if (output.option("wrap_iife")) { + var p = output.parent(); + if (p instanceof AST_Call && p.expression === this) { + return true; + } + } + + if (output.option("wrap_func_args")) { + var p = output.parent(); + if (p instanceof AST_Call && p.args.includes(this)) { + return true; + } + } + + return false; + }); + + PARENS(AST_Arrow, function(output) { + var p = output.parent(); + + if ( + output.option("wrap_func_args") + && p instanceof AST_Call + && p.args.includes(this) + ) { + return true; + } + return p instanceof AST_PropAccess && p.expression === this; + }); + + // same goes for an object literal (as in AST_Function), because + // otherwise {...} would be interpreted as a block of code. + PARENS(AST_Object, function(output) { + return !output.has_parens() && first_in_statement(output); + }); + + PARENS(AST_ClassExpression, first_in_statement); + + PARENS(AST_Unary, function(output) { + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this + || p instanceof AST_Binary + && p.operator === "**" + && this instanceof AST_UnaryPrefix + && p.left === this + && this.operator !== "++" + && this.operator !== "--"; + }); + + PARENS(AST_Await, function(output) { + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this + || p instanceof AST_Binary && p.operator === "**" && p.left === this + || output.option("safari10") && p instanceof AST_UnaryPrefix; + }); + + PARENS(AST_Sequence, function(output) { + var p = output.parent(); + return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) + || p instanceof AST_Unary // !(foo, bar, baz) + || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 + || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 + || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 + || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] + || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 + || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) + * ==> 20 (side effect, set a := 10 and b := 20) */ + || p instanceof AST_Arrow // x => (x, x) + || p instanceof AST_DefaultAssign // x => (x = (0, function(){})) + || p instanceof AST_Expansion // [...(a, b)] + || p instanceof AST_ForOf && this === p.object // for (e of (foo, bar)) {} + || p instanceof AST_Yield // yield (foo, bar) + || p instanceof AST_Export // export default (foo, bar) + ; + }); + + PARENS(AST_Binary, function(output) { + var p = output.parent(); + // (foo && bar)() + if (p instanceof AST_Call && p.expression === this) + return true; + // typeof (foo && bar) + if (p instanceof AST_Unary) + return true; + // (foo && bar)["prop"], (foo && bar).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // this deals with precedence: 3 * (2 + 1) + if (p instanceof AST_Binary) { + const po = p.operator; + const so = this.operator; + + if (so === "??" && (po === "||" || po === "&&")) { + return true; + } + + if (po === "??" && (so === "||" || so === "&&")) { + return true; + } + + const pp = PRECEDENCE[po]; + const sp = PRECEDENCE[so]; + if (pp > sp + || (pp == sp + && (this === p.right || po == "**"))) { + return true; + } + } + }); + + PARENS(AST_Yield, function(output) { + var p = output.parent(); + // (yield 1) + (yield 2) + // a = yield 3 + if (p instanceof AST_Binary && p.operator !== "=") + return true; + // (yield 1)() + // new (yield 1)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (yield 1) ? yield 2 : yield 3 + if (p instanceof AST_Conditional && p.condition === this) + return true; + // -(yield 4) + if (p instanceof AST_Unary) + return true; + // (yield x).foo + // (yield x)['foo'] + if (p instanceof AST_PropAccess && p.expression === this) + return true; + }); + + PARENS(AST_PropAccess, function(output) { + var p = output.parent(); + if (p instanceof AST_New && p.expression === this) { + // i.e. new (foo.bar().baz) + // + // if there's one call into this subtree, then we need + // parens around it too, otherwise the call will be + // interpreted as passing the arguments to the upper New + // expression. + return walk(this, node => { + if (node instanceof AST_Scope) return true; + if (node instanceof AST_Call) { + return walk_abort; // makes walk() return true. + } + }); + } + }); + + PARENS(AST_Call, function(output) { + var p = output.parent(), p1; + if (p instanceof AST_New && p.expression === this + || p instanceof AST_Export && p.is_default && this.expression instanceof AST_Function) + return true; + + // workaround for Safari bug. + // https://bugs.webkit.org/show_bug.cgi?id=123506 + return this.expression instanceof AST_Function + && p instanceof AST_PropAccess + && p.expression === this + && (p1 = output.parent(1)) instanceof AST_Assign + && p1.left === p; + }); + + PARENS(AST_New, function(output) { + var p = output.parent(); + if (this.args.length === 0 + && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() + || p instanceof AST_Call && p.expression === this + || p instanceof AST_PrefixedTemplateString && p.prefix === this)) // (new foo)(bar) + return true; + }); + + PARENS(AST_Number, function(output) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + var value = this.getValue(); + if (value < 0 || /^0/.test(make_num(value))) { + return true; + } + } + }); + + PARENS(AST_BigInt, function(output) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + var value = this.getValue(); + if (value.startsWith("-")) { + return true; + } + } + }); + + PARENS([ AST_Assign, AST_Conditional ], function(output) { + var p = output.parent(); + // !(a = false) → true + if (p instanceof AST_Unary) + return true; + // 1 + (a = 2) + 3 → 6, side effect setting a = 2 + if (p instanceof AST_Binary && !(p instanceof AST_Assign)) + return true; + // (a = func)() —or— new (a = Object)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (a = foo) ? bar : baz + if (p instanceof AST_Conditional && p.condition === this) + return true; + // (a = foo)["prop"] —or— (a = foo).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // ({a, b} = {a: 1, b: 2}), a destructuring assignment + if (this instanceof AST_Assign && this.left instanceof AST_Destructuring && this.left.is_array === false) + return true; + }); + + /* -----[ PRINTERS ]----- */ + + DEFPRINT(AST_Directive, function(self, output) { + output.print_string(self.value, self.quote); + output.semicolon(); + }); + + DEFPRINT(AST_Expansion, function (self, output) { + output.print("..."); + self.expression.print(output); + }); + + DEFPRINT(AST_Destructuring, function (self, output) { + output.print(self.is_array ? "[" : "{"); + var len = self.names.length; + self.names.forEach(function (name, i) { + if (i > 0) output.comma(); + name.print(output); + // If the final element is a hole, we need to make sure it + // doesn't look like a trailing comma, by inserting an actual + // trailing comma. + if (i == len - 1 && name instanceof AST_Hole) output.comma(); + }); + output.print(self.is_array ? "]" : "}"); + }); + + DEFPRINT(AST_Debugger, function(self, output) { + output.print("debugger"); + output.semicolon(); + }); + + /* -----[ statements ]----- */ + + function display_body(body, is_toplevel, output, allow_directives) { + var last = body.length - 1; + output.in_directive = allow_directives; + body.forEach(function(stmt, i) { + if (output.in_directive === true && !(stmt instanceof AST_Directive || + stmt instanceof AST_EmptyStatement || + (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String) + )) { + output.in_directive = false; + } + if (!(stmt instanceof AST_EmptyStatement)) { + output.indent(); + stmt.print(output); + if (!(i == last && is_toplevel)) { + output.newline(); + if (is_toplevel) output.newline(); + } + } + if (output.in_directive === true && + stmt instanceof AST_SimpleStatement && + stmt.body instanceof AST_String + ) { + output.in_directive = false; + } + }); + output.in_directive = false; + } + + AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output) { + force_statement(this.body, output); + }); + + DEFPRINT(AST_Statement, function(self, output) { + self.body.print(output); + output.semicolon(); + }); + DEFPRINT(AST_Toplevel, function(self, output) { + display_body(self.body, true, output, true); + output.print(""); + }); + DEFPRINT(AST_LabeledStatement, function(self, output) { + self.label.print(output); + output.colon(); + self.body.print(output); + }); + DEFPRINT(AST_SimpleStatement, function(self, output) { + self.body.print(output); + output.semicolon(); + }); + function print_braced_empty(self, output) { + output.print("{"); + output.with_indent(output.next_indent(), function() { + output.append_comments(self, true); + }); + output.print("}"); + } + function print_braced(self, output, allow_directives) { + if (self.body.length > 0) { + output.with_block(function() { + display_body(self.body, false, output, allow_directives); + }); + } else print_braced_empty(self, output); + } + DEFPRINT(AST_BlockStatement, function(self, output) { + print_braced(self, output); + }); + DEFPRINT(AST_EmptyStatement, function(self, output) { + output.semicolon(); + }); + DEFPRINT(AST_Do, function(self, output) { + output.print("do"); + output.space(); + make_block(self.body, output); + output.space(); + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.semicolon(); + }); + DEFPRINT(AST_While, function(self, output) { + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_For, function(self, output) { + output.print("for"); + output.space(); + output.with_parens(function() { + if (self.init) { + if (self.init instanceof AST_Definitions) { + self.init.print(output); + } else { + parenthesize_for_noin(self.init, output, true); + } + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.condition) { + self.condition.print(output); + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.step) { + self.step.print(output); + } + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_ForIn, function(self, output) { + output.print("for"); + if (self.await) { + output.space(); + output.print("await"); + } + output.space(); + output.with_parens(function() { + self.init.print(output); + output.space(); + output.print(self instanceof AST_ForOf ? "of" : "in"); + output.space(); + self.object.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_With, function(self, output) { + output.print("with"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + output.space(); + self._do_print_body(output); + }); + + /* -----[ functions ]----- */ + AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword) { + var self = this; + if (!nokeyword) { + if (self.async) { + output.print("async"); + output.space(); + } + output.print("function"); + if (self.is_generator) { + output.star(); + } + if (self.name) { + output.space(); + } + } + if (self.name instanceof AST_Symbol) { + self.name.print(output); + } else if (nokeyword && self.name instanceof AST_Node) { + output.with_square(function() { + self.name.print(output); // Computed method name + }); + } + output.with_parens(function() { + self.argnames.forEach(function(arg, i) { + if (i) output.comma(); + arg.print(output); + }); + }); + output.space(); + print_braced(self, output, true); + }); + DEFPRINT(AST_Lambda, function(self, output) { + self._do_print(output); + }); + + DEFPRINT(AST_PrefixedTemplateString, function(self, output) { + var tag = self.prefix; + var parenthesize_tag = tag instanceof AST_Lambda + || tag instanceof AST_Binary + || tag instanceof AST_Conditional + || tag instanceof AST_Sequence + || tag instanceof AST_Unary + || tag instanceof AST_Dot && tag.expression instanceof AST_Object; + if (parenthesize_tag) output.print("("); + self.prefix.print(output); + if (parenthesize_tag) output.print(")"); + self.template_string.print(output); + }); + DEFPRINT(AST_TemplateString, function(self, output) { + var is_tagged = output.parent() instanceof AST_PrefixedTemplateString; + + output.print("`"); + for (var i = 0; i < self.segments.length; i++) { + if (!(self.segments[i] instanceof AST_TemplateSegment)) { + output.print("${"); + self.segments[i].print(output); + output.print("}"); + } else if (is_tagged) { + output.print(self.segments[i].raw); + } else { + output.print_template_string_chars(self.segments[i].value); + } + } + output.print("`"); + }); + DEFPRINT(AST_TemplateSegment, function(self, output) { + output.print_template_string_chars(self.value); + }); + + AST_Arrow.DEFMETHOD("_do_print", function(output) { + var self = this; + var parent = output.parent(); + var needs_parens = (parent instanceof AST_Binary && !(parent instanceof AST_Assign)) || + parent instanceof AST_Unary || + (parent instanceof AST_Call && self === parent.expression); + if (needs_parens) { output.print("("); } + if (self.async) { + output.print("async"); + output.space(); + } + if (self.argnames.length === 1 && self.argnames[0] instanceof AST_Symbol) { + self.argnames[0].print(output); + } else { + output.with_parens(function() { + self.argnames.forEach(function(arg, i) { + if (i) output.comma(); + arg.print(output); + }); + }); + } + output.space(); + output.print("=>"); + output.space(); + const first_statement = self.body[0]; + if ( + self.body.length === 1 + && first_statement instanceof AST_Return + ) { + const returned = first_statement.value; + if (!returned) { + output.print("{}"); + } else if (left_is_object(returned)) { + output.print("("); + returned.print(output); + output.print(")"); + } else { + returned.print(output); + } + } else { + print_braced(self, output); + } + if (needs_parens) { output.print(")"); } + }); + + /* -----[ exits ]----- */ + AST_Exit.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + if (this.value) { + output.space(); + const comments = this.value.start.comments_before; + if (comments && comments.length && !output.printed_comments.has(comments)) { + output.print("("); + this.value.print(output); + output.print(")"); + } else { + this.value.print(output); + } + } + output.semicolon(); + }); + DEFPRINT(AST_Return, function(self, output) { + self._do_print(output, "return"); + }); + DEFPRINT(AST_Throw, function(self, output) { + self._do_print(output, "throw"); + }); + + /* -----[ yield ]----- */ + + DEFPRINT(AST_Yield, function(self, output) { + var star = self.is_star ? "*" : ""; + output.print("yield" + star); + if (self.expression) { + output.space(); + self.expression.print(output); + } + }); + + DEFPRINT(AST_Await, function(self, output) { + output.print("await"); + output.space(); + var e = self.expression; + var parens = !( + e instanceof AST_Call + || e instanceof AST_SymbolRef + || e instanceof AST_PropAccess + || e instanceof AST_Unary + || e instanceof AST_Constant + || e instanceof AST_Await + || e instanceof AST_Object + ); + if (parens) output.print("("); + self.expression.print(output); + if (parens) output.print(")"); + }); + + /* -----[ loop control ]----- */ + AST_LoopControl.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + if (this.label) { + output.space(); + this.label.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Break, function(self, output) { + self._do_print(output, "break"); + }); + DEFPRINT(AST_Continue, function(self, output) { + self._do_print(output, "continue"); + }); + + /* -----[ if ]----- */ + function make_then(self, output) { + var b = self.body; + if (output.option("braces") + || output.option("ie8") && b instanceof AST_Do) + return make_block(b, output); + // The squeezer replaces "block"-s that contain only a single + // statement with the statement itself; technically, the AST + // is correct, but this can create problems when we output an + // IF having an ELSE clause where the THEN clause ends in an + // IF *without* an ELSE block (then the outer ELSE would refer + // to the inner IF). This function checks for this case and + // adds the block braces if needed. + if (!b) return output.force_semicolon(); + while (true) { + if (b instanceof AST_If) { + if (!b.alternative) { + make_block(self.body, output); + return; + } + b = b.alternative; + } else if (b instanceof AST_StatementWithBody) { + b = b.body; + } else break; + } + force_statement(self.body, output); + } + DEFPRINT(AST_If, function(self, output) { + output.print("if"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.space(); + if (self.alternative) { + make_then(self, output); + output.space(); + output.print("else"); + output.space(); + if (self.alternative instanceof AST_If) + self.alternative.print(output); + else + force_statement(self.alternative, output); + } else { + self._do_print_body(output); + } + }); + + /* -----[ switch ]----- */ + DEFPRINT(AST_Switch, function(self, output) { + output.print("switch"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + output.space(); + var last = self.body.length - 1; + if (last < 0) print_braced_empty(self, output); + else output.with_block(function() { + self.body.forEach(function(branch, i) { + output.indent(true); + branch.print(output); + if (i < last && branch.body.length > 0) + output.newline(); + }); + }); + }); + AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output) { + output.newline(); + this.body.forEach(function(stmt) { + output.indent(); + stmt.print(output); + output.newline(); + }); + }); + DEFPRINT(AST_Default, function(self, output) { + output.print("default:"); + self._do_print_body(output); + }); + DEFPRINT(AST_Case, function(self, output) { + output.print("case"); + output.space(); + self.expression.print(output); + output.print(":"); + self._do_print_body(output); + }); + + /* -----[ exceptions ]----- */ + DEFPRINT(AST_Try, function(self, output) { + output.print("try"); + output.space(); + print_braced(self, output); + if (self.bcatch) { + output.space(); + self.bcatch.print(output); + } + if (self.bfinally) { + output.space(); + self.bfinally.print(output); + } + }); + DEFPRINT(AST_Catch, function(self, output) { + output.print("catch"); + if (self.argname) { + output.space(); + output.with_parens(function() { + self.argname.print(output); + }); + } + output.space(); + print_braced(self, output); + }); + DEFPRINT(AST_Finally, function(self, output) { + output.print("finally"); + output.space(); + print_braced(self, output); + }); + + /* -----[ var/const ]----- */ + AST_Definitions.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + output.space(); + this.definitions.forEach(function(def, i) { + if (i) output.comma(); + def.print(output); + }); + var p = output.parent(); + var in_for = p instanceof AST_For || p instanceof AST_ForIn; + var output_semicolon = !in_for || p && p.init !== this; + if (output_semicolon) + output.semicolon(); + }); + DEFPRINT(AST_Let, function(self, output) { + self._do_print(output, "let"); + }); + DEFPRINT(AST_Var, function(self, output) { + self._do_print(output, "var"); + }); + DEFPRINT(AST_Const, function(self, output) { + self._do_print(output, "const"); + }); + DEFPRINT(AST_Import, function(self, output) { + output.print("import"); + output.space(); + if (self.imported_name) { + self.imported_name.print(output); + } + if (self.imported_name && self.imported_names) { + output.print(","); + output.space(); + } + if (self.imported_names) { + if (self.imported_names.length === 1 && self.imported_names[0].foreign_name.name === "*") { + self.imported_names[0].print(output); + } else { + output.print("{"); + self.imported_names.forEach(function (name_import, i) { + output.space(); + name_import.print(output); + if (i < self.imported_names.length - 1) { + output.print(","); + } + }); + output.space(); + output.print("}"); + } + } + if (self.imported_name || self.imported_names) { + output.space(); + output.print("from"); + output.space(); + } + self.module_name.print(output); + if (self.assert_clause) { + output.print("assert"); + self.assert_clause.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_ImportMeta, function(self, output) { + output.print("import.meta"); + }); + + DEFPRINT(AST_NameMapping, function(self, output) { + var is_import = output.parent() instanceof AST_Import; + var definition = self.name.definition(); + var names_are_different = + (definition && definition.mangled_name || self.name.name) !== + self.foreign_name.name; + if (names_are_different) { + if (is_import) { + output.print(self.foreign_name.name); + } else { + self.name.print(output); + } + output.space(); + output.print("as"); + output.space(); + if (is_import) { + self.name.print(output); + } else { + output.print(self.foreign_name.name); + } + } else { + self.name.print(output); + } + }); + + DEFPRINT(AST_Export, function(self, output) { + output.print("export"); + output.space(); + if (self.is_default) { + output.print("default"); + output.space(); + } + if (self.exported_names) { + if (self.exported_names.length === 1 && self.exported_names[0].name.name === "*") { + self.exported_names[0].print(output); + } else { + output.print("{"); + self.exported_names.forEach(function(name_export, i) { + output.space(); + name_export.print(output); + if (i < self.exported_names.length - 1) { + output.print(","); + } + }); + output.space(); + output.print("}"); + } + } else if (self.exported_value) { + self.exported_value.print(output); + } else if (self.exported_definition) { + self.exported_definition.print(output); + if (self.exported_definition instanceof AST_Definitions) return; + } + if (self.module_name) { + output.space(); + output.print("from"); + output.space(); + self.module_name.print(output); + } + if (self.assert_clause) { + output.print("assert"); + self.assert_clause.print(output); + } + if (self.exported_value + && !(self.exported_value instanceof AST_Defun || + self.exported_value instanceof AST_Function || + self.exported_value instanceof AST_Class) + || self.module_name + || self.exported_names + ) { + output.semicolon(); + } + }); + + function parenthesize_for_noin(node, output, noin) { + var parens = false; + // need to take some precautions here: + // https://github.com/mishoo/UglifyJS2/issues/60 + if (noin) { + parens = walk(node, node => { + // Don't go into scopes -- except arrow functions: + // https://github.com/terser/terser/issues/1019#issuecomment-877642607 + if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) { + return true; + } + if (node instanceof AST_Binary && node.operator == "in") { + return walk_abort; // makes walk() return true + } + }); + } + node.print(output, parens); + } + + DEFPRINT(AST_VarDef, function(self, output) { + self.name.print(output); + if (self.value) { + output.space(); + output.print("="); + output.space(); + var p = output.parent(1); + var noin = p instanceof AST_For || p instanceof AST_ForIn; + parenthesize_for_noin(self.value, output, noin); + } + }); + + /* -----[ other expressions ]----- */ + DEFPRINT(AST_Call, function(self, output) { + self.expression.print(output); + if (self instanceof AST_New && self.args.length === 0) + return; + if (self.expression instanceof AST_Call || self.expression instanceof AST_Lambda) { + output.add_mapping(self.start); + } + if (self.optional) output.print("?."); + output.with_parens(function() { + self.args.forEach(function(expr, i) { + if (i) output.comma(); + expr.print(output); + }); + }); + }); + DEFPRINT(AST_New, function(self, output) { + output.print("new"); + output.space(); + AST_Call.prototype._codegen(self, output); + }); + + AST_Sequence.DEFMETHOD("_do_print", function(output) { + this.expressions.forEach(function(node, index) { + if (index > 0) { + output.comma(); + if (output.should_break()) { + output.newline(); + output.indent(); + } + } + node.print(output); + }); + }); + DEFPRINT(AST_Sequence, function(self, output) { + self._do_print(output); + // var p = output.parent(); + // if (p instanceof AST_Statement) { + // output.with_indent(output.next_indent(), function(){ + // self._do_print(output); + // }); + // } else { + // self._do_print(output); + // } + }); + DEFPRINT(AST_Dot, function(self, output) { + var expr = self.expression; + expr.print(output); + var prop = self.property; + var print_computed = ALL_RESERVED_WORDS.has(prop) + ? output.option("ie8") + : !is_identifier_string( + prop, + output.option("ecma") >= 2015 || output.option("safari10") + ); + + if (self.optional) output.print("?."); + + if (print_computed) { + output.print("["); + output.add_mapping(self.end); + output.print_string(prop); + output.print("]"); + } else { + if (expr instanceof AST_Number && expr.getValue() >= 0) { + if (!/[xa-f.)]/i.test(output.last())) { + output.print("."); + } + } + if (!self.optional) output.print("."); + // the name after dot would be mapped about here. + output.add_mapping(self.end); + output.print_name(prop); + } + }); + DEFPRINT(AST_DotHash, function(self, output) { + var expr = self.expression; + expr.print(output); + var prop = self.property; + + if (self.optional) output.print("?"); + output.print(".#"); + output.add_mapping(self.end); + output.print_name(prop); + }); + DEFPRINT(AST_Sub, function(self, output) { + self.expression.print(output); + if (self.optional) output.print("?."); + output.print("["); + self.property.print(output); + output.print("]"); + }); + DEFPRINT(AST_Chain, function(self, output) { + self.expression.print(output); + }); + DEFPRINT(AST_UnaryPrefix, function(self, output) { + var op = self.operator; + output.print(op); + if (/^[a-z]/i.test(op) + || (/[+-]$/.test(op) + && self.expression instanceof AST_UnaryPrefix + && /^[+-]/.test(self.expression.operator))) { + output.space(); + } + self.expression.print(output); + }); + DEFPRINT(AST_UnaryPostfix, function(self, output) { + self.expression.print(output); + output.print(self.operator); + }); + DEFPRINT(AST_Binary, function(self, output) { + var op = self.operator; + self.left.print(output); + if (op[0] == ">" /* ">>" ">>>" ">" ">=" */ + && self.left instanceof AST_UnaryPostfix + && self.left.operator == "--") { + // space is mandatory to avoid outputting --> + output.print(" "); + } else { + // the space is optional depending on "beautify" + output.space(); + } + output.print(op); + if ((op == "<" || op == "<<") + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "!" + && self.right.expression instanceof AST_UnaryPrefix + && self.right.expression.operator == "--") { + // space is mandatory to avoid outputting ") && S.newline_before) { + forward(3); + skip_line_comment("comment4"); + continue; + } + } + var ch = peek(); + if (!ch) return token("eof"); + var code = ch.charCodeAt(0); + switch (code) { + case 34: case 39: return read_string(); + case 46: return handle_dot(); + case 47: { + var tok = handle_slash(); + if (tok === next_token) continue; + return tok; + } + case 61: return handle_eq_sign(); + case 63: { + if (!is_option_chain_op()) break; // Handled below + + next(); // ? + next(); // . + + return token("punc", "?."); + } + case 96: return read_template_characters(true); + case 123: + S.brace_counter++; + break; + case 125: + S.brace_counter--; + if (S.template_braces.length > 0 + && S.template_braces[S.template_braces.length - 1] === S.brace_counter) + return read_template_characters(false); + break; + } + if (is_digit(code)) return read_num(); + if (PUNC_CHARS.has(ch)) return token("punc", next()); + if (OPERATOR_CHARS.has(ch)) return read_operator(); + if (code == 92 || is_identifier_start(ch)) return read_word(); + if (code == 35) return read_private_word(); + break; + } + parse_error("Unexpected character '" + ch + "'"); + } + + next_token.next = next; + next_token.peek = peek; + + next_token.context = function(nc) { + if (nc) S = nc; + return S; + }; + + next_token.add_directive = function(directive) { + S.directive_stack[S.directive_stack.length - 1].push(directive); + + if (S.directives[directive] === undefined) { + S.directives[directive] = 1; + } else { + S.directives[directive]++; + } + }; + + next_token.push_directives_stack = function() { + S.directive_stack.push([]); + }; + + next_token.pop_directives_stack = function() { + var directives = S.directive_stack[S.directive_stack.length - 1]; + + for (var i = 0; i < directives.length; i++) { + S.directives[directives[i]]--; + } + + S.directive_stack.pop(); + }; + + next_token.has_directive = function(directive) { + return S.directives[directive] > 0; + }; + + return next_token; + +} + +/* -----[ Parser (constants) ]----- */ + +var UNARY_PREFIX = makePredicate([ + "typeof", + "void", + "delete", + "--", + "++", + "!", + "~", + "-", + "+" +]); + +var UNARY_POSTFIX = makePredicate([ "--", "++" ]); + +var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "??=", "&&=", "||=", "/=", "*=", "**=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); + +var LOGICAL_ASSIGNMENT = makePredicate([ "??=", "&&=", "||=" ]); + +var PRECEDENCE = (function(a, ret) { + for (var i = 0; i < a.length; ++i) { + var b = a[i]; + for (var j = 0; j < b.length; ++j) { + ret[b[j]] = i + 1; + } + } + return ret; +})( + [ + ["||"], + ["??"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"], + ["**"] + ], + {} +); + +var ATOMIC_START_TOKEN = makePredicate([ "atom", "num", "big_int", "string", "regexp", "name" ]); + +/* -----[ Parser ]----- */ + +function parse($TEXT, options) { + // maps start tokens to count of comments found outside of their parens + // Example: /* I count */ ( /* I don't */ foo() ) + // Useful because comments_before property of call with parens outside + // contains both comments inside and outside these parens. Used to find the + // right #__PURE__ comments for an expression + const outer_comments_before_counts = new WeakMap(); + + options = defaults(options, { + bare_returns : false, + ecma : null, // Legacy + expression : false, + filename : null, + html5_comments : true, + module : false, + shebang : true, + strict : false, + toplevel : null, + }, true); + + var S = { + input : (typeof $TEXT == "string" + ? tokenizer($TEXT, options.filename, + options.html5_comments, options.shebang) + : $TEXT), + token : null, + prev : null, + peeked : null, + in_function : 0, + in_async : -1, + in_generator : -1, + in_directives : true, + in_loop : 0, + labels : [] + }; + + S.token = next(); + + function is(type, value) { + return is_token(S.token, type, value); + } + + function peek() { return S.peeked || (S.peeked = S.input()); } + + function next() { + S.prev = S.token; + + if (!S.peeked) peek(); + S.token = S.peeked; + S.peeked = null; + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + } + + function prev() { + return S.prev; + } + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + ctx.filename, + line != null ? line : ctx.tokline, + col != null ? col : ctx.tokcol, + pos != null ? pos : ctx.tokpos); + } + + function token_error(token, msg) { + croak(msg, token.line, token.col); + } + + function unexpected(token) { + if (token == null) + token = S.token; + token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); + } + + function expect_token(type, val) { + if (is(type, val)) { + return next(); + } + token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); + } + + function expect(punc) { return expect_token("punc", punc); } + + function has_newline_before(token) { + return token.nlb || !token.comments_before.every((comment) => !comment.nlb); + } + + function can_insert_semicolon() { + return !options.strict + && (is("eof") || is("punc", "}") || has_newline_before(S.token)); + } + + function is_in_generator() { + return S.in_generator === S.in_function; + } + + function is_in_async() { + return S.in_async === S.in_function; + } + + function can_await() { + return ( + S.in_async === S.in_function + || S.in_function === 0 && S.input.has_directive("use strict") + ); + } + + function semicolon(optional) { + if (is("punc", ";")) next(); + else if (!optional && !can_insert_semicolon()) unexpected(); + } + + function parenthesised() { + expect("("); + var exp = expression(true); + expect(")"); + return exp; + } + + function embed_tokens(parser) { + return function _embed_tokens_wrapper(...args) { + const start = S.token; + const expr = parser(...args); + expr.start = start; + expr.end = prev(); + return expr; + }; + } + + function handle_regexp() { + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + } + + var statement = embed_tokens(function statement(is_export_default, is_for_body, is_if_body) { + handle_regexp(); + switch (S.token.type) { + case "string": + if (S.in_directives) { + var token = peek(); + if (!LATEST_RAW.includes("\\") + && (is_token(token, "punc", ";") + || is_token(token, "punc", "}") + || has_newline_before(token) + || is_token(token, "eof"))) { + S.input.add_directive(S.token.value); + } else { + S.in_directives = false; + } + } + var dir = S.in_directives, stat = simple_statement(); + return dir && stat.body instanceof AST_String ? new AST_Directive(stat.body) : stat; + case "template_head": + case "num": + case "big_int": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + if (S.token.value == "async" && is_token(peek(), "keyword", "function")) { + next(); + next(); + if (is_for_body) { + croak("functions are not allowed as the body of a loop"); + } + return function_(AST_Defun, false, true, is_export_default); + } + if (S.token.value == "import" && !is_token(peek(), "punc", "(") && !is_token(peek(), "punc", ".")) { + next(); + var node = import_statement(); + semicolon(); + return node; + } + return is_token(peek(), "punc", ":") + ? labeled_statement() + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return new AST_BlockStatement({ + start : S.token, + body : block_(), + end : prev() + }); + case "[": + case "(": + return simple_statement(); + case ";": + S.in_directives = false; + next(); + return new AST_EmptyStatement(); + default: + unexpected(); + } + + case "keyword": + switch (S.token.value) { + case "break": + next(); + return break_cont(AST_Break); + + case "continue": + next(); + return break_cont(AST_Continue); + + case "debugger": + next(); + semicolon(); + return new AST_Debugger(); + + case "do": + next(); + var body = in_loop(statement); + expect_token("keyword", "while"); + var condition = parenthesised(); + semicolon(true); + return new AST_Do({ + body : body, + condition : condition + }); + + case "while": + next(); + return new AST_While({ + condition : parenthesised(), + body : in_loop(function() { return statement(false, true); }) + }); + + case "for": + next(); + return for_(); + + case "class": + next(); + if (is_for_body) { + croak("classes are not allowed as the body of a loop"); + } + if (is_if_body) { + croak("classes are not allowed as the body of an if"); + } + return class_(AST_DefClass, is_export_default); + + case "function": + next(); + if (is_for_body) { + croak("functions are not allowed as the body of a loop"); + } + return function_(AST_Defun, false, false, is_export_default); + + case "if": + next(); + return if_(); + + case "return": + if (S.in_function == 0 && !options.bare_returns) + croak("'return' outside of function"); + next(); + var value = null; + if (is("punc", ";")) { + next(); + } else if (!can_insert_semicolon()) { + value = expression(true); + semicolon(); + } + return new AST_Return({ + value: value + }); + + case "switch": + next(); + return new AST_Switch({ + expression : parenthesised(), + body : in_loop(switch_body_) + }); + + case "throw": + next(); + if (has_newline_before(S.token)) + croak("Illegal newline after 'throw'"); + var value = expression(true); + semicolon(); + return new AST_Throw({ + value: value + }); + + case "try": + next(); + return try_(); + + case "var": + next(); + var node = var_(); + semicolon(); + return node; + + case "let": + next(); + var node = let_(); + semicolon(); + return node; + + case "const": + next(); + var node = const_(); + semicolon(); + return node; + + case "with": + if (S.input.has_directive("use strict")) { + croak("Strict mode may not include a with statement"); + } + next(); + return new AST_With({ + expression : parenthesised(), + body : statement() + }); + + case "export": + if (!is_token(peek(), "punc", "(")) { + next(); + var node = export_statement(); + if (is("punc", ";")) semicolon(); + return node; + } + } + } + unexpected(); + }); + + function labeled_statement() { + var label = as_symbol(AST_Label); + if (label.name === "await" && is_in_async()) { + token_error(S.prev, "await cannot be used as label inside async function"); + } + if (S.labels.some((l) => l.name === label.name)) { + // ECMA-262, 12.12: An ECMAScript program is considered + // syntactically incorrect if it contains a + // LabelledStatement that is enclosed by a + // LabelledStatement with the same Identifier as label. + croak("Label " + label.name + " defined twice"); + } + expect(":"); + S.labels.push(label); + var stat = statement(); + S.labels.pop(); + if (!(stat instanceof AST_IterationStatement)) { + // check for `continue` that refers to this label. + // those should be reported as syntax errors. + // https://github.com/mishoo/UglifyJS2/issues/287 + label.references.forEach(function(ref) { + if (ref instanceof AST_Continue) { + ref = ref.label.start; + croak("Continue label `" + label.name + "` refers to non-IterationStatement.", + ref.line, ref.col, ref.pos); + } + }); + } + return new AST_LabeledStatement({ body: stat, label: label }); + } + + function simple_statement(tmp) { + return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); + } + + function break_cont(type) { + var label = null, ldef; + if (!can_insert_semicolon()) { + label = as_symbol(AST_LabelRef, true); + } + if (label != null) { + ldef = S.labels.find((l) => l.name === label.name); + if (!ldef) + croak("Undefined label " + label.name); + label.thedef = ldef; + } else if (S.in_loop == 0) + croak(type.TYPE + " not inside a loop or switch"); + semicolon(); + var stat = new type({ label: label }); + if (ldef) ldef.references.push(stat); + return stat; + } + + function for_() { + var for_await_error = "`for await` invalid in this context"; + var await_tok = S.token; + if (await_tok.type == "name" && await_tok.value == "await") { + if (!can_await()) { + token_error(await_tok, for_await_error); + } + next(); + } else { + await_tok = false; + } + expect("("); + var init = null; + if (!is("punc", ";")) { + init = + is("keyword", "var") ? (next(), var_(true)) : + is("keyword", "let") ? (next(), let_(true)) : + is("keyword", "const") ? (next(), const_(true)) : + expression(true, true); + var is_in = is("operator", "in"); + var is_of = is("name", "of"); + if (await_tok && !is_of) { + token_error(await_tok, for_await_error); + } + if (is_in || is_of) { + if (init instanceof AST_Definitions) { + if (init.definitions.length > 1) + token_error(init.start, "Only one variable declaration allowed in for..in loop"); + } else if (!(is_assignable(init) || (init = to_destructuring(init)) instanceof AST_Destructuring)) { + token_error(init.start, "Invalid left-hand side in for..in loop"); + } + next(); + if (is_in) { + return for_in(init); + } else { + return for_of(init, !!await_tok); + } + } + } else if (await_tok) { + token_error(await_tok, for_await_error); + } + return regular_for(init); + } + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(true); + expect(";"); + var step = is("punc", ")") ? null : expression(true); + expect(")"); + return new AST_For({ + init : init, + condition : test, + step : step, + body : in_loop(function() { return statement(false, true); }) + }); + } + + function for_of(init, is_await) { + var lhs = init instanceof AST_Definitions ? init.definitions[0].name : null; + var obj = expression(true); + expect(")"); + return new AST_ForOf({ + await : is_await, + init : init, + name : lhs, + object : obj, + body : in_loop(function() { return statement(false, true); }) + }); + } + + function for_in(init) { + var obj = expression(true); + expect(")"); + return new AST_ForIn({ + init : init, + object : obj, + body : in_loop(function() { return statement(false, true); }) + }); + } + + var arrow_function = function(start, argnames, is_async) { + if (has_newline_before(S.token)) { + croak("Unexpected newline before arrow (=>)"); + } + + expect_token("arrow", "=>"); + + var body = _function_body(is("punc", "{"), false, is_async); + + var end = + body instanceof Array && body.length ? body[body.length - 1].end : + body instanceof Array ? start : + body.end; + + return new AST_Arrow({ + start : start, + end : end, + async : is_async, + argnames : argnames, + body : body + }); + }; + + var function_ = function(ctor, is_generator_property, is_async, is_export_default) { + var in_statement = ctor === AST_Defun; + var is_generator = is("operator", "*"); + if (is_generator) { + next(); + } + + var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null; + if (in_statement && !name) { + if (is_export_default) { + ctor = AST_Function; + } else { + unexpected(); + } + } + + if (name && ctor !== AST_Accessor && !(name instanceof AST_SymbolDeclaration)) + unexpected(prev()); + + var args = []; + var body = _function_body(true, is_generator || is_generator_property, is_async, name, args); + return new ctor({ + start : args.start, + end : body.end, + is_generator: is_generator, + async : is_async, + name : name, + argnames: args, + body : body + }); + }; + + function track_used_binding_identifiers(is_parameter, strict) { + var parameters = new Set(); + var duplicate = false; + var default_assignment = false; + var spread = false; + var strict_mode = !!strict; + var tracker = { + add_parameter: function(token) { + if (parameters.has(token.value)) { + if (duplicate === false) { + duplicate = token; + } + tracker.check_strict(); + } else { + parameters.add(token.value); + if (is_parameter) { + switch (token.value) { + case "arguments": + case "eval": + case "yield": + if (strict_mode) { + token_error(token, "Unexpected " + token.value + " identifier as parameter inside strict mode"); + } + break; + default: + if (RESERVED_WORDS.has(token.value)) { + unexpected(); + } + } + } + } + }, + mark_default_assignment: function(token) { + if (default_assignment === false) { + default_assignment = token; + } + }, + mark_spread: function(token) { + if (spread === false) { + spread = token; + } + }, + mark_strict_mode: function() { + strict_mode = true; + }, + is_strict: function() { + return default_assignment !== false || spread !== false || strict_mode; + }, + check_strict: function() { + if (tracker.is_strict() && duplicate !== false) { + token_error(duplicate, "Parameter " + duplicate.value + " was used already"); + } + } + }; + + return tracker; + } + + function parameters(params) { + var used_parameters = track_used_binding_identifiers(true, S.input.has_directive("use strict")); + + expect("("); + + while (!is("punc", ")")) { + var param = parameter(used_parameters); + params.push(param); + + if (!is("punc", ")")) { + expect(","); + } + + if (param instanceof AST_Expansion) { + break; + } + } + + next(); + } + + function parameter(used_parameters, symbol_type) { + var param; + var expand = false; + if (used_parameters === undefined) { + used_parameters = track_used_binding_identifiers(true, S.input.has_directive("use strict")); + } + if (is("expand", "...")) { + expand = S.token; + used_parameters.mark_spread(S.token); + next(); + } + param = binding_element(used_parameters, symbol_type); + + if (is("operator", "=") && expand === false) { + used_parameters.mark_default_assignment(S.token); + next(); + param = new AST_DefaultAssign({ + start: param.start, + left: param, + operator: "=", + right: expression(false), + end: S.token + }); + } + + if (expand !== false) { + if (!is("punc", ")")) { + unexpected(); + } + param = new AST_Expansion({ + start: expand, + expression: param, + end: expand + }); + } + used_parameters.check_strict(); + + return param; + } + + function binding_element(used_parameters, symbol_type) { + var elements = []; + var first = true; + var is_expand = false; + var expand_token; + var first_token = S.token; + if (used_parameters === undefined) { + used_parameters = track_used_binding_identifiers(false, S.input.has_directive("use strict")); + } + symbol_type = symbol_type === undefined ? AST_SymbolFunarg : symbol_type; + if (is("punc", "[")) { + next(); + while (!is("punc", "]")) { + if (first) { + first = false; + } else { + expect(","); + } + + if (is("expand", "...")) { + is_expand = true; + expand_token = S.token; + used_parameters.mark_spread(S.token); + next(); + } + if (is("punc")) { + switch (S.token.value) { + case ",": + elements.push(new AST_Hole({ + start: S.token, + end: S.token + })); + continue; + case "]": // Trailing comma after last element + break; + case "[": + case "{": + elements.push(binding_element(used_parameters, symbol_type)); + break; + default: + unexpected(); + } + } else if (is("name")) { + used_parameters.add_parameter(S.token); + elements.push(as_symbol(symbol_type)); + } else { + croak("Invalid function parameter"); + } + if (is("operator", "=") && is_expand === false) { + used_parameters.mark_default_assignment(S.token); + next(); + elements[elements.length - 1] = new AST_DefaultAssign({ + start: elements[elements.length - 1].start, + left: elements[elements.length - 1], + operator: "=", + right: expression(false), + end: S.token + }); + } + if (is_expand) { + if (!is("punc", "]")) { + croak("Rest element must be last element"); + } + elements[elements.length - 1] = new AST_Expansion({ + start: expand_token, + expression: elements[elements.length - 1], + end: expand_token + }); + } + } + expect("]"); + used_parameters.check_strict(); + return new AST_Destructuring({ + start: first_token, + names: elements, + is_array: true, + end: prev() + }); + } else if (is("punc", "{")) { + next(); + while (!is("punc", "}")) { + if (first) { + first = false; + } else { + expect(","); + } + if (is("expand", "...")) { + is_expand = true; + expand_token = S.token; + used_parameters.mark_spread(S.token); + next(); + } + if (is("name") && (is_token(peek(), "punc") || is_token(peek(), "operator")) && [",", "}", "="].includes(peek().value)) { + used_parameters.add_parameter(S.token); + var start = prev(); + var value = as_symbol(symbol_type); + if (is_expand) { + elements.push(new AST_Expansion({ + start: expand_token, + expression: value, + end: value.end, + })); + } else { + elements.push(new AST_ObjectKeyVal({ + start: start, + key: value.name, + value: value, + end: value.end, + })); + } + } else if (is("punc", "}")) { + continue; // Allow trailing hole + } else { + var property_token = S.token; + var property = as_property_name(); + if (property === null) { + unexpected(prev()); + } else if (prev().type === "name" && !is("punc", ":")) { + elements.push(new AST_ObjectKeyVal({ + start: prev(), + key: property, + value: new symbol_type({ + start: prev(), + name: property, + end: prev() + }), + end: prev() + })); + } else { + expect(":"); + elements.push(new AST_ObjectKeyVal({ + start: property_token, + quote: property_token.quote, + key: property, + value: binding_element(used_parameters, symbol_type), + end: prev() + })); + } + } + if (is_expand) { + if (!is("punc", "}")) { + croak("Rest element must be last element"); + } + } else if (is("operator", "=")) { + used_parameters.mark_default_assignment(S.token); + next(); + elements[elements.length - 1].value = new AST_DefaultAssign({ + start: elements[elements.length - 1].value.start, + left: elements[elements.length - 1].value, + operator: "=", + right: expression(false), + end: S.token + }); + } + } + expect("}"); + used_parameters.check_strict(); + return new AST_Destructuring({ + start: first_token, + names: elements, + is_array: false, + end: prev() + }); + } else if (is("name")) { + used_parameters.add_parameter(S.token); + return as_symbol(symbol_type); + } else { + croak("Invalid function parameter"); + } + } + + function params_or_seq_(allow_arrows, maybe_sequence) { + var spread_token; + var invalid_sequence; + var trailing_comma; + var a = []; + expect("("); + while (!is("punc", ")")) { + if (spread_token) unexpected(spread_token); + if (is("expand", "...")) { + spread_token = S.token; + if (maybe_sequence) invalid_sequence = S.token; + next(); + a.push(new AST_Expansion({ + start: prev(), + expression: expression(), + end: S.token, + })); + } else { + a.push(expression()); + } + if (!is("punc", ")")) { + expect(","); + if (is("punc", ")")) { + trailing_comma = prev(); + if (maybe_sequence) invalid_sequence = trailing_comma; + } + } + } + expect(")"); + if (allow_arrows && is("arrow", "=>")) { + if (spread_token && trailing_comma) unexpected(trailing_comma); + } else if (invalid_sequence) { + unexpected(invalid_sequence); + } + return a; + } + + function _function_body(block, generator, is_async, name, args) { + var loop = S.in_loop; + var labels = S.labels; + var current_generator = S.in_generator; + var current_async = S.in_async; + ++S.in_function; + if (generator) + S.in_generator = S.in_function; + if (is_async) + S.in_async = S.in_function; + if (args) parameters(args); + if (block) + S.in_directives = true; + S.in_loop = 0; + S.labels = []; + if (block) { + S.input.push_directives_stack(); + var a = block_(); + if (name) _verify_symbol(name); + if (args) args.forEach(_verify_symbol); + S.input.pop_directives_stack(); + } else { + var a = [new AST_Return({ + start: S.token, + value: expression(false), + end: S.token + })]; + } + --S.in_function; + S.in_loop = loop; + S.labels = labels; + S.in_generator = current_generator; + S.in_async = current_async; + return a; + } + + function _await_expression() { + // Previous token must be "await" and not be interpreted as an identifier + if (!can_await()) { + croak("Unexpected await expression outside async function", + S.prev.line, S.prev.col, S.prev.pos); + } + // the await expression is parsed as a unary expression in Babel + return new AST_Await({ + start: prev(), + end: S.token, + expression : maybe_unary(true), + }); + } + + function _yield_expression() { + // Previous token must be keyword yield and not be interpret as an identifier + if (!is_in_generator()) { + croak("Unexpected yield expression outside generator function", + S.prev.line, S.prev.col, S.prev.pos); + } + var start = S.token; + var star = false; + var has_expression = true; + + // Attempt to get expression or star (and then the mandatory expression) + // behind yield on the same line. + // + // If nothing follows on the same line of the yieldExpression, + // it should default to the value `undefined` for yield to return. + // In that case, the `undefined` stored as `null` in ast. + // + // Note 1: It isn't allowed for yield* to close without an expression + // Note 2: If there is a nlb between yield and star, it is interpret as + // yield * + if (can_insert_semicolon() || + (is("punc") && PUNC_AFTER_EXPRESSION.has(S.token.value))) { + has_expression = false; + + } else if (is("operator", "*")) { + star = true; + next(); + } + + return new AST_Yield({ + start : start, + is_star : star, + expression : has_expression ? expression() : null, + end : prev() + }); + } + + function if_() { + var cond = parenthesised(), body = statement(false, false, true), belse = null; + if (is("keyword", "else")) { + next(); + belse = statement(false, false, true); + } + return new AST_If({ + condition : cond, + body : body, + alternative : belse + }); + } + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + a.push(statement()); + } + next(); + return a; + } + + function switch_body_() { + expect("{"); + var a = [], cur = null, branch = null, tmp; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + if (is("keyword", "case")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Case({ + start : (tmp = S.token, next(), tmp), + expression : expression(true), + body : cur + }); + a.push(branch); + expect(":"); + } else if (is("keyword", "default")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Default({ + start : (tmp = S.token, next(), expect(":"), tmp), + body : cur + }); + a.push(branch); + } else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + if (branch) branch.end = prev(); + next(); + return a; + } + + function try_() { + var body = block_(), bcatch = null, bfinally = null; + if (is("keyword", "catch")) { + var start = S.token; + next(); + if (is("punc", "{")) { + var name = null; + } else { + expect("("); + var name = parameter(undefined, AST_SymbolCatch); + expect(")"); + } + bcatch = new AST_Catch({ + start : start, + argname : name, + body : block_(), + end : prev() + }); + } + if (is("keyword", "finally")) { + var start = S.token; + next(); + bfinally = new AST_Finally({ + start : start, + body : block_(), + end : prev() + }); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return new AST_Try({ + body : body, + bcatch : bcatch, + bfinally : bfinally + }); + } + + function vardefs(no_in, kind) { + var a = []; + var def; + for (;;) { + var sym_type = + kind === "var" ? AST_SymbolVar : + kind === "const" ? AST_SymbolConst : + kind === "let" ? AST_SymbolLet : null; + if (is("punc", "{") || is("punc", "[")) { + def = new AST_VarDef({ + start: S.token, + name: binding_element(undefined ,sym_type), + value: is("operator", "=") ? (expect_token("operator", "="), expression(false, no_in)) : null, + end: prev() + }); + } else { + def = new AST_VarDef({ + start : S.token, + name : as_symbol(sym_type), + value : is("operator", "=") + ? (next(), expression(false, no_in)) + : !no_in && kind === "const" + ? croak("Missing initializer in const declaration") : null, + end : prev() + }); + if (def.name.name == "import") croak("Unexpected token: import"); + } + a.push(def); + if (!is("punc", ",")) + break; + next(); + } + return a; + } + + var var_ = function(no_in) { + return new AST_Var({ + start : prev(), + definitions : vardefs(no_in, "var"), + end : prev() + }); + }; + + var let_ = function(no_in) { + return new AST_Let({ + start : prev(), + definitions : vardefs(no_in, "let"), + end : prev() + }); + }; + + var const_ = function(no_in) { + return new AST_Const({ + start : prev(), + definitions : vardefs(no_in, "const"), + end : prev() + }); + }; + + var new_ = function(allow_calls) { + var start = S.token; + expect_token("operator", "new"); + if (is("punc", ".")) { + next(); + expect_token("name", "target"); + return subscripts(new AST_NewTarget({ + start : start, + end : prev() + }), allow_calls); + } + var newexp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")", true); + } else { + args = []; + } + var call = new AST_New({ + start : start, + expression : newexp, + args : args, + end : prev() + }); + annotate(call); + return subscripts(call, allow_calls); + }; + + function as_atom_node() { + var tok = S.token, ret; + switch (tok.type) { + case "name": + ret = _make_symbol(AST_SymbolRef); + break; + case "num": + ret = new AST_Number({ + start: tok, + end: tok, + value: tok.value, + raw: LATEST_RAW + }); + break; + case "big_int": + ret = new AST_BigInt({ start: tok, end: tok, value: tok.value }); + break; + case "string": + ret = new AST_String({ + start : tok, + end : tok, + value : tok.value, + quote : tok.quote + }); + break; + case "regexp": + const [_, source, flags] = tok.value.match(/^\/(.*)\/(\w*)$/); + + ret = new AST_RegExp({ start: tok, end: tok, value: { source, flags } }); + break; + case "atom": + switch (tok.value) { + case "false": + ret = new AST_False({ start: tok, end: tok }); + break; + case "true": + ret = new AST_True({ start: tok, end: tok }); + break; + case "null": + ret = new AST_Null({ start: tok, end: tok }); + break; + } + break; + } + next(); + return ret; + } + + function to_fun_args(ex, default_seen_above) { + var insert_default = function(ex, default_value) { + if (default_value) { + return new AST_DefaultAssign({ + start: ex.start, + left: ex, + operator: "=", + right: default_value, + end: default_value.end + }); + } + return ex; + }; + if (ex instanceof AST_Object) { + return insert_default(new AST_Destructuring({ + start: ex.start, + end: ex.end, + is_array: false, + names: ex.properties.map(prop => to_fun_args(prop)) + }), default_seen_above); + } else if (ex instanceof AST_ObjectKeyVal) { + ex.value = to_fun_args(ex.value); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_Hole) { + return ex; + } else if (ex instanceof AST_Destructuring) { + ex.names = ex.names.map(name => to_fun_args(name)); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_SymbolRef) { + return insert_default(new AST_SymbolFunarg({ + name: ex.name, + start: ex.start, + end: ex.end + }), default_seen_above); + } else if (ex instanceof AST_Expansion) { + ex.expression = to_fun_args(ex.expression); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_Array) { + return insert_default(new AST_Destructuring({ + start: ex.start, + end: ex.end, + is_array: true, + names: ex.elements.map(elm => to_fun_args(elm)) + }), default_seen_above); + } else if (ex instanceof AST_Assign) { + return insert_default(to_fun_args(ex.left, ex.right), default_seen_above); + } else if (ex instanceof AST_DefaultAssign) { + ex.left = to_fun_args(ex.left); + return ex; + } else { + croak("Invalid function parameter", ex.start.line, ex.start.col); + } + } + + var expr_atom = function(allow_calls, allow_arrows) { + if (is("operator", "new")) { + return new_(allow_calls); + } + if (is("operator", "import")) { + return import_meta(); + } + var start = S.token; + var peeked; + var async = is("name", "async") + && (peeked = peek()).value != "[" + && peeked.type != "arrow" + && as_atom_node(); + if (is("punc")) { + switch (S.token.value) { + case "(": + if (async && !allow_calls) break; + var exprs = params_or_seq_(allow_arrows, !async); + if (allow_arrows && is("arrow", "=>")) { + return arrow_function(start, exprs.map(e => to_fun_args(e)), !!async); + } + var ex = async ? new AST_Call({ + expression: async, + args: exprs + }) : exprs.length == 1 ? exprs[0] : new AST_Sequence({ + expressions: exprs + }); + if (ex.start) { + const outer_comments_before = start.comments_before.length; + outer_comments_before_counts.set(start, outer_comments_before); + ex.start.comments_before.unshift(...start.comments_before); + start.comments_before = ex.start.comments_before; + if (outer_comments_before == 0 && start.comments_before.length > 0) { + var comment = start.comments_before[0]; + if (!comment.nlb) { + comment.nlb = start.nlb; + start.nlb = false; + } + } + start.comments_after = ex.start.comments_after; + } + ex.start = start; + var end = prev(); + if (ex.end) { + end.comments_before = ex.end.comments_before; + ex.end.comments_after.push(...end.comments_after); + end.comments_after = ex.end.comments_after; + } + ex.end = end; + if (ex instanceof AST_Call) annotate(ex); + return subscripts(ex, allow_calls); + case "[": + return subscripts(array_(), allow_calls); + case "{": + return subscripts(object_or_destructuring_(), allow_calls); + } + if (!async) unexpected(); + } + if (allow_arrows && is("name") && is_token(peek(), "arrow")) { + var param = new AST_SymbolFunarg({ + name: S.token.value, + start: start, + end: start, + }); + next(); + return arrow_function(start, [param], !!async); + } + if (is("keyword", "function")) { + next(); + var func = function_(AST_Function, false, !!async); + func.start = start; + func.end = prev(); + return subscripts(func, allow_calls); + } + if (async) return subscripts(async, allow_calls); + if (is("keyword", "class")) { + next(); + var cls = class_(AST_ClassExpression); + cls.start = start; + cls.end = prev(); + return subscripts(cls, allow_calls); + } + if (is("template_head")) { + return subscripts(template_string(), allow_calls); + } + if (ATOMIC_START_TOKEN.has(S.token.type)) { + return subscripts(as_atom_node(), allow_calls); + } + unexpected(); + }; + + function template_string() { + var segments = [], start = S.token; + + segments.push(new AST_TemplateSegment({ + start: S.token, + raw: LATEST_RAW, + value: S.token.value, + end: S.token + })); + + while (!LATEST_TEMPLATE_END) { + next(); + handle_regexp(); + segments.push(expression(true)); + + segments.push(new AST_TemplateSegment({ + start: S.token, + raw: LATEST_RAW, + value: S.token.value, + end: S.token + })); + } + next(); + + return new AST_TemplateString({ + start: start, + segments: segments, + end: S.token + }); + } + + function expr_list(closing, allow_trailing_comma, allow_empty) { + var first = true, a = []; + while (!is("punc", closing)) { + if (first) first = false; else expect(","); + if (allow_trailing_comma && is("punc", closing)) break; + if (is("punc", ",") && allow_empty) { + a.push(new AST_Hole({ start: S.token, end: S.token })); + } else if (is("expand", "...")) { + next(); + a.push(new AST_Expansion({start: prev(), expression: expression(),end: S.token})); + } else { + a.push(expression(false)); + } + } + next(); + return a; + } + + var array_ = embed_tokens(function() { + expect("["); + return new AST_Array({ + elements: expr_list("]", !options.strict, true) + }); + }); + + var create_accessor = embed_tokens((is_generator, is_async) => { + return function_(AST_Accessor, is_generator, is_async); + }); + + var object_or_destructuring_ = embed_tokens(function object_or_destructuring_() { + var start = S.token, first = true, a = []; + expect("{"); + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + if (!options.strict && is("punc", "}")) + // allow trailing comma + break; + + start = S.token; + if (start.type == "expand") { + next(); + a.push(new AST_Expansion({ + start: start, + expression: expression(false), + end: prev(), + })); + continue; + } + + var name = as_property_name(); + var value; + + // Check property and fetch value + if (!is("punc", ":")) { + var concise = concise_method_or_getset(name, start); + if (concise) { + a.push(concise); + continue; + } + + value = new AST_SymbolRef({ + start: prev(), + name: name, + end: prev() + }); + } else if (name === null) { + unexpected(prev()); + } else { + next(); // `:` - see first condition + value = expression(false); + } + + // Check for default value and alter value accordingly if necessary + if (is("operator", "=")) { + next(); + value = new AST_Assign({ + start: start, + left: value, + operator: "=", + right: expression(false), + logical: false, + end: prev() + }); + } + + // Create property + a.push(new AST_ObjectKeyVal({ + start: start, + quote: start.quote, + key: name instanceof AST_Node ? name : "" + name, + value: value, + end: prev() + })); + } + next(); + return new AST_Object({ properties: a }); + }); + + function class_(KindOfClass, is_export_default) { + var start, method, class_name, extends_, a = []; + + S.input.push_directives_stack(); // Push directive stack, but not scope stack + S.input.add_directive("use strict"); + + if (S.token.type == "name" && S.token.value != "extends") { + class_name = as_symbol(KindOfClass === AST_DefClass ? AST_SymbolDefClass : AST_SymbolClass); + } + + if (KindOfClass === AST_DefClass && !class_name) { + if (is_export_default) { + KindOfClass = AST_ClassExpression; + } else { + unexpected(); + } + } + + if (S.token.value == "extends") { + next(); + extends_ = expression(true); + } + + expect("{"); + + while (is("punc", ";")) { next(); } // Leading semicolons are okay in class bodies. + while (!is("punc", "}")) { + start = S.token; + method = concise_method_or_getset(as_property_name(), start, true); + if (!method) { unexpected(); } + a.push(method); + while (is("punc", ";")) { next(); } + } + + S.input.pop_directives_stack(); + + next(); + + return new KindOfClass({ + start: start, + name: class_name, + extends: extends_, + properties: a, + end: prev(), + }); + } + + function concise_method_or_getset(name, start, is_class) { + const get_symbol_ast = (name, SymbolClass = AST_SymbolMethod) => { + if (typeof name === "string" || typeof name === "number") { + return new SymbolClass({ + start, + name: "" + name, + end: prev() + }); + } else if (name === null) { + unexpected(); + } + return name; + }; + + const is_not_method_start = () => + !is("punc", "(") && !is("punc", ",") && !is("punc", "}") && !is("punc", ";") && !is("operator", "="); + + var is_async = false; + var is_static = false; + var is_generator = false; + var is_private = false; + var accessor_type = null; + + if (is_class && name === "static" && is_not_method_start()) { + is_static = true; + name = as_property_name(); + } + if (name === "async" && is_not_method_start()) { + is_async = true; + name = as_property_name(); + } + if (prev().type === "operator" && prev().value === "*") { + is_generator = true; + name = as_property_name(); + } + if ((name === "get" || name === "set") && is_not_method_start()) { + accessor_type = name; + name = as_property_name(); + } + if (prev().type === "privatename") { + is_private = true; + } + + const property_token = prev(); + + if (accessor_type != null) { + if (!is_private) { + const AccessorClass = accessor_type === "get" + ? AST_ObjectGetter + : AST_ObjectSetter; + + name = get_symbol_ast(name); + return new AccessorClass({ + start, + static: is_static, + key: name, + quote: name instanceof AST_SymbolMethod ? property_token.quote : undefined, + value: create_accessor(), + end: prev() + }); + } else { + const AccessorClass = accessor_type === "get" + ? AST_PrivateGetter + : AST_PrivateSetter; + + return new AccessorClass({ + start, + static: is_static, + key: get_symbol_ast(name), + value: create_accessor(), + end: prev(), + }); + } + } + + if (is("punc", "(")) { + name = get_symbol_ast(name); + const AST_MethodVariant = is_private + ? AST_PrivateMethod + : AST_ConciseMethod; + var node = new AST_MethodVariant({ + start : start, + static : is_static, + is_generator: is_generator, + async : is_async, + key : name, + quote : name instanceof AST_SymbolMethod ? + property_token.quote : undefined, + value : create_accessor(is_generator, is_async), + end : prev() + }); + return node; + } + + if (is_class) { + const key = get_symbol_ast(name, AST_SymbolClassProperty); + const quote = key instanceof AST_SymbolClassProperty + ? property_token.quote + : undefined; + const AST_ClassPropertyVariant = is_private + ? AST_ClassPrivateProperty + : AST_ClassProperty; + if (is("operator", "=")) { + next(); + return new AST_ClassPropertyVariant({ + start, + static: is_static, + quote, + key, + value: expression(false), + end: prev() + }); + } else if ( + is("name") + || is("privatename") + || is("operator", "*") + || is("punc", ";") + || is("punc", "}") + ) { + return new AST_ClassPropertyVariant({ + start, + static: is_static, + quote, + key, + end: prev() + }); + } + } + } + + function maybe_import_assertion() { + if (is("name", "assert") && !has_newline_before(S.token)) { + next(); + return object_or_destructuring_(); + } + return null; + } + + function import_statement() { + var start = prev(); + + var imported_name; + var imported_names; + if (is("name")) { + imported_name = as_symbol(AST_SymbolImport); + } + + if (is("punc", ",")) { + next(); + } + + imported_names = map_names(true); + + if (imported_names || imported_name) { + expect_token("name", "from"); + } + var mod_str = S.token; + if (mod_str.type !== "string") { + unexpected(); + } + next(); + + const assert_clause = maybe_import_assertion(); + + return new AST_Import({ + start, + imported_name, + imported_names, + module_name: new AST_String({ + start: mod_str, + value: mod_str.value, + quote: mod_str.quote, + end: mod_str, + }), + assert_clause, + end: S.token, + }); + } + + function import_meta() { + var start = S.token; + expect_token("operator", "import"); + expect_token("punc", "."); + expect_token("name", "meta"); + return subscripts(new AST_ImportMeta({ + start: start, + end: prev() + }), false); + } + + function map_name(is_import) { + function make_symbol(type) { + return new type({ + name: as_property_name(), + start: prev(), + end: prev() + }); + } + + var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; + var type = is_import ? AST_SymbolImport : AST_SymbolExport; + var start = S.token; + var foreign_name; + var name; + + if (is_import) { + foreign_name = make_symbol(foreign_type); + } else { + name = make_symbol(type); + } + if (is("name", "as")) { + next(); // The "as" word + if (is_import) { + name = make_symbol(type); + } else { + foreign_name = make_symbol(foreign_type); + } + } else if (is_import) { + name = new type(foreign_name); + } else { + foreign_name = new foreign_type(name); + } + + return new AST_NameMapping({ + start: start, + foreign_name: foreign_name, + name: name, + end: prev(), + }); + } + + function map_nameAsterisk(is_import, name) { + var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; + var type = is_import ? AST_SymbolImport : AST_SymbolExport; + var start = S.token; + var foreign_name; + var end = prev(); + + name = name || new type({ + name: "*", + start: start, + end: end, + }); + + foreign_name = new foreign_type({ + name: "*", + start: start, + end: end, + }); + + return new AST_NameMapping({ + start: start, + foreign_name: foreign_name, + name: name, + end: end, + }); + } + + function map_names(is_import) { + var names; + if (is("punc", "{")) { + next(); + names = []; + while (!is("punc", "}")) { + names.push(map_name(is_import)); + if (is("punc", ",")) { + next(); + } + } + next(); + } else if (is("operator", "*")) { + var name; + next(); + if (is_import && is("name", "as")) { + next(); // The "as" word + name = as_symbol(is_import ? AST_SymbolImport : AST_SymbolExportForeign); + } + names = [map_nameAsterisk(is_import, name)]; + } + return names; + } + + function export_statement() { + var start = S.token; + var is_default; + var exported_names; + + if (is("keyword", "default")) { + is_default = true; + next(); + } else if (exported_names = map_names(false)) { + if (is("name", "from")) { + next(); + + var mod_str = S.token; + if (mod_str.type !== "string") { + unexpected(); + } + next(); + + const assert_clause = maybe_import_assertion(); + + return new AST_Export({ + start: start, + is_default: is_default, + exported_names: exported_names, + module_name: new AST_String({ + start: mod_str, + value: mod_str.value, + quote: mod_str.quote, + end: mod_str, + }), + end: prev(), + assert_clause + }); + } else { + return new AST_Export({ + start: start, + is_default: is_default, + exported_names: exported_names, + end: prev(), + }); + } + } + + var node; + var exported_value; + var exported_definition; + if (is("punc", "{") + || is_default + && (is("keyword", "class") || is("keyword", "function")) + && is_token(peek(), "punc")) { + exported_value = expression(false); + semicolon(); + } else if ((node = statement(is_default)) instanceof AST_Definitions && is_default) { + unexpected(node.start); + } else if ( + node instanceof AST_Definitions + || node instanceof AST_Defun + || node instanceof AST_DefClass + ) { + exported_definition = node; + } else if ( + node instanceof AST_ClassExpression + || node instanceof AST_Function + ) { + exported_value = node; + } else if (node instanceof AST_SimpleStatement) { + exported_value = node.body; + } else { + unexpected(node.start); + } + + return new AST_Export({ + start: start, + is_default: is_default, + exported_value: exported_value, + exported_definition: exported_definition, + end: prev(), + assert_clause: null + }); + } + + function as_property_name() { + var tmp = S.token; + switch (tmp.type) { + case "punc": + if (tmp.value === "[") { + next(); + var ex = expression(false); + expect("]"); + return ex; + } else unexpected(tmp); + case "operator": + if (tmp.value === "*") { + next(); + return null; + } + if (!["delete", "in", "instanceof", "new", "typeof", "void"].includes(tmp.value)) { + unexpected(tmp); + } + /* falls through */ + case "name": + case "privatename": + case "string": + case "num": + case "big_int": + case "keyword": + case "atom": + next(); + return tmp.value; + default: + unexpected(tmp); + } + } + + function as_name() { + var tmp = S.token; + if (tmp.type != "name" && tmp.type != "privatename") unexpected(); + next(); + return tmp.value; + } + + function _make_symbol(type) { + var name = S.token.value; + return new (name == "this" ? AST_This : + name == "super" ? AST_Super : + type)({ + name : String(name), + start : S.token, + end : S.token + }); + } + + function _verify_symbol(sym) { + var name = sym.name; + if (is_in_generator() && name == "yield") { + token_error(sym.start, "Yield cannot be used as identifier inside generators"); + } + if (S.input.has_directive("use strict")) { + if (name == "yield") { + token_error(sym.start, "Unexpected yield identifier inside strict mode"); + } + if (sym instanceof AST_SymbolDeclaration && (name == "arguments" || name == "eval")) { + token_error(sym.start, "Unexpected " + name + " in strict mode"); + } + } + } + + function as_symbol(type, noerror) { + if (!is("name")) { + if (!noerror) croak("Name expected"); + return null; + } + var sym = _make_symbol(type); + _verify_symbol(sym); + next(); + return sym; + } + + // Annotate AST_Call, AST_Lambda or AST_New with the special comments + function annotate(node) { + var start = node.start; + var comments = start.comments_before; + const comments_outside_parens = outer_comments_before_counts.get(start); + var i = comments_outside_parens != null ? comments_outside_parens : comments.length; + while (--i >= 0) { + var comment = comments[i]; + if (/[@#]__/.test(comment.value)) { + if (/[@#]__PURE__/.test(comment.value)) { + set_annotation(node, _PURE); + break; + } + if (/[@#]__INLINE__/.test(comment.value)) { + set_annotation(node, _INLINE); + break; + } + if (/[@#]__NOINLINE__/.test(comment.value)) { + set_annotation(node, _NOINLINE); + break; + } + } + } + } + + var subscripts = function(expr, allow_calls, is_chain) { + var start = expr.start; + if (is("punc", ".")) { + next(); + const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; + return subscripts(new AST_DotVariant({ + start : start, + expression : expr, + optional : false, + property : as_name(), + end : prev() + }), allow_calls, is_chain); + } + if (is("punc", "[")) { + next(); + var prop = expression(true); + expect("]"); + return subscripts(new AST_Sub({ + start : start, + expression : expr, + optional : false, + property : prop, + end : prev() + }), allow_calls, is_chain); + } + if (allow_calls && is("punc", "(")) { + next(); + var call = new AST_Call({ + start : start, + expression : expr, + optional : false, + args : call_args(), + end : prev() + }); + annotate(call); + return subscripts(call, true, is_chain); + } + + if (is("punc", "?.")) { + next(); + + let chain_contents; + + if (allow_calls && is("punc", "(")) { + next(); + + const call = new AST_Call({ + start, + optional: true, + expression: expr, + args: call_args(), + end: prev() + }); + annotate(call); + + chain_contents = subscripts(call, true, true); + } else if (is("name") || is("privatename")) { + const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; + chain_contents = subscripts(new AST_DotVariant({ + start, + expression: expr, + optional: true, + property: as_name(), + end: prev() + }), allow_calls, true); + } else if (is("punc", "[")) { + next(); + const property = expression(true); + expect("]"); + chain_contents = subscripts(new AST_Sub({ + start, + expression: expr, + optional: true, + property, + end: prev() + }), allow_calls, true); + } + + if (!chain_contents) unexpected(); + + if (chain_contents instanceof AST_Chain) return chain_contents; + + return new AST_Chain({ + start, + expression: chain_contents, + end: prev() + }); + } + + if (is("template_head")) { + if (is_chain) { + // a?.b`c` is a syntax error + unexpected(); + } + + return subscripts(new AST_PrefixedTemplateString({ + start: start, + prefix: expr, + template_string: template_string(), + end: prev() + }), allow_calls); + } + + return expr; + }; + + function call_args() { + var args = []; + while (!is("punc", ")")) { + if (is("expand", "...")) { + next(); + args.push(new AST_Expansion({ + start: prev(), + expression: expression(false), + end: prev() + })); + } else { + args.push(expression(false)); + } + if (!is("punc", ")")) { + expect(","); + } + } + next(); + return args; + } + + var maybe_unary = function(allow_calls, allow_arrows) { + var start = S.token; + if (start.type == "name" && start.value == "await" && can_await()) { + next(); + return _await_expression(); + } + if (is("operator") && UNARY_PREFIX.has(start.value)) { + next(); + handle_regexp(); + var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(allow_calls)); + ex.start = start; + ex.end = prev(); + return ex; + } + var val = expr_atom(allow_calls, allow_arrows); + while (is("operator") && UNARY_POSTFIX.has(S.token.value) && !has_newline_before(S.token)) { + if (val instanceof AST_Arrow) unexpected(); + val = make_unary(AST_UnaryPostfix, S.token, val); + val.start = start; + val.end = S.token; + next(); + } + return val; + }; + + function make_unary(ctor, token, expr) { + var op = token.value; + switch (op) { + case "++": + case "--": + if (!is_assignable(expr)) + croak("Invalid use of " + op + " operator", token.line, token.col, token.pos); + break; + case "delete": + if (expr instanceof AST_SymbolRef && S.input.has_directive("use strict")) + croak("Calling delete on expression not allowed in strict mode", expr.start.line, expr.start.col, expr.start.pos); + break; + } + return new ctor({ operator: op, expression: expr }); + } + + var expr_op = function(left, min_prec, no_in) { + var op = is("operator") ? S.token.value : null; + if (op == "in" && no_in) op = null; + if (op == "**" && left instanceof AST_UnaryPrefix + /* unary token in front not allowed - parenthesis required */ + && !is_token(left.start, "punc", "(") + && left.operator !== "--" && left.operator !== "++") + unexpected(left.start); + var prec = op != null ? PRECEDENCE[op] : null; + if (prec != null && (prec > min_prec || (op === "**" && min_prec === prec))) { + next(); + var right = expr_op(maybe_unary(true), prec, no_in); + return expr_op(new AST_Binary({ + start : left.start, + left : left, + operator : op, + right : right, + end : right.end + }), min_prec, no_in); + } + return left; + }; + + function expr_ops(no_in) { + return expr_op(maybe_unary(true, true), 0, no_in); + } + + var maybe_conditional = function(no_in) { + var start = S.token; + var expr = expr_ops(no_in); + if (is("operator", "?")) { + next(); + var yes = expression(false); + expect(":"); + return new AST_Conditional({ + start : start, + condition : expr, + consequent : yes, + alternative : expression(false, no_in), + end : prev() + }); + } + return expr; + }; + + function is_assignable(expr) { + return expr instanceof AST_PropAccess || expr instanceof AST_SymbolRef; + } + + function to_destructuring(node) { + if (node instanceof AST_Object) { + node = new AST_Destructuring({ + start: node.start, + names: node.properties.map(to_destructuring), + is_array: false, + end: node.end + }); + } else if (node instanceof AST_Array) { + var names = []; + + for (var i = 0; i < node.elements.length; i++) { + // Only allow expansion as last element + if (node.elements[i] instanceof AST_Expansion) { + if (i + 1 !== node.elements.length) { + token_error(node.elements[i].start, "Spread must the be last element in destructuring array"); + } + node.elements[i].expression = to_destructuring(node.elements[i].expression); + } + + names.push(to_destructuring(node.elements[i])); + } + + node = new AST_Destructuring({ + start: node.start, + names: names, + is_array: true, + end: node.end + }); + } else if (node instanceof AST_ObjectProperty) { + node.value = to_destructuring(node.value); + } else if (node instanceof AST_Assign) { + node = new AST_DefaultAssign({ + start: node.start, + left: node.left, + operator: "=", + right: node.right, + end: node.end + }); + } + return node; + } + + // In ES6, AssignmentExpression can also be an ArrowFunction + var maybe_assign = function(no_in) { + handle_regexp(); + var start = S.token; + + if (start.type == "name" && start.value == "yield") { + if (is_in_generator()) { + next(); + return _yield_expression(); + } else if (S.input.has_directive("use strict")) { + token_error(S.token, "Unexpected yield identifier inside strict mode"); + } + } + + var left = maybe_conditional(no_in); + var val = S.token.value; + + if (is("operator") && ASSIGNMENT.has(val)) { + if (is_assignable(left) || (left = to_destructuring(left)) instanceof AST_Destructuring) { + next(); + + return new AST_Assign({ + start : start, + left : left, + operator : val, + right : maybe_assign(no_in), + logical : LOGICAL_ASSIGNMENT.has(val), + end : prev() + }); + } + croak("Invalid assignment"); + } + return left; + }; + + var expression = function(commas, no_in) { + var start = S.token; + var exprs = []; + while (true) { + exprs.push(maybe_assign(no_in)); + if (!commas || !is("punc", ",")) break; + next(); + commas = true; + } + return exprs.length == 1 ? exprs[0] : new AST_Sequence({ + start : start, + expressions : exprs, + end : peek() + }); + }; + + function in_loop(cont) { + ++S.in_loop; + var ret = cont(); + --S.in_loop; + return ret; + } + + if (options.expression) { + return expression(true); + } + + return (function parse_toplevel() { + var start = S.token; + var body = []; + S.input.push_directives_stack(); + if (options.module) S.input.add_directive("use strict"); + while (!is("eof")) { + body.push(statement()); + } + S.input.pop_directives_stack(); + var end = prev(); + var toplevel = options.toplevel; + if (toplevel) { + toplevel.body = toplevel.body.concat(body); + toplevel.end = end; + } else { + toplevel = new AST_Toplevel({ start: start, body: body, end: end }); + } + return toplevel; + })(); + +} + +export { + get_full_char_code, + get_full_char, + is_identifier_char, + is_basic_identifier_string, + is_identifier_string, + is_surrogate_pair_head, + is_surrogate_pair_tail, + js_error, + JS_Parse_Error, + parse, + PRECEDENCE, + ALL_RESERVED_WORDS, + tokenizer, +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/propmangle.js b/node_modules/mathjs/examples/node_modules/terser/lib/propmangle.js new file mode 100644 index 0000000..27df236 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/propmangle.js @@ -0,0 +1,376 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; +/* global global, self */ + +import { + defaults, + push_uniq, +} from "./utils/index.js"; +import { base54 } from "./scope.js"; +import { + AST_Binary, + AST_Call, + AST_ClassPrivateProperty, + AST_Conditional, + AST_Dot, + AST_DotHash, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_PrivateMethod, + AST_PrivateGetter, + AST_PrivateSetter, + AST_Sequence, + AST_String, + AST_Sub, + TreeTransformer, + TreeWalker, +} from "./ast.js"; +import { domprops } from "../tools/domprops.js"; + +function find_builtins(reserved) { + domprops.forEach(add); + + // Compatibility fix for some standard defined globals not defined on every js environment + var new_globals = ["Symbol", "Map", "Promise", "Proxy", "Reflect", "Set", "WeakMap", "WeakSet"]; + var objects = {}; + var global_ref = typeof global === "object" ? global : self; + + new_globals.forEach(function (new_global) { + objects[new_global] = global_ref[new_global] || new Function(); + }); + + [ + "null", + "true", + "false", + "NaN", + "Infinity", + "-Infinity", + "undefined", + ].forEach(add); + [ Object, Array, Function, Number, + String, Boolean, Error, Math, + Date, RegExp, objects.Symbol, ArrayBuffer, + DataView, decodeURI, decodeURIComponent, + encodeURI, encodeURIComponent, eval, EvalError, + Float32Array, Float64Array, Int8Array, Int16Array, + Int32Array, isFinite, isNaN, JSON, objects.Map, parseFloat, + parseInt, objects.Promise, objects.Proxy, RangeError, ReferenceError, + objects.Reflect, objects.Set, SyntaxError, TypeError, Uint8Array, + Uint8ClampedArray, Uint16Array, Uint32Array, URIError, + objects.WeakMap, objects.WeakSet + ].forEach(function(ctor) { + Object.getOwnPropertyNames(ctor).map(add); + if (ctor.prototype) { + Object.getOwnPropertyNames(ctor.prototype).map(add); + } + }); + function add(name) { + reserved.add(name); + } +} + +function reserve_quoted_keys(ast, reserved) { + function add(name) { + push_uniq(reserved, name); + } + + ast.walk(new TreeWalker(function(node) { + if (node instanceof AST_ObjectKeyVal && node.quote) { + add(node.key); + } else if (node instanceof AST_ObjectProperty && node.quote) { + add(node.key.name); + } else if (node instanceof AST_Sub) { + addStrings(node.property, add); + } + })); +} + +function addStrings(node, add) { + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_Sequence) { + addStrings(node.tail_node(), add); + } else if (node instanceof AST_String) { + add(node.value); + } else if (node instanceof AST_Conditional) { + addStrings(node.consequent, add); + addStrings(node.alternative, add); + } + return true; + })); +} + +function mangle_private_properties(ast, options) { + var cprivate = -1; + var private_cache = new Map(); + var nth_identifier = options.nth_identifier || base54; + + ast = ast.transform(new TreeTransformer(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + ) { + node.key.name = mangle_private(node.key.name); + } else if (node instanceof AST_DotHash) { + node.property = mangle_private(node.property); + } + })); + return ast; + + function mangle_private(name) { + let mangled = private_cache.get(name); + if (!mangled) { + mangled = nth_identifier.get(++cprivate); + private_cache.set(name, mangled); + } + + return mangled; + } +} + +function mangle_properties(ast, options) { + options = defaults(options, { + builtins: false, + cache: null, + debug: false, + keep_quoted: false, + nth_identifier: base54, + only_cache: false, + regex: null, + reserved: null, + undeclared: false, + }, true); + + var nth_identifier = options.nth_identifier; + + var reserved_option = options.reserved; + if (!Array.isArray(reserved_option)) reserved_option = [reserved_option]; + var reserved = new Set(reserved_option); + if (!options.builtins) find_builtins(reserved); + + var cname = -1; + + var cache; + if (options.cache) { + cache = options.cache.props; + } else { + cache = new Map(); + } + + var regex = options.regex && new RegExp(options.regex); + + // note debug is either false (disabled), or a string of the debug suffix to use (enabled). + // note debug may be enabled as an empty string, which is falsey. Also treat passing 'true' + // the same as passing an empty string. + var debug = options.debug !== false; + var debug_name_suffix; + if (debug) { + debug_name_suffix = (options.debug === true ? "" : options.debug); + } + + var names_to_mangle = new Set(); + var unmangleable = new Set(); + // Track each already-mangled name to prevent nth_identifier from generating + // the same name. + cache.forEach((mangled_name) => unmangleable.add(mangled_name)); + + var keep_quoted = !!options.keep_quoted; + + // step 1: find candidates to mangle + ast.walk(new TreeWalker(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_DotHash + ) { + // handled by mangle_private_properties + } else if (node instanceof AST_ObjectKeyVal) { + if (typeof node.key == "string" && (!keep_quoted || !node.quote)) { + add(node.key); + } + } else if (node instanceof AST_ObjectProperty) { + // setter or getter, since KeyVal is handled above + if (!keep_quoted || !node.quote) { + add(node.key.name); + } + } else if (node instanceof AST_Dot) { + var declared = !!options.undeclared; + if (!declared) { + var root = node; + while (root.expression) { + root = root.expression; + } + declared = !(root.thedef && root.thedef.undeclared); + } + if (declared && + (!keep_quoted || !node.quote)) { + add(node.property); + } + } else if (node instanceof AST_Sub) { + if (!keep_quoted) { + addStrings(node.property, add); + } + } else if (node instanceof AST_Call + && node.expression.print_to_string() == "Object.defineProperty") { + addStrings(node.args[1], add); + } else if (node instanceof AST_Binary && node.operator === "in") { + addStrings(node.left, add); + } + })); + + // step 2: transform the tree, renaming properties + return ast.transform(new TreeTransformer(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_DotHash + ) { + // handled by mangle_private_properties + } else if (node instanceof AST_ObjectKeyVal) { + if (typeof node.key == "string" && (!keep_quoted || !node.quote)) { + node.key = mangle(node.key); + } + } else if (node instanceof AST_ObjectProperty) { + // setter, getter, method or class field + if (!keep_quoted || !node.quote) { + node.key.name = mangle(node.key.name); + } + } else if (node instanceof AST_Dot) { + if (!keep_quoted || !node.quote) { + node.property = mangle(node.property); + } + } else if (!keep_quoted && node instanceof AST_Sub) { + node.property = mangleStrings(node.property); + } else if (node instanceof AST_Call + && node.expression.print_to_string() == "Object.defineProperty") { + node.args[1] = mangleStrings(node.args[1]); + } else if (node instanceof AST_Binary && node.operator === "in") { + node.left = mangleStrings(node.left); + } + })); + + // only function declarations after this line + + function can_mangle(name) { + if (unmangleable.has(name)) return false; + if (reserved.has(name)) return false; + if (options.only_cache) { + return cache.has(name); + } + if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false; + return true; + } + + function should_mangle(name) { + if (regex && !regex.test(name)) return false; + if (reserved.has(name)) return false; + return cache.has(name) + || names_to_mangle.has(name); + } + + function add(name) { + if (can_mangle(name)) + names_to_mangle.add(name); + + if (!should_mangle(name)) { + unmangleable.add(name); + } + } + + function mangle(name) { + if (!should_mangle(name)) { + return name; + } + + var mangled = cache.get(name); + if (!mangled) { + if (debug) { + // debug mode: use a prefix and suffix to preserve readability, e.g. o.foo -> o._$foo$NNN_. + var debug_mangled = "_$" + name + "$" + debug_name_suffix + "_"; + + if (can_mangle(debug_mangled)) { + mangled = debug_mangled; + } + } + + // either debug mode is off, or it is on and we could not use the mangled name + if (!mangled) { + do { + mangled = nth_identifier.get(++cname); + } while (!can_mangle(mangled)); + } + + cache.set(name, mangled); + } + return mangled; + } + + function mangleStrings(node) { + return node.transform(new TreeTransformer(function(node) { + if (node instanceof AST_Sequence) { + var last = node.expressions.length - 1; + node.expressions[last] = mangleStrings(node.expressions[last]); + } else if (node instanceof AST_String) { + node.value = mangle(node.value); + } else if (node instanceof AST_Conditional) { + node.consequent = mangleStrings(node.consequent); + node.alternative = mangleStrings(node.alternative); + } + return node; + })); + } +} + +export { + reserve_quoted_keys, + mangle_properties, + mangle_private_properties, +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/scope.js b/node_modules/mathjs/examples/node_modules/terser/lib/scope.js new file mode 100644 index 0000000..ab822f3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/scope.js @@ -0,0 +1,1042 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +import { + defaults, + keep_name, + mergeSort, + push_uniq, + make_node, + return_false, + return_this, + return_true, + string_template, +} from "./utils/index.js"; +import { + AST_Arrow, + AST_Block, + AST_Call, + AST_Catch, + AST_Class, + AST_Conditional, + AST_DefClass, + AST_Defun, + AST_Destructuring, + AST_Dot, + AST_DotHash, + AST_Export, + AST_For, + AST_ForIn, + AST_Function, + AST_Import, + AST_IterationStatement, + AST_Label, + AST_LabeledStatement, + AST_LabelRef, + AST_Lambda, + AST_LoopControl, + AST_NameMapping, + AST_Node, + AST_Scope, + AST_Sequence, + AST_String, + AST_Sub, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_SymbolBlockDeclaration, + AST_SymbolCatch, + AST_SymbolClass, + AST_SymbolConst, + AST_SymbolDefClass, + AST_SymbolDefun, + AST_SymbolExport, + AST_SymbolFunarg, + AST_SymbolImport, + AST_SymbolLambda, + AST_SymbolLet, + AST_SymbolMethod, + AST_SymbolRef, + AST_SymbolVar, + AST_Toplevel, + AST_VarDef, + AST_With, + TreeWalker, + walk +} from "./ast.js"; +import { + ALL_RESERVED_WORDS, + js_error, +} from "./parse.js"; + +const MASK_EXPORT_DONT_MANGLE = 1 << 0; +const MASK_EXPORT_WANT_MANGLE = 1 << 1; + +let function_defs = null; +let unmangleable_names = null; +/** + * When defined, there is a function declaration somewhere that's inside of a block. + * See https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-block-level-function-declarations-web-legacy-compatibility-semantics +*/ +let scopes_with_block_defuns = null; + +class SymbolDef { + constructor(scope, orig, init) { + this.name = orig.name; + this.orig = [ orig ]; + this.init = init; + this.eliminated = 0; + this.assignments = 0; + this.scope = scope; + this.replaced = 0; + this.global = false; + this.export = 0; + this.mangled_name = null; + this.undeclared = false; + this.id = SymbolDef.next_id++; + this.chained = false; + this.direct_access = false; + this.escaped = 0; + this.recursive_refs = 0; + this.references = []; + this.should_replace = undefined; + this.single_use = false; + this.fixed = false; + Object.seal(this); + } + fixed_value() { + if (!this.fixed || this.fixed instanceof AST_Node) return this.fixed; + return this.fixed(); + } + unmangleable(options) { + if (!options) options = {}; + + if ( + function_defs && + function_defs.has(this.id) && + keep_name(options.keep_fnames, this.orig[0].name) + ) return true; + + return this.global && !options.toplevel + || (this.export & MASK_EXPORT_DONT_MANGLE) + || this.undeclared + || !options.eval && this.scope.pinned() + || (this.orig[0] instanceof AST_SymbolLambda + || this.orig[0] instanceof AST_SymbolDefun) && keep_name(options.keep_fnames, this.orig[0].name) + || this.orig[0] instanceof AST_SymbolMethod + || (this.orig[0] instanceof AST_SymbolClass + || this.orig[0] instanceof AST_SymbolDefClass) && keep_name(options.keep_classnames, this.orig[0].name); + } + mangle(options) { + const cache = options.cache && options.cache.props; + if (this.global && cache && cache.has(this.name)) { + this.mangled_name = cache.get(this.name); + } else if (!this.mangled_name && !this.unmangleable(options)) { + var s = this.scope; + var sym = this.orig[0]; + if (options.ie8 && sym instanceof AST_SymbolLambda) + s = s.parent_scope; + const redefinition = redefined_catch_def(this); + this.mangled_name = redefinition + ? redefinition.mangled_name || redefinition.name + : s.next_mangled(options, this); + if (this.global && cache) { + cache.set(this.name, this.mangled_name); + } + } + } +} + +SymbolDef.next_id = 1; + +function redefined_catch_def(def) { + if (def.orig[0] instanceof AST_SymbolCatch + && def.scope.is_block_scope() + ) { + return def.scope.get_defun_scope().variables.get(def.name); + } +} + +AST_Scope.DEFMETHOD("figure_out_scope", function(options, { parent_scope = null, toplevel = this } = {}) { + options = defaults(options, { + cache: null, + ie8: false, + safari10: false, + }); + + if (!(toplevel instanceof AST_Toplevel)) { + throw new Error("Invalid toplevel scope"); + } + + // pass 1: setup scope chaining and handle definitions + var scope = this.parent_scope = parent_scope; + var labels = new Map(); + var defun = null; + var in_destructuring = null; + var for_scopes = []; + var tw = new TreeWalker((node, descend) => { + if (node.is_block_scope()) { + const save_scope = scope; + node.block_scope = scope = new AST_Scope(node); + scope._block_scope = true; + // AST_Try in the AST sadly *is* (not has) a body itself, + // and its catch and finally branches are children of the AST_Try itself + const parent_scope = node instanceof AST_Catch + ? save_scope.parent_scope + : save_scope; + scope.init_scope_vars(parent_scope); + scope.uses_with = save_scope.uses_with; + scope.uses_eval = save_scope.uses_eval; + if (options.safari10) { + if (node instanceof AST_For || node instanceof AST_ForIn) { + for_scopes.push(scope); + } + } + + if (node instanceof AST_Switch) { + // XXX: HACK! Ensure the switch expression gets the correct scope (the parent scope) and the body gets the contained scope + // AST_Switch has a scope within the body, but it itself "is a block scope" + // This means the switched expression has to belong to the outer scope + // while the body inside belongs to the switch itself. + // This is pretty nasty and warrants an AST change similar to AST_Try (read above) + const the_block_scope = scope; + scope = save_scope; + node.expression.walk(tw); + scope = the_block_scope; + for (let i = 0; i < node.body.length; i++) { + node.body[i].walk(tw); + } + } else { + descend(); + } + scope = save_scope; + return true; + } + if (node instanceof AST_Destructuring) { + const save_destructuring = in_destructuring; + in_destructuring = node; + descend(); + in_destructuring = save_destructuring; + return true; + } + if (node instanceof AST_Scope) { + node.init_scope_vars(scope); + var save_scope = scope; + var save_defun = defun; + var save_labels = labels; + defun = scope = node; + labels = new Map(); + descend(); + scope = save_scope; + defun = save_defun; + labels = save_labels; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_LabeledStatement) { + var l = node.label; + if (labels.has(l.name)) { + throw new Error(string_template("Label {name} defined twice", l)); + } + labels.set(l.name, l); + descend(); + labels.delete(l.name); + return true; // no descend again + } + if (node instanceof AST_With) { + for (var s = scope; s; s = s.parent_scope) + s.uses_with = true; + return; + } + if (node instanceof AST_Symbol) { + node.scope = scope; + } + if (node instanceof AST_Label) { + node.thedef = node; + node.references = []; + } + if (node instanceof AST_SymbolLambda) { + defun.def_function(node, node.name == "arguments" ? undefined : defun); + } else if (node instanceof AST_SymbolDefun) { + // Careful here, the scope where this should be defined is + // the parent scope. The reason is that we enter a new + // scope when we encounter the AST_Defun node (which is + // instanceof AST_Scope) but we get to the symbol a bit + // later. + const closest_scope = defun.parent_scope; + + // In strict mode, function definitions are block-scoped + node.scope = tw.directives["use strict"] + ? closest_scope + : closest_scope.get_defun_scope(); + + mark_export(node.scope.def_function(node, defun), 1); + } else if (node instanceof AST_SymbolClass) { + mark_export(defun.def_variable(node, defun), 1); + } else if (node instanceof AST_SymbolImport) { + scope.def_variable(node); + } else if (node instanceof AST_SymbolDefClass) { + // This deals with the name of the class being available + // inside the class. + mark_export((node.scope = defun.parent_scope).def_function(node, defun), 1); + } else if ( + node instanceof AST_SymbolVar + || node instanceof AST_SymbolLet + || node instanceof AST_SymbolConst + || node instanceof AST_SymbolCatch + ) { + var def; + if (node instanceof AST_SymbolBlockDeclaration) { + def = scope.def_variable(node, null); + } else { + def = defun.def_variable(node, node.TYPE == "SymbolVar" ? null : undefined); + } + if (!def.orig.every((sym) => { + if (sym === node) return true; + if (node instanceof AST_SymbolBlockDeclaration) { + return sym instanceof AST_SymbolLambda; + } + return !(sym instanceof AST_SymbolLet || sym instanceof AST_SymbolConst); + })) { + js_error( + `"${node.name}" is redeclared`, + node.start.file, + node.start.line, + node.start.col, + node.start.pos + ); + } + if (!(node instanceof AST_SymbolFunarg)) mark_export(def, 2); + if (defun !== scope) { + node.mark_enclosed(); + var def = scope.find_variable(node); + if (node.thedef !== def) { + node.thedef = def; + node.reference(); + } + } + } else if (node instanceof AST_LabelRef) { + var sym = labels.get(node.name); + if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", { + name: node.name, + line: node.start.line, + col: node.start.col + })); + node.thedef = sym; + } + if (!(scope instanceof AST_Toplevel) && (node instanceof AST_Export || node instanceof AST_Import)) { + js_error( + `"${node.TYPE}" statement may only appear at the top level`, + node.start.file, + node.start.line, + node.start.col, + node.start.pos + ); + } + }); + this.walk(tw); + + function mark_export(def, level) { + if (in_destructuring) { + var i = 0; + do { + level++; + } while (tw.parent(i++) !== in_destructuring); + } + var node = tw.parent(level); + if (def.export = node instanceof AST_Export ? MASK_EXPORT_DONT_MANGLE : 0) { + var exported = node.exported_definition; + if ((exported instanceof AST_Defun || exported instanceof AST_DefClass) && node.is_default) { + def.export = MASK_EXPORT_WANT_MANGLE; + } + } + } + + // pass 2: find back references and eval + const is_toplevel = this instanceof AST_Toplevel; + if (is_toplevel) { + this.globals = new Map(); + } + + var tw = new TreeWalker(node => { + if (node instanceof AST_LoopControl && node.label) { + node.label.thedef.references.push(node); + return true; + } + if (node instanceof AST_SymbolRef) { + var name = node.name; + if (name == "eval" && tw.parent() instanceof AST_Call) { + for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) { + s.uses_eval = true; + } + } + var sym; + if (tw.parent() instanceof AST_NameMapping && tw.parent(1).module_name + || !(sym = node.scope.find_variable(name))) { + + sym = toplevel.def_global(node); + if (node instanceof AST_SymbolExport) sym.export = MASK_EXPORT_DONT_MANGLE; + } else if (sym.scope instanceof AST_Lambda && name == "arguments") { + sym.scope.uses_arguments = true; + } + node.thedef = sym; + node.reference(); + if (node.scope.is_block_scope() + && !(sym.orig[0] instanceof AST_SymbolBlockDeclaration)) { + node.scope = node.scope.get_defun_scope(); + } + return true; + } + // ensure mangling works if catch reuses a scope variable + var def; + if (node instanceof AST_SymbolCatch && (def = redefined_catch_def(node.definition()))) { + var s = node.scope; + while (s) { + push_uniq(s.enclosed, def); + if (s === def.scope) break; + s = s.parent_scope; + } + } + }); + this.walk(tw); + + // pass 3: work around IE8 and Safari catch scope bugs + if (options.ie8 || options.safari10) { + walk(this, node => { + if (node instanceof AST_SymbolCatch) { + var name = node.name; + var refs = node.thedef.references; + var scope = node.scope.get_defun_scope(); + var def = scope.find_variable(name) + || toplevel.globals.get(name) + || scope.def_variable(node); + refs.forEach(function(ref) { + ref.thedef = def; + ref.reference(); + }); + node.thedef = def; + node.reference(); + return true; + } + }); + } + + // pass 4: add symbol definitions to loop scopes + // Safari/Webkit bug workaround - loop init let variable shadowing argument. + // https://github.com/mishoo/UglifyJS2/issues/1753 + // https://bugs.webkit.org/show_bug.cgi?id=171041 + if (options.safari10) { + for (const scope of for_scopes) { + scope.parent_scope.variables.forEach(function(def) { + push_uniq(scope.enclosed, def); + }); + } + } +}); + +AST_Toplevel.DEFMETHOD("def_global", function(node) { + var globals = this.globals, name = node.name; + if (globals.has(name)) { + return globals.get(name); + } else { + var g = new SymbolDef(this, node); + g.undeclared = true; + g.global = true; + globals.set(name, g); + return g; + } +}); + +AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope) { + this.variables = new Map(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) + this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement + this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` + this.parent_scope = parent_scope; // the parent scope + this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes + this.cname = -1; // the current index for mangling functions/variables +}); + +AST_Scope.DEFMETHOD("conflicting_def", function (name) { + return ( + this.enclosed.find(def => def.name === name) + || this.variables.has(name) + || (this.parent_scope && this.parent_scope.conflicting_def(name)) + ); +}); + +AST_Scope.DEFMETHOD("conflicting_def_shallow", function (name) { + return ( + this.enclosed.find(def => def.name === name) + || this.variables.has(name) + ); +}); + +AST_Scope.DEFMETHOD("add_child_scope", function (scope) { + // `scope` is going to be moved into `this` right now. + // Update the required scopes' information + + if (scope.parent_scope === this) return; + + scope.parent_scope = this; + + // TODO uses_with, uses_eval, etc + + const scope_ancestry = (() => { + const ancestry = []; + let cur = this; + do { + ancestry.push(cur); + } while ((cur = cur.parent_scope)); + ancestry.reverse(); + return ancestry; + })(); + + const new_scope_enclosed_set = new Set(scope.enclosed); + const to_enclose = []; + for (const scope_topdown of scope_ancestry) { + to_enclose.forEach(e => push_uniq(scope_topdown.enclosed, e)); + for (const def of scope_topdown.variables.values()) { + if (new_scope_enclosed_set.has(def)) { + push_uniq(to_enclose, def); + push_uniq(scope_topdown.enclosed, def); + } + } + } +}); + +function find_scopes_visible_from(scopes) { + const found_scopes = new Set(); + + for (const scope of new Set(scopes)) { + (function bubble_up(scope) { + if (scope == null || found_scopes.has(scope)) return; + + found_scopes.add(scope); + + bubble_up(scope.parent_scope); + })(scope); + } + + return [...found_scopes]; +} + +// Creates a symbol during compression +AST_Scope.DEFMETHOD("create_symbol", function(SymClass, { + source, + tentative_name, + scope, + conflict_scopes = [scope], + init = null +} = {}) { + let symbol_name; + + conflict_scopes = find_scopes_visible_from(conflict_scopes); + + if (tentative_name) { + // Implement hygiene (no new names are conflicting with existing names) + tentative_name = + symbol_name = + tentative_name.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/ig, "_"); + + let i = 0; + while (conflict_scopes.find(s => s.conflicting_def_shallow(symbol_name))) { + symbol_name = tentative_name + "$" + i++; + } + } + + if (!symbol_name) { + throw new Error("No symbol name could be generated in create_symbol()"); + } + + const symbol = make_node(SymClass, source, { + name: symbol_name, + scope + }); + + this.def_variable(symbol, init || null); + + symbol.mark_enclosed(); + + return symbol; +}); + + +AST_Node.DEFMETHOD("is_block_scope", return_false); +AST_Class.DEFMETHOD("is_block_scope", return_false); +AST_Lambda.DEFMETHOD("is_block_scope", return_false); +AST_Toplevel.DEFMETHOD("is_block_scope", return_false); +AST_SwitchBranch.DEFMETHOD("is_block_scope", return_false); +AST_Block.DEFMETHOD("is_block_scope", return_true); +AST_Scope.DEFMETHOD("is_block_scope", function () { + return this._block_scope || false; +}); +AST_IterationStatement.DEFMETHOD("is_block_scope", return_true); + +AST_Lambda.DEFMETHOD("init_scope_vars", function() { + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; + this.def_variable(new AST_SymbolFunarg({ + name: "arguments", + start: this.start, + end: this.end + })); +}); + +AST_Arrow.DEFMETHOD("init_scope_vars", function() { + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; +}); + +AST_Symbol.DEFMETHOD("mark_enclosed", function() { + var def = this.definition(); + var s = this.scope; + while (s) { + push_uniq(s.enclosed, def); + if (s === def.scope) break; + s = s.parent_scope; + } +}); + +AST_Symbol.DEFMETHOD("reference", function() { + this.definition().references.push(this); + this.mark_enclosed(); +}); + +AST_Scope.DEFMETHOD("find_variable", function(name) { + if (name instanceof AST_Symbol) name = name.name; + return this.variables.get(name) + || (this.parent_scope && this.parent_scope.find_variable(name)); +}); + +AST_Scope.DEFMETHOD("def_function", function(symbol, init) { + var def = this.def_variable(symbol, init); + if (!def.init || def.init instanceof AST_Defun) def.init = init; + return def; +}); + +AST_Scope.DEFMETHOD("def_variable", function(symbol, init) { + var def = this.variables.get(symbol.name); + if (def) { + def.orig.push(symbol); + if (def.init && (def.scope !== symbol.scope || def.init instanceof AST_Function)) { + def.init = init; + } + } else { + def = new SymbolDef(this, symbol, init); + this.variables.set(symbol.name, def); + def.global = !this.parent_scope; + } + return symbol.thedef = def; +}); + +function next_mangled(scope, options) { + let defun_scope; + if ( + scopes_with_block_defuns + && (defun_scope = scope.get_defun_scope()) + && scopes_with_block_defuns.has(defun_scope) + ) { + scope = defun_scope; + } + + var ext = scope.enclosed; + var nth_identifier = options.nth_identifier; + out: while (true) { + var m = nth_identifier.get(++scope.cname); + if (ALL_RESERVED_WORDS.has(m)) continue; // skip over "do" + + // https://github.com/mishoo/UglifyJS2/issues/242 -- do not + // shadow a name reserved from mangling. + if (options.reserved.has(m)) continue; + + // Functions with short names might collide with base54 output + // and therefore cause collisions when keep_fnames is true. + if (unmangleable_names && unmangleable_names.has(m)) continue out; + + // we must ensure that the mangled name does not shadow a name + // from some parent scope that is referenced in this or in + // inner scopes. + for (let i = ext.length; --i >= 0;) { + const def = ext[i]; + const name = def.mangled_name || (def.unmangleable(options) && def.name); + if (m == name) continue out; + } + return m; + } +} + +AST_Scope.DEFMETHOD("next_mangled", function(options) { + return next_mangled(this, options); +}); + +AST_Toplevel.DEFMETHOD("next_mangled", function(options) { + let name; + const mangled_names = this.mangled_names; + do { + name = next_mangled(this, options); + } while (mangled_names.has(name)); + return name; +}); + +AST_Function.DEFMETHOD("next_mangled", function(options, def) { + // #179, #326 + // in Safari strict mode, something like (function x(x){...}) is a syntax error; + // a function expression's argument cannot shadow the function expression's name + + var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition(); + + // the function's mangled_name is null when keep_fnames is true + var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null; + + while (true) { + var name = next_mangled(this, options); + if (!tricky_name || tricky_name != name) + return name; + } +}); + +AST_Symbol.DEFMETHOD("unmangleable", function(options) { + var def = this.definition(); + return !def || def.unmangleable(options); +}); + +// labels are always mangleable +AST_Label.DEFMETHOD("unmangleable", return_false); + +AST_Symbol.DEFMETHOD("unreferenced", function() { + return !this.definition().references.length && !this.scope.pinned(); +}); + +AST_Symbol.DEFMETHOD("definition", function() { + return this.thedef; +}); + +AST_Symbol.DEFMETHOD("global", function() { + return this.thedef.global; +}); + +AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options) { + options = defaults(options, { + eval : false, + nth_identifier : base54, + ie8 : false, + keep_classnames: false, + keep_fnames : false, + module : false, + reserved : [], + toplevel : false, + }); + if (options.module) options.toplevel = true; + if (!Array.isArray(options.reserved) + && !(options.reserved instanceof Set) + ) { + options.reserved = []; + } + options.reserved = new Set(options.reserved); + // Never mangle arguments + options.reserved.add("arguments"); + return options; +}); + +AST_Toplevel.DEFMETHOD("mangle_names", function(options) { + options = this._default_mangler_options(options); + var nth_identifier = options.nth_identifier; + + // We only need to mangle declaration nodes. Special logic wired + // into the code generator will display the mangled name if it's + // present (and for AST_SymbolRef-s it'll use the mangled name of + // the AST_SymbolDeclaration that it points to). + var lname = -1; + var to_mangle = []; + + if (options.keep_fnames) { + function_defs = new Set(); + } + + const mangled_names = this.mangled_names = new Set(); + unmangleable_names = new Set(); + + if (options.cache) { + this.globals.forEach(collect); + if (options.cache.props) { + options.cache.props.forEach(function(mangled_name) { + mangled_names.add(mangled_name); + }); + } + } + + var tw = new TreeWalker(function(node, descend) { + if (node instanceof AST_LabeledStatement) { + // lname is incremented when we get to the AST_Label + var save_nesting = lname; + descend(); + lname = save_nesting; + return true; // don't descend again in TreeWalker + } + if ( + node instanceof AST_Defun + && !(tw.parent() instanceof AST_Scope) + ) { + scopes_with_block_defuns = scopes_with_block_defuns || new Set(); + scopes_with_block_defuns.add(node.parent_scope.get_defun_scope()); + } + if (node instanceof AST_Scope) { + node.variables.forEach(collect); + return; + } + if (node.is_block_scope()) { + node.block_scope.variables.forEach(collect); + return; + } + if ( + function_defs + && node instanceof AST_VarDef + && node.value instanceof AST_Lambda + && !node.value.name + && keep_name(options.keep_fnames, node.name.name) + ) { + function_defs.add(node.name.definition().id); + return; + } + if (node instanceof AST_Label) { + let name; + do { + name = nth_identifier.get(++lname); + } while (ALL_RESERVED_WORDS.has(name)); + node.mangled_name = name; + return true; + } + if (!(options.ie8 || options.safari10) && node instanceof AST_SymbolCatch) { + to_mangle.push(node.definition()); + return; + } + }); + + this.walk(tw); + + if (options.keep_fnames || options.keep_classnames) { + // Collect a set of short names which are unmangleable, + // for use in avoiding collisions in next_mangled. + to_mangle.forEach(def => { + if (def.name.length < 6 && def.unmangleable(options)) { + unmangleable_names.add(def.name); + } + }); + } + + to_mangle.forEach(def => { def.mangle(options); }); + + function_defs = null; + unmangleable_names = null; + scopes_with_block_defuns = null; + + function collect(symbol) { + if (symbol.export & MASK_EXPORT_DONT_MANGLE) { + unmangleable_names.add(symbol.name); + } else if (!options.reserved.has(symbol.name)) { + to_mangle.push(symbol); + } + } +}); + +AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) { + const cache = options.cache && options.cache.props; + const avoid = new Set(); + options.reserved.forEach(to_avoid); + this.globals.forEach(add_def); + this.walk(new TreeWalker(function(node) { + if (node instanceof AST_Scope) node.variables.forEach(add_def); + if (node instanceof AST_SymbolCatch) add_def(node.definition()); + })); + return avoid; + + function to_avoid(name) { + avoid.add(name); + } + + function add_def(def) { + var name = def.name; + if (def.global && cache && cache.has(name)) name = cache.get(name); + else if (!def.unmangleable(options)) return; + to_avoid(name); + } +}); + +AST_Toplevel.DEFMETHOD("expand_names", function(options) { + options = this._default_mangler_options(options); + var nth_identifier = options.nth_identifier; + if (nth_identifier.reset && nth_identifier.sort) { + nth_identifier.reset(); + nth_identifier.sort(); + } + var avoid = this.find_colliding_names(options); + var cname = 0; + this.globals.forEach(rename); + this.walk(new TreeWalker(function(node) { + if (node instanceof AST_Scope) node.variables.forEach(rename); + if (node instanceof AST_SymbolCatch) rename(node.definition()); + })); + + function next_name() { + var name; + do { + name = nth_identifier.get(cname++); + } while (avoid.has(name) || ALL_RESERVED_WORDS.has(name)); + return name; + } + + function rename(def) { + if (def.global && options.cache) return; + if (def.unmangleable(options)) return; + if (options.reserved.has(def.name)) return; + const redefinition = redefined_catch_def(def); + const name = def.name = redefinition ? redefinition.name : next_name(); + def.orig.forEach(function(sym) { + sym.name = name; + }); + def.references.forEach(function(sym) { + sym.name = name; + }); + } +}); + +AST_Node.DEFMETHOD("tail_node", return_this); +AST_Sequence.DEFMETHOD("tail_node", function() { + return this.expressions[this.expressions.length - 1]; +}); + +AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) { + options = this._default_mangler_options(options); + var nth_identifier = options.nth_identifier; + if (!nth_identifier.reset || !nth_identifier.consider || !nth_identifier.sort) { + // If the identifier mangler is invariant, skip computing character frequency. + return; + } + nth_identifier.reset(); + + try { + AST_Node.prototype.print = function(stream, force_parens) { + this._print(stream, force_parens); + if (this instanceof AST_Symbol && !this.unmangleable(options)) { + nth_identifier.consider(this.name, -1); + } else if (options.properties) { + if (this instanceof AST_DotHash) { + nth_identifier.consider("#" + this.property, -1); + } else if (this instanceof AST_Dot) { + nth_identifier.consider(this.property, -1); + } else if (this instanceof AST_Sub) { + skip_string(this.property); + } + } + }; + nth_identifier.consider(this.print_to_string(), 1); + } finally { + AST_Node.prototype.print = AST_Node.prototype._print; + } + nth_identifier.sort(); + + function skip_string(node) { + if (node instanceof AST_String) { + nth_identifier.consider(node.value, -1); + } else if (node instanceof AST_Conditional) { + skip_string(node.consequent); + skip_string(node.alternative); + } else if (node instanceof AST_Sequence) { + skip_string(node.tail_node()); + } + } +}); + +const base54 = (() => { + const leading = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split(""); + const digits = "0123456789".split(""); + let chars; + let frequency; + function reset() { + frequency = new Map(); + leading.forEach(function(ch) { + frequency.set(ch, 0); + }); + digits.forEach(function(ch) { + frequency.set(ch, 0); + }); + } + function consider(str, delta) { + for (var i = str.length; --i >= 0;) { + frequency.set(str[i], frequency.get(str[i]) + delta); + } + } + function compare(a, b) { + return frequency.get(b) - frequency.get(a); + } + function sort() { + chars = mergeSort(leading, compare).concat(mergeSort(digits, compare)); + } + // Ensure this is in a usable initial state. + reset(); + sort(); + function base54(num) { + var ret = "", base = 54; + num++; + do { + num--; + ret += chars[num % base]; + num = Math.floor(num / base); + base = 64; + } while (num > 0); + return ret; + } + + return { + get: base54, + consider, + reset, + sort + }; +})(); + +export { + base54, + SymbolDef, +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/size.js b/node_modules/mathjs/examples/node_modules/terser/lib/size.js new file mode 100644 index 0000000..24ee39a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/size.js @@ -0,0 +1,490 @@ +import { + AST_Accessor, + AST_Array, + AST_Arrow, + AST_Await, + AST_BigInt, + AST_Binary, + AST_Block, + AST_Break, + AST_Call, + AST_Case, + AST_Class, + AST_ClassPrivateProperty, + AST_ClassProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Const, + AST_Continue, + AST_Debugger, + AST_Default, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DotHash, + AST_EmptyStatement, + AST_Expansion, + AST_Export, + AST_False, + AST_For, + AST_ForIn, + AST_Function, + AST_Hole, + AST_If, + AST_Import, + AST_ImportMeta, + AST_Infinity, + AST_LabeledStatement, + AST_Let, + AST_NameMapping, + AST_NaN, + AST_New, + AST_NewTarget, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectKeyVal, + AST_ObjectGetter, + AST_ObjectSetter, + AST_PrivateGetter, + AST_PrivateMethod, + AST_PrivateSetter, + AST_RegExp, + AST_Return, + AST_Sequence, + AST_String, + AST_Sub, + AST_Super, + AST_Switch, + AST_Symbol, + AST_SymbolClassProperty, + AST_SymbolExportForeign, + AST_SymbolImportForeign, + AST_SymbolRef, + AST_SymbolDeclaration, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Throw, + AST_Toplevel, + AST_True, + AST_Try, + AST_Catch, + AST_Finally, + AST_Unary, + AST_Undefined, + AST_Var, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, + walk_parent +} from "./ast.js"; +import { first_in_statement } from "./utils/first_in_statement.js"; + +let mangle_options = undefined; +AST_Node.prototype.size = function (compressor, stack) { + mangle_options = compressor && compressor.mangle_options; + + let size = 0; + walk_parent(this, (node, info) => { + size += node._size(info); + + // Braceless arrow functions have fake "return" statements + if (node instanceof AST_Arrow && node.is_braceless()) { + size += node.body[0].value._size(info); + return true; + } + }, stack || (compressor && compressor.stack)); + + // just to save a bit of memory + mangle_options = undefined; + + return size; +}; + +AST_Node.prototype._size = () => 0; + +AST_Debugger.prototype._size = () => 8; + +AST_Directive.prototype._size = function () { + // TODO string encoding stuff + return 2 + this.value.length; +}; + +const list_overhead = (array) => array.length && array.length - 1; + +AST_Block.prototype._size = function () { + return 2 + list_overhead(this.body); +}; + +AST_Toplevel.prototype._size = function() { + return list_overhead(this.body); +}; + +AST_EmptyStatement.prototype._size = () => 1; + +AST_LabeledStatement.prototype._size = () => 2; // x: + +AST_Do.prototype._size = () => 9; + +AST_While.prototype._size = () => 7; + +AST_For.prototype._size = () => 8; + +AST_ForIn.prototype._size = () => 8; +// AST_ForOf inherits ^ + +AST_With.prototype._size = () => 6; + +AST_Expansion.prototype._size = () => 3; + +const lambda_modifiers = func => + (func.is_generator ? 1 : 0) + (func.async ? 6 : 0); + +AST_Accessor.prototype._size = function () { + return lambda_modifiers(this) + 4 + list_overhead(this.argnames) + list_overhead(this.body); +}; + +AST_Function.prototype._size = function (info) { + const first = !!first_in_statement(info); + return (first * 2) + lambda_modifiers(this) + 12 + list_overhead(this.argnames) + list_overhead(this.body); +}; + +AST_Defun.prototype._size = function () { + return lambda_modifiers(this) + 13 + list_overhead(this.argnames) + list_overhead(this.body); +}; + +AST_Arrow.prototype._size = function () { + let args_and_arrow = 2 + list_overhead(this.argnames); + + if ( + !( + this.argnames.length === 1 + && this.argnames[0] instanceof AST_Symbol + ) + ) { + args_and_arrow += 2; + } + + const body_overhead = this.is_braceless() ? 0 : list_overhead(this.body) + 2; + + return lambda_modifiers(this) + args_and_arrow + body_overhead; +}; + +AST_Destructuring.prototype._size = () => 2; + +AST_TemplateString.prototype._size = function () { + return 2 + (Math.floor(this.segments.length / 2) * 3); /* "${}" */ +}; + +AST_TemplateSegment.prototype._size = function () { + return this.value.length; +}; + +AST_Return.prototype._size = function () { + return this.value ? 7 : 6; +}; + +AST_Throw.prototype._size = () => 6; + +AST_Break.prototype._size = function () { + return this.label ? 6 : 5; +}; + +AST_Continue.prototype._size = function () { + return this.label ? 9 : 8; +}; + +AST_If.prototype._size = () => 4; + +AST_Switch.prototype._size = function () { + return 8 + list_overhead(this.body); +}; + +AST_Case.prototype._size = function () { + return 5 + list_overhead(this.body); +}; + +AST_Default.prototype._size = function () { + return 8 + list_overhead(this.body); +}; + +AST_Try.prototype._size = function () { + return 3 + list_overhead(this.body); +}; + +AST_Catch.prototype._size = function () { + let size = 7 + list_overhead(this.body); + if (this.argname) { + size += 2; + } + return size; +}; + +AST_Finally.prototype._size = function () { + return 7 + list_overhead(this.body); +}; + +/*#__INLINE__*/ +const def_size = (size, def) => size + list_overhead(def.definitions); + +AST_Var.prototype._size = function () { + return def_size(4, this); +}; + +AST_Let.prototype._size = function () { + return def_size(4, this); +}; + +AST_Const.prototype._size = function () { + return def_size(6, this); +}; + +AST_VarDef.prototype._size = function () { + return this.value ? 1 : 0; +}; + +AST_NameMapping.prototype._size = function () { + // foreign name isn't mangled + return this.name ? 4 : 0; +}; + +AST_Import.prototype._size = function () { + // import + let size = 6; + + if (this.imported_name) size += 1; + + // from + if (this.imported_name || this.imported_names) size += 5; + + // braces, and the commas + if (this.imported_names) { + size += 2 + list_overhead(this.imported_names); + } + + return size; +}; + +AST_ImportMeta.prototype._size = () => 11; + +AST_Export.prototype._size = function () { + let size = 7 + (this.is_default ? 8 : 0); + + if (this.exported_value) { + size += this.exported_value._size(); + } + + if (this.exported_names) { + // Braces and commas + size += 2 + list_overhead(this.exported_names); + } + + if (this.module_name) { + // "from " + size += 5; + } + + return size; +}; + +AST_Call.prototype._size = function () { + if (this.optional) { + return 4 + list_overhead(this.args); + } + return 2 + list_overhead(this.args); +}; + +AST_New.prototype._size = function () { + return 6 + list_overhead(this.args); +}; + +AST_Sequence.prototype._size = function () { + return list_overhead(this.expressions); +}; + +AST_Dot.prototype._size = function () { + if (this.optional) { + return this.property.length + 2; + } + return this.property.length + 1; +}; + +AST_DotHash.prototype._size = function () { + if (this.optional) { + return this.property.length + 3; + } + return this.property.length + 2; +}; + +AST_Sub.prototype._size = function () { + return this.optional ? 4 : 2; +}; + +AST_Unary.prototype._size = function () { + if (this.operator === "typeof") return 7; + if (this.operator === "void") return 5; + return this.operator.length; +}; + +AST_Binary.prototype._size = function (info) { + if (this.operator === "in") return 4; + + let size = this.operator.length; + + if ( + (this.operator === "+" || this.operator === "-") + && this.right instanceof AST_Unary && this.right.operator === this.operator + ) { + // 1+ +a > needs space between the + + size += 1; + } + + if (this.needs_parens(info)) { + size += 2; + } + + return size; +}; + +AST_Conditional.prototype._size = () => 3; + +AST_Array.prototype._size = function () { + return 2 + list_overhead(this.elements); +}; + +AST_Object.prototype._size = function (info) { + let base = 2; + if (first_in_statement(info)) { + base += 2; // parens + } + return base + list_overhead(this.properties); +}; + +/*#__INLINE__*/ +const key_size = key => + typeof key === "string" ? key.length : 0; + +AST_ObjectKeyVal.prototype._size = function () { + return key_size(this.key) + 1; +}; + +/*#__INLINE__*/ +const static_size = is_static => is_static ? 7 : 0; + +AST_ObjectGetter.prototype._size = function () { + return 5 + static_size(this.static) + key_size(this.key); +}; + +AST_ObjectSetter.prototype._size = function () { + return 5 + static_size(this.static) + key_size(this.key); +}; + +AST_ConciseMethod.prototype._size = function () { + return static_size(this.static) + key_size(this.key) + lambda_modifiers(this); +}; + +AST_PrivateMethod.prototype._size = function () { + return AST_ConciseMethod.prototype._size.call(this) + 1; +}; + +AST_PrivateGetter.prototype._size = AST_PrivateSetter.prototype._size = function () { + return AST_ConciseMethod.prototype._size.call(this) + 4; +}; + +AST_Class.prototype._size = function () { + return ( + (this.name ? 8 : 7) + + (this.extends ? 8 : 0) + ); +}; + +AST_ClassProperty.prototype._size = function () { + return ( + static_size(this.static) + + (typeof this.key === "string" ? this.key.length + 2 : 0) + + (this.value ? 1 : 0) + ); +}; + +AST_ClassPrivateProperty.prototype._size = function () { + return AST_ClassProperty.prototype._size.call(this) + 1; +}; + +AST_Symbol.prototype._size = function () { + return !mangle_options || this.definition().unmangleable(mangle_options) + ? this.name.length + : 1; +}; + +// TODO take propmangle into account +AST_SymbolClassProperty.prototype._size = function () { + return this.name.length; +}; + +AST_SymbolRef.prototype._size = AST_SymbolDeclaration.prototype._size = function () { + const { name, thedef } = this; + + if (thedef && thedef.global) return name.length; + + if (name === "arguments") return 9; + + return AST_Symbol.prototype._size.call(this); +}; + +AST_NewTarget.prototype._size = () => 10; + +AST_SymbolImportForeign.prototype._size = function () { + return this.name.length; +}; + +AST_SymbolExportForeign.prototype._size = function () { + return this.name.length; +}; + +AST_This.prototype._size = () => 4; + +AST_Super.prototype._size = () => 5; + +AST_String.prototype._size = function () { + return this.value.length + 2; +}; + +AST_Number.prototype._size = function () { + const { value } = this; + if (value === 0) return 1; + if (value > 0 && Math.floor(value) === value) { + return Math.floor(Math.log10(value) + 1); + } + return value.toString().length; +}; + +AST_BigInt.prototype._size = function () { + return this.value.length; +}; + +AST_RegExp.prototype._size = function () { + return this.value.toString().length; +}; + +AST_Null.prototype._size = () => 4; + +AST_NaN.prototype._size = () => 3; + +AST_Undefined.prototype._size = () => 6; // "void 0" + +AST_Hole.prototype._size = () => 0; // comma is taken into account + +AST_Infinity.prototype._size = () => 8; + +AST_True.prototype._size = () => 4; + +AST_False.prototype._size = () => 5; + +AST_Await.prototype._size = () => 6; + +AST_Yield.prototype._size = () => 6; diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/sourcemap.js b/node_modules/mathjs/examples/node_modules/terser/lib/sourcemap.js new file mode 100644 index 0000000..178a208 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/sourcemap.js @@ -0,0 +1,114 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +import MOZ_SourceMap from "source-map"; +import { + defaults, +} from "./utils/index.js"; + +// a small wrapper around fitzgen's source-map library +async function SourceMap(options) { + options = defaults(options, { + file : null, + root : null, + orig : null, + + orig_line_diff : 0, + dest_line_diff : 0, + }); + + var orig_map; + var generator = new MOZ_SourceMap.SourceMapGenerator({ + file : options.file, + sourceRoot : options.root + }); + + if (options.orig) { + orig_map = await new MOZ_SourceMap.SourceMapConsumer(options.orig); + orig_map.sources.forEach(function(source) { + var sourceContent = orig_map.sourceContentFor(source, true); + if (sourceContent) { + generator.setSourceContent(source, sourceContent); + } + }); + } + + function add(source, gen_line, gen_col, orig_line, orig_col, name) { + if (orig_map) { + var info = orig_map.originalPositionFor({ + line: orig_line, + column: orig_col + }); + if (info.source === null) { + return; + } + source = info.source; + orig_line = info.line; + orig_col = info.column; + name = info.name || name; + } + generator.addMapping({ + generated : { line: gen_line + options.dest_line_diff, column: gen_col }, + original : { line: orig_line + options.orig_line_diff, column: orig_col }, + source : source, + name : name + }); + } + + return { + add : add, + get : function() { return generator; }, + toString : function() { return generator.toString(); }, + destroy : function () { + if (orig_map && orig_map.destroy) { + orig_map.destroy(); + } + } + }; +} + +export { + SourceMap, +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/transform.js b/node_modules/mathjs/examples/node_modules/terser/lib/transform.js new file mode 100644 index 0000000..346ae59 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/transform.js @@ -0,0 +1,318 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +import { + AST_Array, + AST_Await, + AST_Binary, + AST_Block, + AST_Call, + AST_Case, + AST_Catch, + AST_Chain, + AST_Class, + AST_Conditional, + AST_Definitions, + AST_Destructuring, + AST_Do, + AST_Exit, + AST_Expansion, + AST_Export, + AST_For, + AST_ForIn, + AST_If, + AST_Import, + AST_LabeledStatement, + AST_Lambda, + AST_LoopControl, + AST_NameMapping, + AST_Node, + AST_Number, + AST_Object, + AST_ObjectProperty, + AST_PrefixedTemplateString, + AST_PropAccess, + AST_Sequence, + AST_SimpleStatement, + AST_Sub, + AST_Switch, + AST_TemplateString, + AST_Try, + AST_Unary, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, +} from "./ast.js"; +import { + MAP, + noop, +} from "./utils/index.js"; + +function def_transform(node, descend) { + node.DEFMETHOD("transform", function(tw, in_list) { + let transformed = undefined; + tw.push(this); + if (tw.before) transformed = tw.before(this, descend, in_list); + if (transformed === undefined) { + transformed = this; + descend(transformed, tw); + if (tw.after) { + const after_ret = tw.after(transformed, in_list); + if (after_ret !== undefined) transformed = after_ret; + } + } + tw.pop(); + return transformed; + }); +} + +function do_list(list, tw) { + return MAP(list, function(node) { + return node.transform(tw, true); + }); +} + +def_transform(AST_Node, noop); + +def_transform(AST_LabeledStatement, function(self, tw) { + self.label = self.label.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_SimpleStatement, function(self, tw) { + self.body = self.body.transform(tw); +}); + +def_transform(AST_Block, function(self, tw) { + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Do, function(self, tw) { + self.body = self.body.transform(tw); + self.condition = self.condition.transform(tw); +}); + +def_transform(AST_While, function(self, tw) { + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_For, function(self, tw) { + if (self.init) self.init = self.init.transform(tw); + if (self.condition) self.condition = self.condition.transform(tw); + if (self.step) self.step = self.step.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_ForIn, function(self, tw) { + self.init = self.init.transform(tw); + self.object = self.object.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_With, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_Exit, function(self, tw) { + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_LoopControl, function(self, tw) { + if (self.label) self.label = self.label.transform(tw); +}); + +def_transform(AST_If, function(self, tw) { + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + if (self.alternative) self.alternative = self.alternative.transform(tw); +}); + +def_transform(AST_Switch, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Case, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Try, function(self, tw) { + self.body = do_list(self.body, tw); + if (self.bcatch) self.bcatch = self.bcatch.transform(tw); + if (self.bfinally) self.bfinally = self.bfinally.transform(tw); +}); + +def_transform(AST_Catch, function(self, tw) { + if (self.argname) self.argname = self.argname.transform(tw); + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Definitions, function(self, tw) { + self.definitions = do_list(self.definitions, tw); +}); + +def_transform(AST_VarDef, function(self, tw) { + self.name = self.name.transform(tw); + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_Destructuring, function(self, tw) { + self.names = do_list(self.names, tw); +}); + +def_transform(AST_Lambda, function(self, tw) { + if (self.name) self.name = self.name.transform(tw); + self.argnames = do_list(self.argnames, tw); + if (self.body instanceof AST_Node) { + self.body = self.body.transform(tw); + } else { + self.body = do_list(self.body, tw); + } +}); + +def_transform(AST_Call, function(self, tw) { + self.expression = self.expression.transform(tw); + self.args = do_list(self.args, tw); +}); + +def_transform(AST_Sequence, function(self, tw) { + const result = do_list(self.expressions, tw); + self.expressions = result.length + ? result + : [new AST_Number({ value: 0 })]; +}); + +def_transform(AST_PropAccess, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Sub, function(self, tw) { + self.expression = self.expression.transform(tw); + self.property = self.property.transform(tw); +}); + +def_transform(AST_Chain, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Yield, function(self, tw) { + if (self.expression) self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Await, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Unary, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Binary, function(self, tw) { + self.left = self.left.transform(tw); + self.right = self.right.transform(tw); +}); + +def_transform(AST_Conditional, function(self, tw) { + self.condition = self.condition.transform(tw); + self.consequent = self.consequent.transform(tw); + self.alternative = self.alternative.transform(tw); +}); + +def_transform(AST_Array, function(self, tw) { + self.elements = do_list(self.elements, tw); +}); + +def_transform(AST_Object, function(self, tw) { + self.properties = do_list(self.properties, tw); +}); + +def_transform(AST_ObjectProperty, function(self, tw) { + if (self.key instanceof AST_Node) { + self.key = self.key.transform(tw); + } + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_Class, function(self, tw) { + if (self.name) self.name = self.name.transform(tw); + if (self.extends) self.extends = self.extends.transform(tw); + self.properties = do_list(self.properties, tw); +}); + +def_transform(AST_Expansion, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_NameMapping, function(self, tw) { + self.foreign_name = self.foreign_name.transform(tw); + self.name = self.name.transform(tw); +}); + +def_transform(AST_Import, function(self, tw) { + if (self.imported_name) self.imported_name = self.imported_name.transform(tw); + if (self.imported_names) do_list(self.imported_names, tw); + self.module_name = self.module_name.transform(tw); +}); + +def_transform(AST_Export, function(self, tw) { + if (self.exported_definition) self.exported_definition = self.exported_definition.transform(tw); + if (self.exported_value) self.exported_value = self.exported_value.transform(tw); + if (self.exported_names) do_list(self.exported_names, tw); + if (self.module_name) self.module_name = self.module_name.transform(tw); +}); + +def_transform(AST_TemplateString, function(self, tw) { + self.segments = do_list(self.segments, tw); +}); + +def_transform(AST_PrefixedTemplateString, function(self, tw) { + self.prefix = self.prefix.transform(tw); + self.template_string = self.template_string.transform(tw); +}); + diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/utils/first_in_statement.js b/node_modules/mathjs/examples/node_modules/terser/lib/utils/first_in_statement.js new file mode 100644 index 0000000..19228b6 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/utils/first_in_statement.js @@ -0,0 +1,50 @@ +import { + AST_Binary, + AST_Conditional, + AST_Dot, + AST_Object, + AST_Sequence, + AST_Statement, + AST_Sub, + AST_UnaryPostfix, + AST_PrefixedTemplateString +} from "../ast.js"; + +// return true if the node at the top of the stack (that means the +// innermost node in the current output) is lexically the first in +// a statement. +function first_in_statement(stack) { + let node = stack.parent(-1); + for (let i = 0, p; p = stack.parent(i); i++) { + if (p instanceof AST_Statement && p.body === node) + return true; + if ((p instanceof AST_Sequence && p.expressions[0] === node) || + (p.TYPE === "Call" && p.expression === node) || + (p instanceof AST_PrefixedTemplateString && p.prefix === node) || + (p instanceof AST_Dot && p.expression === node) || + (p instanceof AST_Sub && p.expression === node) || + (p instanceof AST_Conditional && p.condition === node) || + (p instanceof AST_Binary && p.left === node) || + (p instanceof AST_UnaryPostfix && p.expression === node) + ) { + node = p; + } else { + return false; + } + } +} + +// Returns whether the leftmost item in the expression is an object +function left_is_object(node) { + if (node instanceof AST_Object) return true; + if (node instanceof AST_Sequence) return left_is_object(node.expressions[0]); + if (node.TYPE === "Call") return left_is_object(node.expression); + if (node instanceof AST_PrefixedTemplateString) return left_is_object(node.prefix); + if (node instanceof AST_Dot || node instanceof AST_Sub) return left_is_object(node.expression); + if (node instanceof AST_Conditional) return left_is_object(node.condition); + if (node instanceof AST_Binary) return left_is_object(node.left); + if (node instanceof AST_UnaryPostfix) return left_is_object(node.expression); + return false; +} + +export { first_in_statement, left_is_object }; diff --git a/node_modules/mathjs/examples/node_modules/terser/lib/utils/index.js b/node_modules/mathjs/examples/node_modules/terser/lib/utils/index.js new file mode 100644 index 0000000..df86464 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/lib/utils/index.js @@ -0,0 +1,302 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +function characters(str) { + return str.split(""); +} + +function member(name, array) { + return array.includes(name); +} + +class DefaultsError extends Error { + constructor(msg, defs) { + super(); + + this.name = "DefaultsError"; + this.message = msg; + this.defs = defs; + } +} + +function defaults(args, defs, croak) { + if (args === true) { + args = {}; + } else if (args != null && typeof args === "object") { + args = {...args}; + } + + const ret = args || {}; + + if (croak) for (const i in ret) if (HOP(ret, i) && !HOP(defs, i)) { + throw new DefaultsError("`" + i + "` is not a supported option", defs); + } + + for (const i in defs) if (HOP(defs, i)) { + if (!args || !HOP(args, i)) { + ret[i] = defs[i]; + } else if (i === "ecma") { + let ecma = args[i] | 0; + if (ecma > 5 && ecma < 2015) ecma += 2009; + ret[i] = ecma; + } else { + ret[i] = (args && HOP(args, i)) ? args[i] : defs[i]; + } + } + + return ret; +} + +function noop() {} +function return_false() { return false; } +function return_true() { return true; } +function return_this() { return this; } +function return_null() { return null; } + +var MAP = (function() { + function MAP(a, f, backwards) { + var ret = [], top = [], i; + function doit() { + var val = f(a[i], i); + var is_last = val instanceof Last; + if (is_last) val = val.v; + if (val instanceof AtTop) { + val = val.v; + if (val instanceof Splice) { + top.push.apply(top, backwards ? val.v.slice().reverse() : val.v); + } else { + top.push(val); + } + } else if (val !== skip) { + if (val instanceof Splice) { + ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v); + } else { + ret.push(val); + } + } + return is_last; + } + if (Array.isArray(a)) { + if (backwards) { + for (i = a.length; --i >= 0;) if (doit()) break; + ret.reverse(); + top.reverse(); + } else { + for (i = 0; i < a.length; ++i) if (doit()) break; + } + } else { + for (i in a) if (HOP(a, i)) if (doit()) break; + } + return top.concat(ret); + } + MAP.at_top = function(val) { return new AtTop(val); }; + MAP.splice = function(val) { return new Splice(val); }; + MAP.last = function(val) { return new Last(val); }; + var skip = MAP.skip = {}; + function AtTop(val) { this.v = val; } + function Splice(val) { this.v = val; } + function Last(val) { this.v = val; } + return MAP; +})(); + +function make_node(ctor, orig, props) { + if (!props) props = {}; + if (orig) { + if (!props.start) props.start = orig.start; + if (!props.end) props.end = orig.end; + } + return new ctor(props); +} + +function push_uniq(array, el) { + if (!array.includes(el)) + array.push(el); +} + +function string_template(text, props) { + return text.replace(/{(.+?)}/g, function(str, p) { + return props && props[p]; + }); +} + +function remove(array, el) { + for (var i = array.length; --i >= 0;) { + if (array[i] === el) array.splice(i, 1); + } +} + +function mergeSort(array, cmp) { + if (array.length < 2) return array.slice(); + function merge(a, b) { + var r = [], ai = 0, bi = 0, i = 0; + while (ai < a.length && bi < b.length) { + cmp(a[ai], b[bi]) <= 0 + ? r[i++] = a[ai++] + : r[i++] = b[bi++]; + } + if (ai < a.length) r.push.apply(r, a.slice(ai)); + if (bi < b.length) r.push.apply(r, b.slice(bi)); + return r; + } + function _ms(a) { + if (a.length <= 1) + return a; + var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m); + left = _ms(left); + right = _ms(right); + return merge(left, right); + } + return _ms(array); +} + +function makePredicate(words) { + if (!Array.isArray(words)) words = words.split(" "); + + return new Set(words.sort()); +} + +function map_add(map, key, value) { + if (map.has(key)) { + map.get(key).push(value); + } else { + map.set(key, [ value ]); + } +} + +function map_from_object(obj) { + var map = new Map(); + for (var key in obj) { + if (HOP(obj, key) && key.charAt(0) === "$") { + map.set(key.substr(1), obj[key]); + } + } + return map; +} + +function map_to_object(map) { + var obj = Object.create(null); + map.forEach(function (value, key) { + obj["$" + key] = value; + }); + return obj; +} + +function HOP(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +function keep_name(keep_setting, name) { + return keep_setting === true + || (keep_setting instanceof RegExp && keep_setting.test(name)); +} + +var lineTerminatorEscape = { + "\0": "0", + "\n": "n", + "\r": "r", + "\u2028": "u2028", + "\u2029": "u2029", +}; +function regexp_source_fix(source) { + // V8 does not escape line terminators in regexp patterns in node 12 + // We'll also remove literal \0 + return source.replace(/[\0\n\r\u2028\u2029]/g, function (match, offset) { + var escaped = source[offset - 1] == "\\" + && (source[offset - 2] != "\\" + || /(?:^|[^\\])(?:\\{2})*$/.test(source.slice(0, offset - 1))); + return (escaped ? "" : "\\") + lineTerminatorEscape[match]; + }); +} +const all_flags = "gimuy"; +function sort_regexp_flags(flags) { + const existing_flags = new Set(flags.split("")); + let out = ""; + for (const flag of all_flags) { + if (existing_flags.has(flag)) { + out += flag; + existing_flags.delete(flag); + } + } + if (existing_flags.size) { + // Flags Terser doesn't know about + existing_flags.forEach(flag => { out += flag; }); + } + return out; +} + +function has_annotation(node, annotation) { + return node._annotations & annotation; +} + +function set_annotation(node, annotation) { + node._annotations |= annotation; +} + +export { + characters, + defaults, + HOP, + keep_name, + make_node, + makePredicate, + map_add, + map_from_object, + map_to_object, + MAP, + member, + mergeSort, + noop, + push_uniq, + regexp_source_fix, + remove, + return_false, + return_null, + return_this, + return_true, + sort_regexp_flags, + string_template, + has_annotation, + set_annotation +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/main.js b/node_modules/mathjs/examples/node_modules/terser/main.js new file mode 100644 index 0000000..0a10db5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/main.js @@ -0,0 +1,27 @@ +import "./lib/transform.js"; +import "./lib/mozilla-ast.js"; +import { minify } from "./lib/minify.js"; + +export { minify } from "./lib/minify.js"; +export { run_cli as _run_cli } from "./lib/cli.js"; + +export async function _default_options() { + const defs = {}; + + Object.keys(infer_options({ 0: 0 })).forEach((component) => { + const options = infer_options({ + [component]: {0: 0} + }); + + if (options) defs[component] = options; + }); + return defs; +} + +async function infer_options(options) { + try { + await minify("", options); + } catch (error) { + return error.defs; + } +} diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/CHANGELOG.md b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/CHANGELOG.md new file mode 100644 index 0000000..ef31a09 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/CHANGELOG.md @@ -0,0 +1,344 @@ +# Change Log + +## 0.7.3 + +* Fix a bug where nested uses of `SourceMapConsumer` could result in a + `TypeError`. [#338](https://github.com/mozilla/source-map/issues/338) + [#330](https://github.com/mozilla/source-map/issues/330) + [#319](https://github.com/mozilla/source-map/issues/319) + +## 0.7.2 + +* Another 3x speed up in `SourceMapConsumer`. Read about it here: + http://fitzgeraldnick.com/2018/02/26/speed-without-wizardry.html + +## 0.7.1 + +* Updated TypeScript typings. [#321][] + +[#321]: https://github.com/mozilla/source-map/pull/321 + +## 0.7.0 + +* `SourceMapConsumer` now uses WebAssembly, and is **much** faster! Read about + it here: + https://hacks.mozilla.org/2018/01/oxidizing-source-maps-with-rust-and-webassembly/ + +* **Breaking change:** `new SourceMapConsumer` now returns a `Promise` object + that resolves to the newly constructed `SourceMapConsumer` instance, rather + than returning the new instance immediately. + +* **Breaking change:** when you're done using a `SourceMapConsumer` instance, + you must call `SourceMapConsumer.prototype.destroy` on it. After calling + `destroy`, you must not use the instance again. + +* **Breaking change:** `SourceMapConsumer` used to be able to handle lines, + columns numbers and source and name indices up to `2^53 - 1` (aka + `Number.MAX_SAFE_INTEGER`). It can now only handle them up to `2^32 - 1`. + +* **Breaking change:** The `source-map` library now uses modern ECMAScript-isms: + `let`, arrow functions, `async`, etc. Use Babel to compile it down to + ECMAScript 5 if you need to support older JavaScript environments. + +* **Breaking change:** Drop support for Node < 8. If you want to support older +versions of node, please use v0.6 or below. + +## 0.5.6 + +* Fix for regression when people were using numbers as names in source maps. See + #236. + +## 0.5.5 + +* Fix "regression" of unsupported, implementation behavior that half the world + happens to have come to depend on. See #235. + +* Fix regression involving function hoisting in SpiderMonkey. See #233. + +## 0.5.4 + +* Large performance improvements to source-map serialization. See #228 and #229. + +## 0.5.3 + +* Do not include unnecessary distribution files. See + commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86. + +## 0.5.2 + +* Include browser distributions of the library in package.json's `files`. See + issue #212. + +## 0.5.1 + +* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See + ff05274becc9e6e1295ed60f3ea090d31d843379. + +## 0.5.0 + +* Node 0.8 is no longer supported. + +* Use webpack instead of dryice for bundling. + +* Big speedups serializing source maps. See pull request #203. + +* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that + explicitly start with the source root. See issue #199. + +## 0.4.4 + +* Fix an issue where using a `SourceMapGenerator` after having created a + `SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See + issue #191. + +* Fix an issue with where `SourceMapGenerator` would mistakenly consider + different mappings as duplicates of each other and avoid generating them. See + issue #192. + +## 0.4.3 + +* A very large number of performance improvements, particularly when parsing + source maps. Collectively about 75% of time shaved off of the source map + parsing benchmark! + +* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy + searching in the presence of a column option. See issue #177. + +* Fix a bug with joining a source and its source root when the source is above + the root. See issue #182. + +* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to + determine when all sources' contents are inlined into the source map. See + issue #190. + +## 0.4.2 + +* Add an `.npmignore` file so that the benchmarks aren't pulled down by + dependent projects. Issue #169. + +* Add an optional `column` argument to + `SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines + with no mappings. Issues #172 and #173. + +## 0.4.1 + +* Fix accidentally defining a global variable. #170. + +## 0.4.0 + +* The default direction for fuzzy searching was changed back to its original + direction. See #164. + +* There is now a `bias` option you can supply to `SourceMapConsumer` to control + the fuzzy searching direction. See #167. + +* About an 8% speed up in parsing source maps. See #159. + +* Added a benchmark for parsing and generating source maps. + +## 0.3.0 + +* Change the default direction that searching for positions fuzzes when there is + not an exact match. See #154. + +* Support for environments using json2.js for JSON serialization. See #156. + +## 0.2.0 + +* Support for consuming "indexed" source maps which do not have any remote + sections. See pull request #127. This introduces a minor backwards + incompatibility if you are monkey patching `SourceMapConsumer.prototype` + methods. + +## 0.1.43 + +* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue + #148 for some discussion and issues #150, #151, and #152 for implementations. + +## 0.1.42 + +* Fix an issue where `SourceNode`s from different versions of the source-map + library couldn't be used in conjunction with each other. See issue #142. + +## 0.1.41 + +* Fix a bug with getting the source content of relative sources with a "./" + prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768). + +* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the + column span of each mapping. + +* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find + all generated positions associated with a given original source and line. + +## 0.1.40 + +* Performance improvements for parsing source maps in SourceMapConsumer. + +## 0.1.39 + +* Fix a bug where setting a source's contents to null before any source content + had been set before threw a TypeError. See issue #131. + +## 0.1.38 + +* Fix a bug where finding relative paths from an empty path were creating + absolute paths. See issue #129. + +## 0.1.37 + +* Fix a bug where if the source root was an empty string, relative source paths + would turn into absolute source paths. Issue #124. + +## 0.1.36 + +* Allow the `names` mapping property to be an empty string. Issue #121. + +## 0.1.35 + +* A third optional parameter was added to `SourceNode.fromStringWithSourceMap` + to specify a path that relative sources in the second parameter should be + relative to. Issue #105. + +* If no file property is given to a `SourceMapGenerator`, then the resulting + source map will no longer have a `null` file property. The property will + simply not exist. Issue #104. + +* Fixed a bug where consecutive newlines were ignored in `SourceNode`s. + Issue #116. + +## 0.1.34 + +* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103. + +* Fix bug involving source contents and the + `SourceMapGenerator.prototype.applySourceMap`. Issue #100. + +## 0.1.33 + +* Fix some edge cases surrounding path joining and URL resolution. + +* Add a third parameter for relative path to + `SourceMapGenerator.prototype.applySourceMap`. + +* Fix issues with mappings and EOLs. + +## 0.1.32 + +* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns + (issue 92). + +* Fixed test runner to actually report number of failed tests as its process + exit code. + +* Fixed a typo when reporting bad mappings (issue 87). + +## 0.1.31 + +* Delay parsing the mappings in SourceMapConsumer until queried for a source + location. + +* Support Sass source maps (which at the time of writing deviate from the spec + in small ways) in SourceMapConsumer. + +## 0.1.30 + +* Do not join source root with a source, when the source is a data URI. + +* Extend the test runner to allow running single specific test files at a time. + +* Performance improvements in `SourceNode.prototype.walk` and + `SourceMapConsumer.prototype.eachMapping`. + +* Source map browser builds will now work inside Workers. + +* Better error messages when attempting to add an invalid mapping to a + `SourceMapGenerator`. + +## 0.1.29 + +* Allow duplicate entries in the `names` and `sources` arrays of source maps + (usually from TypeScript) we are parsing. Fixes github issue 72. + +## 0.1.28 + +* Skip duplicate mappings when creating source maps from SourceNode; github + issue 75. + +## 0.1.27 + +* Don't throw an error when the `file` property is missing in SourceMapConsumer, + we don't use it anyway. + +## 0.1.26 + +* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70. + +## 0.1.25 + +* Make compatible with browserify + +## 0.1.24 + +* Fix issue with absolute paths and `file://` URIs. See + https://bugzilla.mozilla.org/show_bug.cgi?id=885597 + +## 0.1.23 + +* Fix issue with absolute paths and sourcesContent, github issue 64. + +## 0.1.22 + +* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21. + +## 0.1.21 + +* Fixed handling of sources that start with a slash so that they are relative to + the source root's host. + +## 0.1.20 + +* Fixed github issue #43: absolute URLs aren't joined with the source root + anymore. + +## 0.1.19 + +* Using Travis CI to run tests. + +## 0.1.18 + +* Fixed a bug in the handling of sourceRoot. + +## 0.1.17 + +* Added SourceNode.fromStringWithSourceMap. + +## 0.1.16 + +* Added missing documentation. + +* Fixed the generating of empty mappings in SourceNode. + +## 0.1.15 + +* Added SourceMapGenerator.applySourceMap. + +## 0.1.14 + +* The sourceRoot is now handled consistently. + +## 0.1.13 + +* Added SourceMapGenerator.fromSourceMap. + +## 0.1.12 + +* SourceNode now generates empty mappings too. + +## 0.1.11 + +* Added name support to SourceNode. + +## 0.1.10 + +* Added sourcesContent support to the customer and generator. diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/LICENSE b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/LICENSE new file mode 100644 index 0000000..ed1b7cf --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/LICENSE @@ -0,0 +1,28 @@ + +Copyright (c) 2009-2011, Mozilla Foundation and contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the names of the Mozilla Foundation nor the names of project + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/README.md b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/README.md new file mode 100644 index 0000000..db20846 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/README.md @@ -0,0 +1,822 @@ +# Source Map + +[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) + +[![Coverage Status](https://coveralls.io/repos/github/mozilla/source-map/badge.svg)](https://coveralls.io/github/mozilla/source-map) + +[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) + +This is a library to generate and consume the source map format +[described here][format]. + +[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit + +## Use with Node + + $ npm install source-map + +## Use on the Web + + + + +-------------------------------------------------------------------------------- + + + + + +## Table of Contents + +- [Examples](#examples) + - [Consuming a source map](#consuming-a-source-map) + - [Generating a source map](#generating-a-source-map) + - [With SourceNode (high level API)](#with-sourcenode-high-level-api) + - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) +- [API](#api) + - [SourceMapConsumer](#sourcemapconsumer) + - [SourceMapConsumer.initialize(options)](#sourcemapconsumerinitializeoptions) + - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) + - [SourceMapConsumer.with](#sourcemapconsumerwith) + - [SourceMapConsumer.prototype.destroy()](#sourcemapconsumerprototypedestroy) + - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) + - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) + - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) + - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) + - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) + - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) + - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) + - [SourceMapGenerator](#sourcemapgenerator) + - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) + - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) + - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) + - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) + - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) + - [SourceNode](#sourcenode) + - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) + - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) + - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) + - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) + - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) + - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) + - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) + - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) + - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) + - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) + + + +## Examples + +### Consuming a source map + +```js +const rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' +}; + +const whatever = await SourceMapConsumer.with(rawSourceMap, null, consumer => { + + console.log(consumer.sources); + // [ 'http://example.com/www/js/one.js', + // 'http://example.com/www/js/two.js' ] + + console.log(consumer.originalPositionFor({ + line: 2, + column: 28 + })); + // { source: 'http://example.com/www/js/two.js', + // line: 2, + // column: 10, + // name: 'n' } + + console.log(consumer.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10 + })); + // { line: 2, column: 28 } + + consumer.eachMapping(function (m) { + // ... + }); + + return computeWhatever(); +}); +``` + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + +```js +function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), " + ", compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error("Bad AST"); + } +} + +var ast = parse("40 + 2", "add.js"); +console.log(compile(ast).toStringWithSourceMap({ + file: 'add.js' +})); +// { code: '40 + 2', +// map: [object SourceMapGenerator] } +``` + +#### With SourceMapGenerator (low level API) + +```js +var map = new SourceMapGenerator({ + file: "source-mapped.js" +}); + +map.addMapping({ + generated: { + line: 10, + column: 35 + }, + source: "foo.js", + original: { + line: 33, + column: 2 + }, + name: "christopher" +}); + +console.log(map.toString()); +// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' +``` + +## API + +Get a reference to the module: + +```js +// Node.js +var sourceMap = require('source-map'); + +// Browser builds +var sourceMap = window.sourceMap; + +// Inside Firefox +const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); +``` + +### SourceMapConsumer + +A `SourceMapConsumer` instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### SourceMapConsumer.initialize(options) + +When using `SourceMapConsumer` outside of node.js, for example on the Web, it +needs to know from what URL to load `lib/mappings.wasm`. You must inform it by +calling `initialize` before constructing any `SourceMapConsumer`s. + +The options object has the following properties: + +* `"lib/mappings.wasm"`: A `String` containing the URL of the + `lib/mappings.wasm` file. + +```js +sourceMap.SourceMapConsumer.initialize({ + "lib/mappings.wasm": "https://example.com/source-map/lib/mappings.wasm" +}); +``` + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +* `version`: Which version of the source map spec this map is following. + +* `sources`: An array of URLs to the original source files. + +* `names`: An array of identifiers which can be referenced by individual + mappings. + +* `sourceRoot`: Optional. The URL root from which all sources are relative. + +* `sourcesContent`: Optional. An array of contents of the original source files. + +* `mappings`: A string of base64 VLQs which contain the actual mappings. + +* `file`: Optional. The generated filename this source map is associated with. + +The promise of the constructed souce map consumer is returned. + +When the `SourceMapConsumer` will no longer be used anymore, you must call its +`destroy` method. + +```js +const consumer = await new sourceMap.SourceMapConsumer(rawSourceMapJsonData); +doStuffWith(consumer); +consumer.destroy(); +``` + +Alternatively, you can use `SourceMapConsumer.with` to avoid needing to remember +to call `destroy`. + +#### SourceMapConsumer.with + +Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl` +(see the `SourceMapConsumer` constructor for details. Then, invoke the `async +function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait +for `f` to complete, call `destroy` on the consumer, and return `f`'s return +value. + +You must not use the consumer after `f` completes! + +By using `with`, you do not have to remember to manually call `destroy` on +the consumer, since it will be called automatically once `f` completes. + +```js +const xSquared = await SourceMapConsumer.with( + myRawSourceMap, + null, + async function (consumer) { + // Use `consumer` inside here and don't worry about remembering + // to call `destroy`. + + const x = await whatever(consumer); + return x * x; + } +); + +// You may not use that `consumer` anymore out here; it has +// been destroyed. But you can use `xSquared`. +console.log(xSquared); +``` + +#### SourceMapConsumer.prototype.destroy() + +Free this source map consumer's associated wasm data that is manually-managed. + +```js +consumer.destroy(); +``` + +Alternatively, you can use `SourceMapConsumer.with` to avoid needing to remember +to call `destroy`. + +#### SourceMapConsumer.prototype.computeColumnSpans() + +Compute the last column for each generated mapping. The last column is +inclusive. + +```js +// Before: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] + +consumer.computeColumnSpans(); + +// After: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1, +// lastColumn: 9 }, +// { line: 2, +// column: 10, +// lastColumn: 19 }, +// { line: 2, +// column: 20, +// lastColumn: Infinity } ] +``` + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +* `line`: The line number in the generated source. Line numbers in + this library are 1-based (note that the underlying source map + specification uses 0-based line numbers -- this library handles the + translation). + +* `column`: The column number in the generated source. Column numbers + in this library are 0-based. + +* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or + `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest + element that is smaller than or greater than the one we are searching for, + respectively, if the exact element cannot be found. Defaults to + `SourceMapConsumer.GREATEST_LOWER_BOUND`. + +and an object is returned with the following properties: + +* `source`: The original source file, or null if this information is not + available. + +* `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. + +* `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. + +* `name`: The original identifier, or null if this information is not available. + +```js +consumer.originalPositionFor({ line: 2, column: 10 }) +// { source: 'foo.coffee', +// line: 2, +// column: 2, +// name: null } + +consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) +// { source: null, +// line: null, +// column: null, +// name: null } +``` + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: The column number in the original source. The column + number is 0-based. + +and an object is returned with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) +// { line: 1, +// column: 56 } +``` + +#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) + +Returns all generated line and column information for the original source, line, +and column provided. If no column is provided, returns all mappings +corresponding to a either the line we are searching for or the next closest line +that has any mappings. Otherwise, returns all mappings corresponding to the +given line and either the column we are searching for or the next closest column +that has any offsets. + +The only argument is an object with the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: Optional. The column number in the original source. The + column number is 0-based. + +and an array of objects is returned, each with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] +``` + +#### SourceMapConsumer.prototype.hasContentsOfAllSources() + +Return true if we have the embedded source content for every source listed in +the source map, false otherwise. + +In other words, if this method returns `true`, then +`consumer.sourceContentFor(s)` will succeed for every source `s` in +`consumer.sources`. + +```js +// ... +if (consumer.hasContentsOfAllSources()) { + consumerReadyCallback(consumer); +} else { + fetchSources(consumer, consumerReadyCallback); +} +// ... +``` + +#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +If the source content for the given source is not found, then an error is +thrown. Optionally, pass `true` as the second param to have `null` returned +instead. + +```js +consumer.sources +// [ "my-cool-lib.clj" ] + +consumer.sourceContentFor("my-cool-lib.clj") +// "..." + +consumer.sourceContentFor("this is not in the source map"); +// Error: "this is not in the source map" is not in the source map + +consumer.sourceContentFor("this is not in the source map", true); +// null +``` + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +* `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, + name }` + +* `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +```js +consumer.eachMapping(function (m) { console.log(m); }) +// ... +// { source: 'illmatic.js', +// generatedLine: 1, +// generatedColumn: 0, +// originalLine: 1, +// originalColumn: 0, +// name: null } +// { source: 'illmatic.js', +// generatedLine: 2, +// generatedColumn: 0, +// originalLine: 2, +// originalColumn: 0, +// name: null } +// ... +``` +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +* `file`: The filename of the generated source that this source map is + associated with. + +* `sourceRoot`: A root for all relative URLs in this source map. + +* `skipValidation`: Optional. When `true`, disables validation of mappings as + they are added. This can improve performance but should be used with + discretion, as a last resort. Even then, one should avoid using this flag when + running tests, if possible. + +```js +var generator = new sourceMap.SourceMapGenerator({ + file: "my-generated-javascript-file.js", + sourceRoot: "http://example.com/app/js/" +}); +``` + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer) + +Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. + +* `sourceMapConsumer` The SourceMap. + +```js +var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); +``` + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +* `generated`: An object with the generated line and column positions. + +* `original`: An object with the original line and column positions. + +* `source`: The original source file (relative to the sourceRoot). + +* `name`: An optional original token name for this mapping. + +```js +generator.addMapping({ + source: "module-one.scm", + original: { line: 128, column: 0 }, + generated: { line: 3, column: 456 } +}) +``` + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +* `sourceFile` the URL of the original source file. + +* `sourceContent` the content of the source file. + +```js +generator.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimum of this map and the supplied map. + +* `sourceMapConsumer`: The SourceMap to be applied. + +* `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +* `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +```js +generator.toString() +// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' +``` + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +* `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. + +* `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number + is 0-based. + +* `source`: The original source's filename; null if no filename is provided. + +* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +* `name`: Optional. The original identifier. + +```js +var node = new SourceNode(1, 2, "a.cpp", [ + new SourceNode(3, 4, "b.cpp", "extern int status;\n"), + new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), + new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), +]); +``` + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +* `code`: The generated code + +* `sourceMapConsumer` The SourceMap for the generated code + +* `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +```js +const consumer = await new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); +const node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), consumer); +``` + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.add(" + "); +node.add(otherNode); +node.add([leftHandOperandNode, " + ", rightHandOperandNode]); +``` + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.prepend("/** Build Id: f783haef86324gf **/\n\n"); +``` + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +* `sourceFile`: The filename of the source file + +* `sourceContent`: The content of the source file + +```js +node.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +* `fn`: The traversal function. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.walk(function (code, loc) { console.log("WALK:", code, loc); }) +// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } +// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } +// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } +// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } +``` + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +* `fn`: The traversal function. + +```js +var a = new SourceNode(1, 2, "a.js", "generated from a"); +a.setSourceContent("a.js", "original a"); +var b = new SourceNode(1, 2, "b.js", "generated from b"); +b.setSourceContent("b.js", "original b"); +var c = new SourceNode(1, 2, "c.js", "generated from c"); +c.setSourceContent("c.js", "original c"); + +var node = new SourceNode(null, null, null, [a, b, c]); +node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) +// WALK: a.js : original a +// WALK: b.js : original b +// WALK: c.js : original c +``` + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +* `sep`: The separator. + +```js +var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); +var operand = new SourceNode(3, 4, "a.rs", "="); +var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); + +var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); +var joinedNode = node.join(" "); +``` + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming white space from the end of a source node, etc. + +* `pattern`: The pattern to replace. + +* `replacement`: The thing to replace the pattern with. + +```js +// Trim trailing white space. +node.replaceRight(/\s*$/, ""); +``` + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toString() +// 'unodostresquatro' +``` + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toStringWithSourceMap({ file: "my-output-file.js" }) +// { code: 'unodostresquatro', +// map: [object SourceMapGenerator] } +``` diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/dist/source-map.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/dist/source-map.js new file mode 100644 index 0000000..a947957 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/dist/source-map.js @@ -0,0 +1,3351 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(require("fs"), require("path")); + else if(typeof define === 'function' && define.amd) + define(["fs", "path"], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(require("fs"), require("path")); + else + root["sourceMap"] = factory(root["fs"], root["path"]); +})(typeof self !== 'undefined' ? self : this, function(__WEBPACK_EXTERNAL_MODULE_10__, __WEBPACK_EXTERNAL_MODULE_11__) { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 5); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } + throw new Error('"' + aName + '" is a required argument.'); + +} +exports.getArg = getArg; + +const urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +const dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + const match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + let url = ""; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ":"; + } + url += "//"; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + "@"; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port; + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +const MAX_CACHED_INPUTS = 32; + +/** + * Takes some function `f(input) -> result` and returns a memoized version of + * `f`. + * + * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The + * memoization is a dumb-simple, linear least-recently-used cache. + */ +function lruMemoize(f) { + const cache = []; + + return function(input) { + for (let i = 0; i < cache.length; i++) { + if (cache[i].input === input) { + const temp = cache[0]; + cache[0] = cache[i]; + cache[i] = temp; + return cache[0].result; + } + } + + const result = f(input); + + cache.unshift({ + input, + result, + }); + + if (cache.length > MAX_CACHED_INPUTS) { + cache.pop(); + } + + return result; + }; +} + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +const normalize = lruMemoize(function normalize(aPath) { + let path = aPath; + const url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + const isAbsolute = exports.isAbsolute(path); + + // Split the path into parts between `/` characters. This is much faster than + // using `.split(/\/+/g)`. + const parts = []; + let start = 0; + let i = 0; + while (true) { + start = i; + i = path.indexOf("/", start); + if (i === -1) { + parts.push(path.slice(start)); + break; + } else { + parts.push(path.slice(start, i)); + while (i < path.length && path[i] === "/") { + i++; + } + } + } + + let up = 0; + for (i = parts.length - 1; i >= 0; i--) { + const part = parts[i]; + if (part === ".") { + parts.splice(i, 1); + } else if (part === "..") { + up++; + } else if (up > 0) { + if (part === "") { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join("/"); + + if (path === "") { + path = isAbsolute ? "/" : "."; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +}); +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + const aPathUrl = urlParse(aPath); + const aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || "/"; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + const joined = aPath.charAt(0) === "/" + ? aPath + : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function(aPath) { + return aPath.charAt(0) === "/" || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ""); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + let level = 0; + while (aPath.indexOf(aRoot + "/") !== 0) { + const index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +const supportsNullProto = (function() { + const obj = Object.create(null); + return !("__proto__" in obj); +}()); + +function identity(s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return "$" + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + const length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + /* eslint-disable no-multi-spaces */ + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + /* eslint-enable no-multi-spaces */ + + for (let i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + let cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + let cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + let cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, "")); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ""; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") { + sourceRoot += "/"; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + const parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + const index = parsed.path.lastIndexOf("/"); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +const base64VLQ = __webpack_require__(2); +const util = __webpack_require__(0); +const ArraySet = __webpack_require__(3).ArraySet; +const MappingList = __webpack_require__(7).MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +class SourceMapGenerator { + constructor(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, "file", null); + this._sourceRoot = util.getArg(aArgs, "sourceRoot", null); + this._skipValidation = util.getArg(aArgs, "skipValidation", false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + static fromSourceMap(aSourceMapConsumer) { + const sourceRoot = aSourceMapConsumer.sourceRoot; + const generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot + }); + aSourceMapConsumer.eachMapping(function(mapping) { + const newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function(sourceFile) { + let sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + const content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + } + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + addMapping(aArgs) { + const generated = util.getArg(aArgs, "generated"); + const original = util.getArg(aArgs, "original", null); + let source = util.getArg(aArgs, "source", null); + let name = util.getArg(aArgs, "name", null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source, + name + }); + } + + /** + * Set the source content for a source file. + */ + setSourceContent(aSourceFile, aSourceContent) { + let source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + } + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + let sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + "SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, " + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + const sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + const newSources = this._mappings.toArray().length > 0 + ? new ArraySet() + : this._sources; + const newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function(mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + const original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source); + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + const source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + const name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function(srcFile) { + const content = aSourceMapConsumer.sourceContentFor(srcFile); + if (content != null) { + if (aSourceMapPath != null) { + srcFile = util.join(aSourceMapPath, srcFile); + } + if (sourceRoot != null) { + srcFile = util.relative(sourceRoot, srcFile); + } + this.setSourceContent(srcFile, content); + } + }, this); + } + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + _validateMapping(aGenerated, aOriginal, aSource, aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") { + throw new Error( + "original.line and original.column are not numbers -- you probably meant to omit " + + "the original mapping entirely and only map the generated position. If so, pass " + + "null for the original mapping instead of an object with empty or null values." + ); + } + + if (aGenerated && "line" in aGenerated && "column" in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + + } else if (aGenerated && "line" in aGenerated && "column" in aGenerated + && aOriginal && "line" in aOriginal && "column" in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + + } else { + throw new Error("Invalid mapping: " + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + } + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + _serializeMappings() { + let previousGeneratedColumn = 0; + let previousGeneratedLine = 1; + let previousOriginalColumn = 0; + let previousOriginalLine = 0; + let previousName = 0; + let previousSource = 0; + let result = ""; + let next; + let mapping; + let nameIdx; + let sourceIdx; + + const mappings = this._mappings.toArray(); + for (let i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = ""; + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ";"; + previousGeneratedLine++; + } + } else if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ","; + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + } + + _generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function(source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + const key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + } + + /** + * Externalize the source map. + */ + toJSON() { + const map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + } + + /** + * Render the source map being generated to a string. + */ + toString() { + return JSON.stringify(this.toJSON()); + } +} + +SourceMapGenerator.prototype._version = 3; +exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const base64 = __webpack_require__(6); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +const VLQ_BASE_SHIFT = 5; + +// binary: 100000 +const VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +const VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +const VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +// eslint-disable-next-line no-unused-vars +function fromVLQSigned(aValue) { + const isNegative = (aValue & 1) === 1; + const shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + let encoded = ""; + let digit; + + let vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +class ArraySet { + constructor() { + this._array = []; + this._set = new Map(); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + static fromArray(aArray, aAllowDuplicates) { + const set = new ArraySet(); + for (let i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + } + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + size() { + return this._set.size; + } + + /** + * Add the given string to this set. + * + * @param String aStr + */ + add(aStr, aAllowDuplicates) { + const isDuplicate = this.has(aStr); + const idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + this._set.set(aStr, idx); + } + } + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + has(aStr) { + return this._set.has(aStr); + } + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + indexOf(aStr) { + const idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + throw new Error('"' + aStr + '" is not in the set.'); + } + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error("No element indexed by " + aIdx); + } + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + toArray() { + return this._array.slice(); + } +} +exports.ArraySet = ArraySet; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(__dirname) {if (typeof fetch === "function") { + // Web version of reading a wasm file into an array buffer. + + let mappingsWasmUrl = null; + + module.exports = function readWasm() { + if (typeof mappingsWasmUrl !== "string") { + throw new Error("You must provide the URL of lib/mappings.wasm by calling " + + "SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) " + + "before using SourceMapConsumer"); + } + + return fetch(mappingsWasmUrl) + .then(response => response.arrayBuffer()); + }; + + module.exports.initialize = url => mappingsWasmUrl = url; +} else { + // Node version of reading a wasm file into an array buffer. + const fs = __webpack_require__(10); + const path = __webpack_require__(11); + + module.exports = function readWasm() { + return new Promise((resolve, reject) => { + const wasmPath = path.join(__dirname, "mappings.wasm"); + fs.readFile(wasmPath, null, (error, data) => { + if (error) { + reject(error); + return; + } + + resolve(data.buffer); + }); + }); + }; + + module.exports.initialize = _ => { + console.debug("SourceMapConsumer.initialize is a no-op when running in node.js"); + }; +} + +/* WEBPACK VAR INJECTION */}.call(exports, "/")) + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; +exports.SourceMapConsumer = __webpack_require__(8).SourceMapConsumer; +exports.SourceNode = __webpack_require__(13).SourceNode; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +const intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function(number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +const util = __webpack_require__(0); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + const lineA = mappingA.generatedLine; + const lineB = mappingB.generatedLine; + const columnA = mappingA.generatedColumn; + const columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a negligible overhead in general + * case for a large speedup in case of mappings being added in order. + */ +class MappingList { + constructor() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + unsortedForEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + } + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + } + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + } +} + +exports.MappingList = MappingList; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +const util = __webpack_require__(0); +const binarySearch = __webpack_require__(9); +const ArraySet = __webpack_require__(3).ArraySet; +const base64VLQ = __webpack_require__(2); // eslint-disable-line no-unused-vars +const readWasm = __webpack_require__(4); +const wasm = __webpack_require__(12); + +const INTERNAL = Symbol("smcInternal"); + +class SourceMapConsumer { + constructor(aSourceMap, aSourceMapURL) { + // If the constructor was called by super(), just return Promise. + // Yes, this is a hack to retain the pre-existing API of the base-class + // constructor also being an async factory function. + if (aSourceMap == INTERNAL) { + return Promise.resolve(this); + } + + return _factory(aSourceMap, aSourceMapURL); + } + + static initialize(opts) { + readWasm.initialize(opts["lib/mappings.wasm"]); + } + + static fromSourceMap(aSourceMap, aSourceMapURL) { + return _factoryBSM(aSourceMap, aSourceMapURL); + } + + /** + * Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl` + * (see the `SourceMapConsumer` constructor for details. Then, invoke the `async + * function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait + * for `f` to complete, call `destroy` on the consumer, and return `f`'s return + * value. + * + * You must not use the consumer after `f` completes! + * + * By using `with`, you do not have to remember to manually call `destroy` on + * the consumer, since it will be called automatically once `f` completes. + * + * ```js + * const xSquared = await SourceMapConsumer.with( + * myRawSourceMap, + * null, + * async function (consumer) { + * // Use `consumer` inside here and don't worry about remembering + * // to call `destroy`. + * + * const x = await whatever(consumer); + * return x * x; + * } + * ); + * + * // You may not use that `consumer` anymore out here; it has + * // been destroyed. But you can use `xSquared`. + * console.log(xSquared); + * ``` + */ + static with(rawSourceMap, sourceMapUrl, f) { + // Note: The `acorn` version that `webpack` currently depends on doesn't + // support `async` functions, and the nodes that we support don't all have + // `.finally`. Therefore, this is written a bit more convolutedly than it + // should really be. + + let consumer = null; + const promise = new SourceMapConsumer(rawSourceMap, sourceMapUrl); + return promise + .then(c => { + consumer = c; + return f(c); + }) + .then(x => { + if (consumer) { + consumer.destroy(); + } + return x; + }, e => { + if (consumer) { + consumer.destroy(); + } + throw e; + }); + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + _parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + } + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + eachMapping(aCallback, aContext, aOrder) { + throw new Error("Subclasses must implement eachMapping"); + } + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + allGeneratedPositionsFor(aArgs) { + throw new Error("Subclasses must implement allGeneratedPositionsFor"); + } + + destroy() { + throw new Error("Subclasses must implement destroy"); + } +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +class BasicSourceMapConsumer extends SourceMapConsumer { + constructor(aSourceMap, aSourceMapURL) { + return super(INTERNAL).then(that => { + let sourceMap = aSourceMap; + if (typeof aSourceMap === "string") { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + const version = util.getArg(sourceMap, "version"); + let sources = util.getArg(sourceMap, "sources"); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + const names = util.getArg(sourceMap, "names", []); + let sourceRoot = util.getArg(sourceMap, "sourceRoot", null); + const sourcesContent = util.getArg(sourceMap, "sourcesContent", null); + const mappings = util.getArg(sourceMap, "mappings"); + const file = util.getArg(sourceMap, "file", null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != that._version) { + throw new Error("Unsupported version: " + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function(source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + that._names = ArraySet.fromArray(names.map(String), true); + that._sources = ArraySet.fromArray(sources, true); + + that._absoluteSources = that._sources.toArray().map(function(s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + that.sourceRoot = sourceRoot; + that.sourcesContent = sourcesContent; + that._mappings = mappings; + that._sourceMapURL = aSourceMapURL; + that.file = file; + + that._computedColumnSpans = false; + that._mappingsPtr = 0; + that._wasm = null; + + return wasm().then(w => { + that._wasm = w; + return that; + }); + }); + } + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + _findSourceIndex(aSource) { + let relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + for (let i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + } + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + static fromSourceMap(aSourceMap, aSourceMapURL) { + return new BasicSourceMapConsumer(aSourceMap.toString()); + } + + get sources() { + return this._absoluteSources.slice(); + } + + _getMappingsPtr() { + if (this._mappingsPtr === 0) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this._mappingsPtr; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + _parseMappings(aStr, aSourceRoot) { + const size = aStr.length; + + const mappingsBufPtr = this._wasm.exports.allocate_mappings(size); + const mappingsBuf = new Uint8Array(this._wasm.exports.memory.buffer, mappingsBufPtr, size); + for (let i = 0; i < size; i++) { + mappingsBuf[i] = aStr.charCodeAt(i); + } + + const mappingsPtr = this._wasm.exports.parse_mappings(mappingsBufPtr); + + if (!mappingsPtr) { + const error = this._wasm.exports.get_last_error(); + let msg = `Error parsing mappings (code ${error}): `; + + // XXX: keep these error codes in sync with `fitzgen/source-map-mappings`. + switch (error) { + case 1: + msg += "the mappings contained a negative line, column, source index, or name index"; + break; + case 2: + msg += "the mappings contained a number larger than 2**32"; + break; + case 3: + msg += "reached EOF while in the middle of parsing a VLQ"; + break; + case 4: + msg += "invalid base 64 character while parsing a VLQ"; + break; + default: + msg += "unknown error code"; + break; + } + + throw new Error(msg); + } + + this._mappingsPtr = mappingsPtr; + } + + eachMapping(aCallback, aContext, aOrder) { + const context = aContext || null; + const order = aOrder || SourceMapConsumer.GENERATED_ORDER; + const sourceRoot = this.sourceRoot; + + this._wasm.withMappingCallback( + mapping => { + if (mapping.source !== null) { + mapping.source = this._sources.at(mapping.source); + mapping.source = util.computeSourceURL(sourceRoot, mapping.source, this._sourceMapURL); + + if (mapping.name !== null) { + mapping.name = this._names.at(mapping.name); + } + } + + aCallback.call(context, mapping); + }, + () => { + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + this._wasm.exports.by_generated_location(this._getMappingsPtr()); + break; + case SourceMapConsumer.ORIGINAL_ORDER: + this._wasm.exports.by_original_location(this._getMappingsPtr()); + break; + default: + throw new Error("Unknown order of iteration."); + } + } + ); + } + + allGeneratedPositionsFor(aArgs) { + let source = util.getArg(aArgs, "source"); + const originalLine = util.getArg(aArgs, "line"); + const originalColumn = aArgs.column || 0; + + source = this._findSourceIndex(source); + if (source < 0) { + return []; + } + + if (originalLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (originalColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + const mappings = []; + + this._wasm.withMappingCallback( + m => { + let lastColumn = m.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + mappings.push({ + line: m.generatedLine, + column: m.generatedColumn, + lastColumn, + }); + }, () => { + this._wasm.exports.all_generated_locations_for( + this._getMappingsPtr(), + source, + originalLine - 1, + "column" in aArgs, + originalColumn + ); + } + ); + + return mappings; + } + + destroy() { + if (this._mappingsPtr !== 0) { + this._wasm.exports.free_mappings(this._mappingsPtr); + this._mappingsPtr = 0; + } + } + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + computeColumnSpans() { + if (this._computedColumnSpans) { + return; + } + + this._wasm.exports.compute_column_spans(this._getMappingsPtr()); + this._computedColumnSpans = true; + } + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + originalPositionFor(aArgs) { + const needle = { + generatedLine: util.getArg(aArgs, "line"), + generatedColumn: util.getArg(aArgs, "column") + }; + + if (needle.generatedLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (needle.generatedColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + let bias = util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND); + if (bias == null) { + bias = SourceMapConsumer.GREATEST_LOWER_BOUND; + } + + let mapping; + this._wasm.withMappingCallback(m => mapping = m, () => { + this._wasm.exports.original_location_for( + this._getMappingsPtr(), + needle.generatedLine - 1, + needle.generatedColumn, + bias + ); + }); + + if (mapping) { + if (mapping.generatedLine === needle.generatedLine) { + let source = util.getArg(mapping, "source", null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + + let name = util.getArg(mapping, "name", null); + if (name !== null) { + name = this._names.at(name); + } + + return { + source, + line: util.getArg(mapping, "originalLine", null), + column: util.getArg(mapping, "originalColumn", null), + name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + } + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function(sc) { return sc == null; }); + } + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + const index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + let relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + let url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + const fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + generatedPositionFor(aArgs) { + let source = util.getArg(aArgs, "source"); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + const needle = { + source, + originalLine: util.getArg(aArgs, "line"), + originalColumn: util.getArg(aArgs, "column") + }; + + if (needle.originalLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (needle.originalColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + let bias = util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND); + if (bias == null) { + bias = SourceMapConsumer.GREATEST_LOWER_BOUND; + } + + let mapping; + this._wasm.withMappingCallback(m => mapping = m, () => { + this._wasm.exports.generated_location_for( + this._getMappingsPtr(), + needle.source, + needle.originalLine - 1, + needle.originalColumn, + bias + ); + }); + + if (mapping) { + if (mapping.source === needle.source) { + let lastColumn = mapping.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + return { + line: util.getArg(mapping, "generatedLine", null), + column: util.getArg(mapping, "generatedColumn", null), + lastColumn, + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + } +} + +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +class IndexedSourceMapConsumer extends SourceMapConsumer { + constructor(aSourceMap, aSourceMapURL) { + return super(INTERNAL).then(that => { + let sourceMap = aSourceMap; + if (typeof aSourceMap === "string") { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + const version = util.getArg(sourceMap, "version"); + const sections = util.getArg(sourceMap, "sections"); + + if (version != that._version) { + throw new Error("Unsupported version: " + version); + } + + that._sources = new ArraySet(); + that._names = new ArraySet(); + that.__generatedMappings = null; + that.__originalMappings = null; + that.__generatedMappingsUnsorted = null; + that.__originalMappingsUnsorted = null; + + let lastOffset = { + line: -1, + column: 0 + }; + return Promise.all(sections.map(s => { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error("Support for url field in sections not implemented."); + } + const offset = util.getArg(s, "offset"); + const offsetLine = util.getArg(offset, "line"); + const offsetColumn = util.getArg(offset, "column"); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error("Section offsets must be ordered and non-overlapping."); + } + lastOffset = offset; + + const cons = new SourceMapConsumer(util.getArg(s, "map"), aSourceMapURL); + return cons.then(consumer => { + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer + }; + }); + })).then(s => { + that._sections = s; + return that; + }); + }); + } + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + get _generatedMappings() { + if (!this.__generatedMappings) { + this._sortGeneratedMappings(); + } + + return this.__generatedMappings; + } + + get _originalMappings() { + if (!this.__originalMappings) { + this._sortOriginalMappings(); + } + + return this.__originalMappings; + } + + get _generatedMappingsUnsorted() { + if (!this.__generatedMappingsUnsorted) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappingsUnsorted; + } + + get _originalMappingsUnsorted() { + if (!this.__originalMappingsUnsorted) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappingsUnsorted; + } + + _sortGeneratedMappings() { + const mappings = this._generatedMappingsUnsorted; + mappings.sort(util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = mappings; + } + + _sortOriginalMappings() { + const mappings = this._originalMappingsUnsorted; + mappings.sort(util.compareByOriginalPositions); + this.__originalMappings = mappings; + } + + /** + * The list of original sources. + */ + get sources() { + const sources = []; + for (let i = 0; i < this._sections.length; i++) { + for (let j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + originalPositionFor(aArgs) { + const needle = { + generatedLine: util.getArg(aArgs, "line"), + generatedColumn: util.getArg(aArgs, "column") + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + const sectionIndex = binarySearch.search(needle, this._sections, + function(aNeedle, section) { + const cmp = aNeedle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (aNeedle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + const section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + } + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + hasContentsOfAllSources() { + return this._sections.every(function(s) { + return s.consumer.hasContentsOfAllSources(); + }); + } + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + sourceContentFor(aSource, nullOnMissing) { + for (let i = 0; i < this._sections.length; i++) { + const section = this._sections[i]; + + const content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + generatedPositionFor(aArgs) { + for (let i = 0; i < this._sections.length; i++) { + const section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, "source")) === -1) { + continue; + } + const generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + const ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + _parseMappings(aStr, aSourceRoot) { + const generatedMappings = this.__generatedMappingsUnsorted = []; + const originalMappings = this.__originalMappingsUnsorted = []; + for (let i = 0; i < this._sections.length; i++) { + const section = this._sections[i]; + + const sectionMappings = []; + section.consumer.eachMapping(m => sectionMappings.push(m)); + + for (let j = 0; j < sectionMappings.length; j++) { + const mapping = sectionMappings[j]; + + // TODO: test if null is correct here. The original code used + // `source`, which would actually have gotten used as null because + // var's get hoisted. + // See: https://github.com/mozilla/source-map/issues/333 + let source = util.computeSourceURL(section.consumer.sourceRoot, null, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + let name = null; + if (mapping.name) { + this._names.add(mapping.name); + name = this._names.indexOf(mapping.name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + const adjustedMapping = { + source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name + }; + + generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === "number") { + originalMappings.push(adjustedMapping); + } + } + } + } + + eachMapping(aCallback, aContext, aOrder) { + const context = aContext || null; + const order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + let mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + const sourceRoot = this.sourceRoot; + mappings.map(function(mapping) { + let source = null; + if (mapping.source !== null) { + source = this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + } + return { + source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + } + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + _findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError("Line must be greater than or equal to 1, got " + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError("Column must be greater than or equal to 0, got " + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + } + + allGeneratedPositionsFor(aArgs) { + const line = util.getArg(aArgs, "line"); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + const needle = { + source: util.getArg(aArgs, "source"), + originalLine: line, + originalColumn: util.getArg(aArgs, "column", 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + if (needle.originalLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (needle.originalColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + const mappings = []; + + let index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + let mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + const originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + let lastColumn = mapping.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + mappings.push({ + line: util.getArg(mapping, "generatedLine", null), + column: util.getArg(mapping, "generatedColumn", null), + lastColumn, + }); + + mapping = this._originalMappings[++index]; + } + } else { + const originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + let lastColumn = mapping.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + mappings.push({ + line: util.getArg(mapping, "generatedLine", null), + column: util.getArg(mapping, "generatedColumn", null), + lastColumn, + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + } + + destroy() { + for (let i = 0; i < this._sections.length; i++) { + this._sections[i].consumer.destroy(); + } + } +} +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + +/* + * Cheat to get around inter-twingled classes. `factory()` can be at the end + * where it has access to non-hoisted classes, but it gets hoisted itself. + */ +function _factory(aSourceMap, aSourceMapURL) { + let sourceMap = aSourceMap; + if (typeof aSourceMap === "string") { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + const consumer = sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + return Promise.resolve(consumer); +} + +function _factoryBSM(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + const mid = Math.floor((aHigh - aLow) / 2) + aLow; + const cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } + return mid; + } + + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } + return aLow < 0 ? -1 : aLow; +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + let index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports) { + +module.exports = __WEBPACK_EXTERNAL_MODULE_10__; + +/***/ }), +/* 11 */ +/***/ (function(module, exports) { + +module.exports = __WEBPACK_EXTERNAL_MODULE_11__; + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +const readWasm = __webpack_require__(4); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.lastGeneratedColumn = null; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +let cachedWasm = null; + +module.exports = function wasm() { + if (cachedWasm) { + return cachedWasm; + } + + const callbackStack = []; + + cachedWasm = readWasm().then(buffer => { + return WebAssembly.instantiate(buffer, { + env: { + mapping_callback( + generatedLine, + generatedColumn, + + hasLastGeneratedColumn, + lastGeneratedColumn, + + hasOriginal, + source, + originalLine, + originalColumn, + + hasName, + name + ) { + const mapping = new Mapping(); + // JS uses 1-based line numbers, wasm uses 0-based. + mapping.generatedLine = generatedLine + 1; + mapping.generatedColumn = generatedColumn; + + if (hasLastGeneratedColumn) { + // JS uses inclusive last generated column, wasm uses exclusive. + mapping.lastGeneratedColumn = lastGeneratedColumn - 1; + } + + if (hasOriginal) { + mapping.source = source; + // JS uses 1-based line numbers, wasm uses 0-based. + mapping.originalLine = originalLine + 1; + mapping.originalColumn = originalColumn; + + if (hasName) { + mapping.name = name; + } + } + + callbackStack[callbackStack.length - 1](mapping); + }, + + start_all_generated_locations_for() { console.time("all_generated_locations_for"); }, + end_all_generated_locations_for() { console.timeEnd("all_generated_locations_for"); }, + + start_compute_column_spans() { console.time("compute_column_spans"); }, + end_compute_column_spans() { console.timeEnd("compute_column_spans"); }, + + start_generated_location_for() { console.time("generated_location_for"); }, + end_generated_location_for() { console.timeEnd("generated_location_for"); }, + + start_original_location_for() { console.time("original_location_for"); }, + end_original_location_for() { console.timeEnd("original_location_for"); }, + + start_parse_mappings() { console.time("parse_mappings"); }, + end_parse_mappings() { console.timeEnd("parse_mappings"); }, + + start_sort_by_generated_location() { console.time("sort_by_generated_location"); }, + end_sort_by_generated_location() { console.timeEnd("sort_by_generated_location"); }, + + start_sort_by_original_location() { console.time("sort_by_original_location"); }, + end_sort_by_original_location() { console.timeEnd("sort_by_original_location"); }, + } + }); + }).then(Wasm => { + return { + exports: Wasm.instance.exports, + withMappingCallback: (mappingCallback, f) => { + callbackStack.push(mappingCallback); + try { + f(); + } finally { + callbackStack.pop(); + } + } + }; + }).then(null, e => { + cachedWasm = null; + throw e; + }); + + return cachedWasm; +}; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +const SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; +const util = __webpack_require__(0); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +const REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +const NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +const isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +class SourceNode { + constructor(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + static fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + const node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + const remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + let remainingLinesIndex = 0; + const shiftNextLine = function() { + const lineContents = getNextLine(); + // The last line of a file might not have a newline. + const newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + let lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + let lastMapping = null; + let nextLine; + + aSourceMapConsumer.eachMapping(function(mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + nextLine = remainingLines[remainingLinesIndex] || ""; + const code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + nextLine = remainingLines[remainingLinesIndex] || ""; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function(sourceFile) { + const content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + const source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + } + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function(chunk) { + this.add(chunk); + }, this); + } else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + } + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (let i = aChunk.length - 1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + } + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + walk(aFn) { + let chunk; + for (let i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } else if (chunk !== "") { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + join(aSep) { + let newChildren; + let i; + const len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len - 1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + } + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + replaceRight(aPattern, aReplacement) { + const lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } else if (typeof lastChild === "string") { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } else { + this.children.push("".replace(aPattern, aReplacement)); + } + return this; + } + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + } + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + walkSourceContents(aFn) { + for (let i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + const sources = Object.keys(this.sourceContents); + for (let i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + } + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + toString() { + let str = ""; + this.walk(function(chunk) { + str += chunk; + }); + return str; + } + + /** + * Returns the string representation of this source node along with a source + * map. + */ + toStringWithSourceMap(aArgs) { + const generated = { + code: "", + line: 1, + column: 0 + }; + const map = new SourceMapGenerator(aArgs); + let sourceMappingActive = false; + let lastOriginalSource = null; + let lastOriginalLine = null; + let lastOriginalColumn = null; + let lastOriginalName = null; + this.walk(function(chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if (lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (let idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function(sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map }; + } +} + +exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]); +}); \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/array-set.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/array-set.js new file mode 100644 index 0000000..40171b9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/array-set.js @@ -0,0 +1,100 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +class ArraySet { + constructor() { + this._array = []; + this._set = new Map(); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + static fromArray(aArray, aAllowDuplicates) { + const set = new ArraySet(); + for (let i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + } + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + size() { + return this._set.size; + } + + /** + * Add the given string to this set. + * + * @param String aStr + */ + add(aStr, aAllowDuplicates) { + const isDuplicate = this.has(aStr); + const idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + this._set.set(aStr, idx); + } + } + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + has(aStr) { + return this._set.has(aStr); + } + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + indexOf(aStr) { + const idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + throw new Error('"' + aStr + '" is not in the set.'); + } + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error("No element indexed by " + aIdx); + } + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + toArray() { + return this._array.slice(); + } +} +exports.ArraySet = ArraySet; diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/base64-vlq.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/base64-vlq.js new file mode 100644 index 0000000..fc1049c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/base64-vlq.js @@ -0,0 +1,111 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const base64 = require("./base64"); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +const VLQ_BASE_SHIFT = 5; + +// binary: 100000 +const VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +const VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +const VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +// eslint-disable-next-line no-unused-vars +function fromVLQSigned(aValue) { + const isNegative = (aValue & 1) === 1; + const shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + let encoded = ""; + let digit; + + let vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/base64.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/base64.js new file mode 100644 index 0000000..b9ca319 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/base64.js @@ -0,0 +1,18 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +const intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function(number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/binary-search.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/binary-search.js new file mode 100644 index 0000000..d6f898e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/binary-search.js @@ -0,0 +1,107 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + const mid = Math.floor((aHigh - aLow) / 2) + aLow; + const cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } + return mid; + } + + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } + return aLow < 0 ? -1 : aLow; +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + let index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/mapping-list.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/mapping-list.js new file mode 100644 index 0000000..7056861 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/mapping-list.js @@ -0,0 +1,80 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +const util = require("./util"); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + const lineA = mappingA.generatedLine; + const lineB = mappingB.generatedLine; + const columnA = mappingA.generatedColumn; + const columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a negligible overhead in general + * case for a large speedup in case of mappings being added in order. + */ +class MappingList { + constructor() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + unsortedForEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + } + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + } + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + } +} + +exports.MappingList = MappingList; diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/mappings.wasm b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/mappings.wasm new file mode 100644 index 0000000..3515370 Binary files /dev/null and b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/mappings.wasm differ diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/read-wasm.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/read-wasm.js new file mode 100644 index 0000000..9bb6492 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/read-wasm.js @@ -0,0 +1,40 @@ +if (typeof fetch === "function") { + // Web version of reading a wasm file into an array buffer. + + let mappingsWasmUrl = null; + + module.exports = function readWasm() { + if (typeof mappingsWasmUrl !== "string") { + throw new Error("You must provide the URL of lib/mappings.wasm by calling " + + "SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) " + + "before using SourceMapConsumer"); + } + + return fetch(mappingsWasmUrl) + .then(response => response.arrayBuffer()); + }; + + module.exports.initialize = url => mappingsWasmUrl = url; +} else { + // Node version of reading a wasm file into an array buffer. + const fs = require("fs"); + const path = require("path"); + + module.exports = function readWasm() { + return new Promise((resolve, reject) => { + const wasmPath = path.join(__dirname, "mappings.wasm"); + fs.readFile(wasmPath, null, (error, data) => { + if (error) { + reject(error); + return; + } + + resolve(data.buffer); + }); + }); + }; + + module.exports.initialize = _ => { + console.debug("SourceMapConsumer.initialize is a no-op when running in node.js"); + }; +} diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/source-map-consumer.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/source-map-consumer.js new file mode 100644 index 0000000..43ea1a0 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/source-map-consumer.js @@ -0,0 +1,1254 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +const util = require("./util"); +const binarySearch = require("./binary-search"); +const ArraySet = require("./array-set").ArraySet; +const base64VLQ = require("./base64-vlq"); // eslint-disable-line no-unused-vars +const readWasm = require("../lib/read-wasm"); +const wasm = require("./wasm"); + +const INTERNAL = Symbol("smcInternal"); + +class SourceMapConsumer { + constructor(aSourceMap, aSourceMapURL) { + // If the constructor was called by super(), just return Promise. + // Yes, this is a hack to retain the pre-existing API of the base-class + // constructor also being an async factory function. + if (aSourceMap == INTERNAL) { + return Promise.resolve(this); + } + + return _factory(aSourceMap, aSourceMapURL); + } + + static initialize(opts) { + readWasm.initialize(opts["lib/mappings.wasm"]); + } + + static fromSourceMap(aSourceMap, aSourceMapURL) { + return _factoryBSM(aSourceMap, aSourceMapURL); + } + + /** + * Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl` + * (see the `SourceMapConsumer` constructor for details. Then, invoke the `async + * function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait + * for `f` to complete, call `destroy` on the consumer, and return `f`'s return + * value. + * + * You must not use the consumer after `f` completes! + * + * By using `with`, you do not have to remember to manually call `destroy` on + * the consumer, since it will be called automatically once `f` completes. + * + * ```js + * const xSquared = await SourceMapConsumer.with( + * myRawSourceMap, + * null, + * async function (consumer) { + * // Use `consumer` inside here and don't worry about remembering + * // to call `destroy`. + * + * const x = await whatever(consumer); + * return x * x; + * } + * ); + * + * // You may not use that `consumer` anymore out here; it has + * // been destroyed. But you can use `xSquared`. + * console.log(xSquared); + * ``` + */ + static with(rawSourceMap, sourceMapUrl, f) { + // Note: The `acorn` version that `webpack` currently depends on doesn't + // support `async` functions, and the nodes that we support don't all have + // `.finally`. Therefore, this is written a bit more convolutedly than it + // should really be. + + let consumer = null; + const promise = new SourceMapConsumer(rawSourceMap, sourceMapUrl); + return promise + .then(c => { + consumer = c; + return f(c); + }) + .then(x => { + if (consumer) { + consumer.destroy(); + } + return x; + }, e => { + if (consumer) { + consumer.destroy(); + } + throw e; + }); + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + _parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + } + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + eachMapping(aCallback, aContext, aOrder) { + throw new Error("Subclasses must implement eachMapping"); + } + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + allGeneratedPositionsFor(aArgs) { + throw new Error("Subclasses must implement allGeneratedPositionsFor"); + } + + destroy() { + throw new Error("Subclasses must implement destroy"); + } +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +class BasicSourceMapConsumer extends SourceMapConsumer { + constructor(aSourceMap, aSourceMapURL) { + return super(INTERNAL).then(that => { + let sourceMap = aSourceMap; + if (typeof aSourceMap === "string") { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + const version = util.getArg(sourceMap, "version"); + let sources = util.getArg(sourceMap, "sources"); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + const names = util.getArg(sourceMap, "names", []); + let sourceRoot = util.getArg(sourceMap, "sourceRoot", null); + const sourcesContent = util.getArg(sourceMap, "sourcesContent", null); + const mappings = util.getArg(sourceMap, "mappings"); + const file = util.getArg(sourceMap, "file", null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != that._version) { + throw new Error("Unsupported version: " + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function(source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + that._names = ArraySet.fromArray(names.map(String), true); + that._sources = ArraySet.fromArray(sources, true); + + that._absoluteSources = that._sources.toArray().map(function(s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + that.sourceRoot = sourceRoot; + that.sourcesContent = sourcesContent; + that._mappings = mappings; + that._sourceMapURL = aSourceMapURL; + that.file = file; + + that._computedColumnSpans = false; + that._mappingsPtr = 0; + that._wasm = null; + + return wasm().then(w => { + that._wasm = w; + return that; + }); + }); + } + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + _findSourceIndex(aSource) { + let relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + for (let i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + } + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + static fromSourceMap(aSourceMap, aSourceMapURL) { + return new BasicSourceMapConsumer(aSourceMap.toString()); + } + + get sources() { + return this._absoluteSources.slice(); + } + + _getMappingsPtr() { + if (this._mappingsPtr === 0) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this._mappingsPtr; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + _parseMappings(aStr, aSourceRoot) { + const size = aStr.length; + + const mappingsBufPtr = this._wasm.exports.allocate_mappings(size); + const mappingsBuf = new Uint8Array(this._wasm.exports.memory.buffer, mappingsBufPtr, size); + for (let i = 0; i < size; i++) { + mappingsBuf[i] = aStr.charCodeAt(i); + } + + const mappingsPtr = this._wasm.exports.parse_mappings(mappingsBufPtr); + + if (!mappingsPtr) { + const error = this._wasm.exports.get_last_error(); + let msg = `Error parsing mappings (code ${error}): `; + + // XXX: keep these error codes in sync with `fitzgen/source-map-mappings`. + switch (error) { + case 1: + msg += "the mappings contained a negative line, column, source index, or name index"; + break; + case 2: + msg += "the mappings contained a number larger than 2**32"; + break; + case 3: + msg += "reached EOF while in the middle of parsing a VLQ"; + break; + case 4: + msg += "invalid base 64 character while parsing a VLQ"; + break; + default: + msg += "unknown error code"; + break; + } + + throw new Error(msg); + } + + this._mappingsPtr = mappingsPtr; + } + + eachMapping(aCallback, aContext, aOrder) { + const context = aContext || null; + const order = aOrder || SourceMapConsumer.GENERATED_ORDER; + const sourceRoot = this.sourceRoot; + + this._wasm.withMappingCallback( + mapping => { + if (mapping.source !== null) { + mapping.source = this._sources.at(mapping.source); + mapping.source = util.computeSourceURL(sourceRoot, mapping.source, this._sourceMapURL); + + if (mapping.name !== null) { + mapping.name = this._names.at(mapping.name); + } + } + + aCallback.call(context, mapping); + }, + () => { + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + this._wasm.exports.by_generated_location(this._getMappingsPtr()); + break; + case SourceMapConsumer.ORIGINAL_ORDER: + this._wasm.exports.by_original_location(this._getMappingsPtr()); + break; + default: + throw new Error("Unknown order of iteration."); + } + } + ); + } + + allGeneratedPositionsFor(aArgs) { + let source = util.getArg(aArgs, "source"); + const originalLine = util.getArg(aArgs, "line"); + const originalColumn = aArgs.column || 0; + + source = this._findSourceIndex(source); + if (source < 0) { + return []; + } + + if (originalLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (originalColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + const mappings = []; + + this._wasm.withMappingCallback( + m => { + let lastColumn = m.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + mappings.push({ + line: m.generatedLine, + column: m.generatedColumn, + lastColumn, + }); + }, () => { + this._wasm.exports.all_generated_locations_for( + this._getMappingsPtr(), + source, + originalLine - 1, + "column" in aArgs, + originalColumn + ); + } + ); + + return mappings; + } + + destroy() { + if (this._mappingsPtr !== 0) { + this._wasm.exports.free_mappings(this._mappingsPtr); + this._mappingsPtr = 0; + } + } + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + computeColumnSpans() { + if (this._computedColumnSpans) { + return; + } + + this._wasm.exports.compute_column_spans(this._getMappingsPtr()); + this._computedColumnSpans = true; + } + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + originalPositionFor(aArgs) { + const needle = { + generatedLine: util.getArg(aArgs, "line"), + generatedColumn: util.getArg(aArgs, "column") + }; + + if (needle.generatedLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (needle.generatedColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + let bias = util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND); + if (bias == null) { + bias = SourceMapConsumer.GREATEST_LOWER_BOUND; + } + + let mapping; + this._wasm.withMappingCallback(m => mapping = m, () => { + this._wasm.exports.original_location_for( + this._getMappingsPtr(), + needle.generatedLine - 1, + needle.generatedColumn, + bias + ); + }); + + if (mapping) { + if (mapping.generatedLine === needle.generatedLine) { + let source = util.getArg(mapping, "source", null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + + let name = util.getArg(mapping, "name", null); + if (name !== null) { + name = this._names.at(name); + } + + return { + source, + line: util.getArg(mapping, "originalLine", null), + column: util.getArg(mapping, "originalColumn", null), + name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + } + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function(sc) { return sc == null; }); + } + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + const index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + let relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + let url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + const fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + generatedPositionFor(aArgs) { + let source = util.getArg(aArgs, "source"); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + const needle = { + source, + originalLine: util.getArg(aArgs, "line"), + originalColumn: util.getArg(aArgs, "column") + }; + + if (needle.originalLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (needle.originalColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + let bias = util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND); + if (bias == null) { + bias = SourceMapConsumer.GREATEST_LOWER_BOUND; + } + + let mapping; + this._wasm.withMappingCallback(m => mapping = m, () => { + this._wasm.exports.generated_location_for( + this._getMappingsPtr(), + needle.source, + needle.originalLine - 1, + needle.originalColumn, + bias + ); + }); + + if (mapping) { + if (mapping.source === needle.source) { + let lastColumn = mapping.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + return { + line: util.getArg(mapping, "generatedLine", null), + column: util.getArg(mapping, "generatedColumn", null), + lastColumn, + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + } +} + +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +class IndexedSourceMapConsumer extends SourceMapConsumer { + constructor(aSourceMap, aSourceMapURL) { + return super(INTERNAL).then(that => { + let sourceMap = aSourceMap; + if (typeof aSourceMap === "string") { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + const version = util.getArg(sourceMap, "version"); + const sections = util.getArg(sourceMap, "sections"); + + if (version != that._version) { + throw new Error("Unsupported version: " + version); + } + + that._sources = new ArraySet(); + that._names = new ArraySet(); + that.__generatedMappings = null; + that.__originalMappings = null; + that.__generatedMappingsUnsorted = null; + that.__originalMappingsUnsorted = null; + + let lastOffset = { + line: -1, + column: 0 + }; + return Promise.all(sections.map(s => { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error("Support for url field in sections not implemented."); + } + const offset = util.getArg(s, "offset"); + const offsetLine = util.getArg(offset, "line"); + const offsetColumn = util.getArg(offset, "column"); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error("Section offsets must be ordered and non-overlapping."); + } + lastOffset = offset; + + const cons = new SourceMapConsumer(util.getArg(s, "map"), aSourceMapURL); + return cons.then(consumer => { + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer + }; + }); + })).then(s => { + that._sections = s; + return that; + }); + }); + } + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + get _generatedMappings() { + if (!this.__generatedMappings) { + this._sortGeneratedMappings(); + } + + return this.__generatedMappings; + } + + get _originalMappings() { + if (!this.__originalMappings) { + this._sortOriginalMappings(); + } + + return this.__originalMappings; + } + + get _generatedMappingsUnsorted() { + if (!this.__generatedMappingsUnsorted) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappingsUnsorted; + } + + get _originalMappingsUnsorted() { + if (!this.__originalMappingsUnsorted) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappingsUnsorted; + } + + _sortGeneratedMappings() { + const mappings = this._generatedMappingsUnsorted; + mappings.sort(util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = mappings; + } + + _sortOriginalMappings() { + const mappings = this._originalMappingsUnsorted; + mappings.sort(util.compareByOriginalPositions); + this.__originalMappings = mappings; + } + + /** + * The list of original sources. + */ + get sources() { + const sources = []; + for (let i = 0; i < this._sections.length; i++) { + for (let j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + originalPositionFor(aArgs) { + const needle = { + generatedLine: util.getArg(aArgs, "line"), + generatedColumn: util.getArg(aArgs, "column") + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + const sectionIndex = binarySearch.search(needle, this._sections, + function(aNeedle, section) { + const cmp = aNeedle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (aNeedle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + const section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + } + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + hasContentsOfAllSources() { + return this._sections.every(function(s) { + return s.consumer.hasContentsOfAllSources(); + }); + } + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + sourceContentFor(aSource, nullOnMissing) { + for (let i = 0; i < this._sections.length; i++) { + const section = this._sections[i]; + + const content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + generatedPositionFor(aArgs) { + for (let i = 0; i < this._sections.length; i++) { + const section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, "source")) === -1) { + continue; + } + const generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + const ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + _parseMappings(aStr, aSourceRoot) { + const generatedMappings = this.__generatedMappingsUnsorted = []; + const originalMappings = this.__originalMappingsUnsorted = []; + for (let i = 0; i < this._sections.length; i++) { + const section = this._sections[i]; + + const sectionMappings = []; + section.consumer.eachMapping(m => sectionMappings.push(m)); + + for (let j = 0; j < sectionMappings.length; j++) { + const mapping = sectionMappings[j]; + + // TODO: test if null is correct here. The original code used + // `source`, which would actually have gotten used as null because + // var's get hoisted. + // See: https://github.com/mozilla/source-map/issues/333 + let source = util.computeSourceURL(section.consumer.sourceRoot, null, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + let name = null; + if (mapping.name) { + this._names.add(mapping.name); + name = this._names.indexOf(mapping.name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + const adjustedMapping = { + source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name + }; + + generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === "number") { + originalMappings.push(adjustedMapping); + } + } + } + } + + eachMapping(aCallback, aContext, aOrder) { + const context = aContext || null; + const order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + let mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + const sourceRoot = this.sourceRoot; + mappings.map(function(mapping) { + let source = null; + if (mapping.source !== null) { + source = this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + } + return { + source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + } + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + _findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError("Line must be greater than or equal to 1, got " + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError("Column must be greater than or equal to 0, got " + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + } + + allGeneratedPositionsFor(aArgs) { + const line = util.getArg(aArgs, "line"); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + const needle = { + source: util.getArg(aArgs, "source"), + originalLine: line, + originalColumn: util.getArg(aArgs, "column", 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + if (needle.originalLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (needle.originalColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + const mappings = []; + + let index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + let mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + const originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + let lastColumn = mapping.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + mappings.push({ + line: util.getArg(mapping, "generatedLine", null), + column: util.getArg(mapping, "generatedColumn", null), + lastColumn, + }); + + mapping = this._originalMappings[++index]; + } + } else { + const originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + let lastColumn = mapping.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + mappings.push({ + line: util.getArg(mapping, "generatedLine", null), + column: util.getArg(mapping, "generatedColumn", null), + lastColumn, + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + } + + destroy() { + for (let i = 0; i < this._sections.length; i++) { + this._sections[i].consumer.destroy(); + } + } +} +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + +/* + * Cheat to get around inter-twingled classes. `factory()` can be at the end + * where it has access to non-hoisted classes, but it gets hoisted itself. + */ +function _factory(aSourceMap, aSourceMapURL) { + let sourceMap = aSourceMap; + if (typeof aSourceMap === "string") { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + const consumer = sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + return Promise.resolve(consumer); +} + +function _factoryBSM(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/source-map-generator.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/source-map-generator.js new file mode 100644 index 0000000..8111e06 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/source-map-generator.js @@ -0,0 +1,413 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +const base64VLQ = require("./base64-vlq"); +const util = require("./util"); +const ArraySet = require("./array-set").ArraySet; +const MappingList = require("./mapping-list").MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +class SourceMapGenerator { + constructor(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, "file", null); + this._sourceRoot = util.getArg(aArgs, "sourceRoot", null); + this._skipValidation = util.getArg(aArgs, "skipValidation", false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + static fromSourceMap(aSourceMapConsumer) { + const sourceRoot = aSourceMapConsumer.sourceRoot; + const generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot + }); + aSourceMapConsumer.eachMapping(function(mapping) { + const newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function(sourceFile) { + let sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + const content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + } + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + addMapping(aArgs) { + const generated = util.getArg(aArgs, "generated"); + const original = util.getArg(aArgs, "original", null); + let source = util.getArg(aArgs, "source", null); + let name = util.getArg(aArgs, "name", null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source, + name + }); + } + + /** + * Set the source content for a source file. + */ + setSourceContent(aSourceFile, aSourceContent) { + let source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + } + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + let sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + "SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, " + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + const sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + const newSources = this._mappings.toArray().length > 0 + ? new ArraySet() + : this._sources; + const newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function(mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + const original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source); + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + const source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + const name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function(srcFile) { + const content = aSourceMapConsumer.sourceContentFor(srcFile); + if (content != null) { + if (aSourceMapPath != null) { + srcFile = util.join(aSourceMapPath, srcFile); + } + if (sourceRoot != null) { + srcFile = util.relative(sourceRoot, srcFile); + } + this.setSourceContent(srcFile, content); + } + }, this); + } + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + _validateMapping(aGenerated, aOriginal, aSource, aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") { + throw new Error( + "original.line and original.column are not numbers -- you probably meant to omit " + + "the original mapping entirely and only map the generated position. If so, pass " + + "null for the original mapping instead of an object with empty or null values." + ); + } + + if (aGenerated && "line" in aGenerated && "column" in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + + } else if (aGenerated && "line" in aGenerated && "column" in aGenerated + && aOriginal && "line" in aOriginal && "column" in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + + } else { + throw new Error("Invalid mapping: " + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + } + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + _serializeMappings() { + let previousGeneratedColumn = 0; + let previousGeneratedLine = 1; + let previousOriginalColumn = 0; + let previousOriginalLine = 0; + let previousName = 0; + let previousSource = 0; + let result = ""; + let next; + let mapping; + let nameIdx; + let sourceIdx; + + const mappings = this._mappings.toArray(); + for (let i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = ""; + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ";"; + previousGeneratedLine++; + } + } else if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ","; + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + } + + _generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function(source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + const key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + } + + /** + * Externalize the source map. + */ + toJSON() { + const map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + } + + /** + * Render the source map being generated to a string. + */ + toString() { + return JSON.stringify(this.toJSON()); + } +} + +SourceMapGenerator.prototype._version = 3; +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/source-node.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/source-node.js new file mode 100644 index 0000000..8a7a157 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/source-node.js @@ -0,0 +1,404 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +const SourceMapGenerator = require("./source-map-generator").SourceMapGenerator; +const util = require("./util"); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +const REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +const NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +const isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +class SourceNode { + constructor(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + static fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + const node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + const remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + let remainingLinesIndex = 0; + const shiftNextLine = function() { + const lineContents = getNextLine(); + // The last line of a file might not have a newline. + const newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + let lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + let lastMapping = null; + let nextLine; + + aSourceMapConsumer.eachMapping(function(mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + nextLine = remainingLines[remainingLinesIndex] || ""; + const code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + nextLine = remainingLines[remainingLinesIndex] || ""; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function(sourceFile) { + const content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + const source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + } + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function(chunk) { + this.add(chunk); + }, this); + } else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + } + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (let i = aChunk.length - 1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + } + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + walk(aFn) { + let chunk; + for (let i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } else if (chunk !== "") { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + join(aSep) { + let newChildren; + let i; + const len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len - 1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + } + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + replaceRight(aPattern, aReplacement) { + const lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } else if (typeof lastChild === "string") { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } else { + this.children.push("".replace(aPattern, aReplacement)); + } + return this; + } + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + } + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + walkSourceContents(aFn) { + for (let i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + const sources = Object.keys(this.sourceContents); + for (let i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + } + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + toString() { + let str = ""; + this.walk(function(chunk) { + str += chunk; + }); + return str; + } + + /** + * Returns the string representation of this source node along with a source + * map. + */ + toStringWithSourceMap(aArgs) { + const generated = { + code: "", + line: 1, + column: 0 + }; + const map = new SourceMapGenerator(aArgs); + let sourceMappingActive = false; + let lastOriginalSource = null; + let lastOriginalLine = null; + let lastOriginalColumn = null; + let lastOriginalName = null; + this.walk(function(chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if (lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (let idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function(sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map }; + } +} + +exports.SourceNode = SourceNode; diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/util.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/util.js new file mode 100644 index 0000000..35bd93d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/util.js @@ -0,0 +1,546 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } + throw new Error('"' + aName + '" is a required argument.'); + +} +exports.getArg = getArg; + +const urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +const dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + const match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + let url = ""; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ":"; + } + url += "//"; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + "@"; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port; + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +const MAX_CACHED_INPUTS = 32; + +/** + * Takes some function `f(input) -> result` and returns a memoized version of + * `f`. + * + * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The + * memoization is a dumb-simple, linear least-recently-used cache. + */ +function lruMemoize(f) { + const cache = []; + + return function(input) { + for (let i = 0; i < cache.length; i++) { + if (cache[i].input === input) { + const temp = cache[0]; + cache[0] = cache[i]; + cache[i] = temp; + return cache[0].result; + } + } + + const result = f(input); + + cache.unshift({ + input, + result, + }); + + if (cache.length > MAX_CACHED_INPUTS) { + cache.pop(); + } + + return result; + }; +} + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +const normalize = lruMemoize(function normalize(aPath) { + let path = aPath; + const url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + const isAbsolute = exports.isAbsolute(path); + + // Split the path into parts between `/` characters. This is much faster than + // using `.split(/\/+/g)`. + const parts = []; + let start = 0; + let i = 0; + while (true) { + start = i; + i = path.indexOf("/", start); + if (i === -1) { + parts.push(path.slice(start)); + break; + } else { + parts.push(path.slice(start, i)); + while (i < path.length && path[i] === "/") { + i++; + } + } + } + + let up = 0; + for (i = parts.length - 1; i >= 0; i--) { + const part = parts[i]; + if (part === ".") { + parts.splice(i, 1); + } else if (part === "..") { + up++; + } else if (up > 0) { + if (part === "") { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join("/"); + + if (path === "") { + path = isAbsolute ? "/" : "."; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +}); +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + const aPathUrl = urlParse(aPath); + const aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || "/"; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + const joined = aPath.charAt(0) === "/" + ? aPath + : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function(aPath) { + return aPath.charAt(0) === "/" || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ""); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + let level = 0; + while (aPath.indexOf(aRoot + "/") !== 0) { + const index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +const supportsNullProto = (function() { + const obj = Object.create(null); + return !("__proto__" in obj); +}()); + +function identity(s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return "$" + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + const length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + /* eslint-disable no-multi-spaces */ + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + /* eslint-enable no-multi-spaces */ + + for (let i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + let cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + let cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + let cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, "")); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ""; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") { + sourceRoot += "/"; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + const parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + const index = parsed.path.lastIndexOf("/"); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/wasm.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/wasm.js new file mode 100644 index 0000000..88b18be --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/lib/wasm.js @@ -0,0 +1,107 @@ +const readWasm = require("../lib/read-wasm"); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.lastGeneratedColumn = null; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +let cachedWasm = null; + +module.exports = function wasm() { + if (cachedWasm) { + return cachedWasm; + } + + const callbackStack = []; + + cachedWasm = readWasm().then(buffer => { + return WebAssembly.instantiate(buffer, { + env: { + mapping_callback( + generatedLine, + generatedColumn, + + hasLastGeneratedColumn, + lastGeneratedColumn, + + hasOriginal, + source, + originalLine, + originalColumn, + + hasName, + name + ) { + const mapping = new Mapping(); + // JS uses 1-based line numbers, wasm uses 0-based. + mapping.generatedLine = generatedLine + 1; + mapping.generatedColumn = generatedColumn; + + if (hasLastGeneratedColumn) { + // JS uses inclusive last generated column, wasm uses exclusive. + mapping.lastGeneratedColumn = lastGeneratedColumn - 1; + } + + if (hasOriginal) { + mapping.source = source; + // JS uses 1-based line numbers, wasm uses 0-based. + mapping.originalLine = originalLine + 1; + mapping.originalColumn = originalColumn; + + if (hasName) { + mapping.name = name; + } + } + + callbackStack[callbackStack.length - 1](mapping); + }, + + start_all_generated_locations_for() { console.time("all_generated_locations_for"); }, + end_all_generated_locations_for() { console.timeEnd("all_generated_locations_for"); }, + + start_compute_column_spans() { console.time("compute_column_spans"); }, + end_compute_column_spans() { console.timeEnd("compute_column_spans"); }, + + start_generated_location_for() { console.time("generated_location_for"); }, + end_generated_location_for() { console.timeEnd("generated_location_for"); }, + + start_original_location_for() { console.time("original_location_for"); }, + end_original_location_for() { console.timeEnd("original_location_for"); }, + + start_parse_mappings() { console.time("parse_mappings"); }, + end_parse_mappings() { console.timeEnd("parse_mappings"); }, + + start_sort_by_generated_location() { console.time("sort_by_generated_location"); }, + end_sort_by_generated_location() { console.timeEnd("sort_by_generated_location"); }, + + start_sort_by_original_location() { console.time("sort_by_original_location"); }, + end_sort_by_original_location() { console.timeEnd("sort_by_original_location"); }, + } + }); + }).then(Wasm => { + return { + exports: Wasm.instance.exports, + withMappingCallback: (mappingCallback, f) => { + callbackStack.push(mappingCallback); + try { + f(); + } finally { + callbackStack.pop(); + } + } + }; + }).then(null, e => { + cachedWasm = null; + throw e; + }); + + return cachedWasm; +}; diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/package.json b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/package.json new file mode 100644 index 0000000..35476da --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/package.json @@ -0,0 +1,90 @@ +{ + "name": "source-map", + "description": "Generates and consumes source maps", + "version": "0.7.3", + "homepage": "https://github.com/mozilla/source-map", + "author": "Nick Fitzgerald ", + "contributors": [ + "Tobias Koppers ", + "Duncan Beevers ", + "Stephen Crane ", + "Ryan Seddon ", + "Miles Elam ", + "Mihai Bazon ", + "Michael Ficarra ", + "Todd Wolfson ", + "Alexander Solovyov ", + "Felix Gnass ", + "Conrad Irwin ", + "usrbincc ", + "David Glasser ", + "Chase Douglas ", + "Evan Wallace ", + "Heather Arthur ", + "Hugh Kennedy ", + "David Glasser ", + "Simon Lydell ", + "Jmeas Smith ", + "Michael Z Goddard ", + "azu ", + "John Gozde ", + "Adam Kirkton ", + "Chris Montgomery ", + "J. Ryan Stinnett ", + "Jack Herrington ", + "Chris Truter ", + "Daniel Espeset ", + "Jamie Wong ", + "Eddy Bruël ", + "Hawken Rives ", + "Gilad Peleg ", + "djchie ", + "Gary Ye ", + "Nicolas Lalevée " + ], + "repository": { + "type": "git", + "url": "http://github.com/mozilla/source-map.git" + }, + "main": "./source-map.js", + "types": "./source-map.d.ts", + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/", + "dist/source-map.js" + ], + "engines": { + "node": ">= 8" + }, + "license": "BSD-3-Clause", + "scripts": { + "lint": "eslint *.js lib/ test/", + "prebuild": "npm run lint", + "build": "webpack --color", + "pretest": "npm run build", + "test": "node test/run-tests.js", + "precoverage": "npm run build", + "coverage": "nyc node test/run-tests.js", + "setup": "mkdir -p coverage && cp -n .waiting.html coverage/index.html || true", + "dev:live": "live-server --port=4103 --ignorePattern='(js|css|png)$' coverage", + "dev:watch": "watch 'npm run coverage' lib/ test/", + "predev": "npm run setup", + "dev": "npm-run-all -p --silent dev:*", + "clean": "rm -rf coverage .nyc_output", + "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" + }, + "devDependencies": { + "doctoc": "^0.15.0", + "eslint": "^4.19.1", + "live-server": "^1.2.0", + "npm-run-all": "^4.1.2", + "nyc": "^11.7.1", + "watch": "^1.0.2", + "webpack": "^3.10" + }, + "nyc": { + "reporter": "html" + }, + "typings": "source-map" +} diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/source-map.d.ts b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/source-map.d.ts new file mode 100644 index 0000000..2459391 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/source-map.d.ts @@ -0,0 +1,369 @@ +// Type definitions for source-map 0.7 +// Project: https://github.com/mozilla/source-map +// Definitions by: Morten Houston Ludvigsen , +// Ron Buckton , +// John Vilk +// Definitions: https://github.com/mozilla/source-map +export type SourceMapUrl = string; + +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; + skipValidation?: boolean; +} + +export interface RawSourceMap { + version: number; + sources: string[]; + names: string[]; + sourceRoot?: string; + sourcesContent?: string[]; + mappings: string; + file: string; +} + +export interface RawIndexMap extends StartOfSourceMap { + version: number; + sections: RawSection[]; +} + +export interface RawSection { + offset: Position; + map: RawSourceMap; +} + +export interface Position { + line: number; + column: number; +} + +export interface NullablePosition { + line: number | null; + column: number | null; + lastColumn: number | null; +} + +export interface MappedPosition { + source: string; + line: number; + column: number; + name?: string; +} + +export interface NullableMappedPosition { + source: string | null; + line: number | null; + column: number | null; + name: string | null; +} + +export interface MappingItem { + source: string; + generatedLine: number; + generatedColumn: number; + originalLine: number; + originalColumn: number; + name: string; +} + +export interface Mapping { + generated: Position; + original: Position; + source: string; + name?: string; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export interface SourceMapConsumer { + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + computeColumnSpans(): void; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + originalPositionFor(generatedPosition: Position & { bias?: number }): NullableMappedPosition; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + generatedPositionFor(originalPosition: MappedPosition & { bias?: number }): NullablePosition; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + allGeneratedPositionsFor(originalPosition: MappedPosition): NullablePosition[]; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + hasContentsOfAllSources(): boolean; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param callback + * The function that is called with each mapping. + * @param context + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param order + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; + /** + * Free this source map consumer's associated wasm data that is manually-managed. + * Alternatively, you can use SourceMapConsumer.with to avoid needing to remember to call destroy. + */ + destroy(): void; +} + +export interface SourceMapConsumerConstructor { + prototype: SourceMapConsumer; + + GENERATED_ORDER: number; + ORIGINAL_ORDER: number; + GREATEST_LOWER_BOUND: number; + LEAST_UPPER_BOUND: number; + + new (rawSourceMap: RawSourceMap, sourceMapUrl?: SourceMapUrl): Promise; + new (rawSourceMap: RawIndexMap, sourceMapUrl?: SourceMapUrl): Promise; + new (rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl?: SourceMapUrl): Promise; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param sourceMap + * The source map that will be consumed. + */ + fromSourceMap(sourceMap: SourceMapGenerator, sourceMapUrl?: SourceMapUrl): Promise; + + /** + * Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl` + * (see the `SourceMapConsumer` constructor for details. Then, invoke the `async + * function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait + * for `f` to complete, call `destroy` on the consumer, and return `f`'s return + * value. + * + * You must not use the consumer after `f` completes! + * + * By using `with`, you do not have to remember to manually call `destroy` on + * the consumer, since it will be called automatically once `f` completes. + * + * ```js + * const xSquared = await SourceMapConsumer.with( + * myRawSourceMap, + * null, + * async function (consumer) { + * // Use `consumer` inside here and don't worry about remembering + * // to call `destroy`. + * + * const x = await whatever(consumer); + * return x * x; + * } + * ); + * + * // You may not use that `consumer` anymore out here; it has + * // been destroyed. But you can use `xSquared`. + * console.log(xSquared); + * ``` + */ + with(rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl: SourceMapUrl | null | undefined, callback: (consumer: BasicSourceMapConsumer | IndexedSourceMapConsumer) => Promise | T): Promise; +} + +export const SourceMapConsumer: SourceMapConsumerConstructor; + +export interface BasicSourceMapConsumer extends SourceMapConsumer { + file: string; + sourceRoot: string; + sources: string[]; + sourcesContent: string[]; +} + +export interface BasicSourceMapConsumerConstructor { + prototype: BasicSourceMapConsumer; + + new (rawSourceMap: RawSourceMap | string): Promise; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param sourceMap + * The source map that will be consumed. + */ + fromSourceMap(sourceMap: SourceMapGenerator): Promise; +} + +export const BasicSourceMapConsumer: BasicSourceMapConsumerConstructor; + +export interface IndexedSourceMapConsumer extends SourceMapConsumer { + sources: string[]; +} + +export interface IndexedSourceMapConsumerConstructor { + prototype: IndexedSourceMapConsumer; + + new (rawSourceMap: RawIndexMap | string): Promise; +} + +export const IndexedSourceMapConsumer: IndexedSourceMapConsumerConstructor; + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param sourceMapConsumer The SourceMap. + */ + static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + addMapping(mapping: Mapping): void; + + /** + * Set the source content for a source file. + */ + setSourceContent(sourceFile: string, sourceContent: string): void; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param sourceMapConsumer The source map to be applied. + * @param sourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param sourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + + toString(): string; + + toJSON(): RawSourceMap; +} + +export class SourceNode { + children: SourceNode[]; + sourceContents: any; + line: number; + column: number; + source: string; + name: string; + + constructor(); + constructor( + line: number | null, + column: number | null, + source: string | null, + chunks?: Array<(string | SourceNode)> | SourceNode | string, + name?: string + ); + + static fromStringWithSourceMap( + code: string, + sourceMapConsumer: SourceMapConsumer, + relativePath?: string + ): SourceNode; + + add(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode; + + prepend(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode; + + setSourceContent(sourceFile: string, sourceContent: string): void; + + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + + walkSourceContents(fn: (file: string, content: string) => void): void; + + join(sep: string): SourceNode; + + replaceRight(pattern: string, replacement: string): SourceNode; + + toString(): string; + + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; +} diff --git a/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/source-map.js b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/source-map.js new file mode 100644 index 0000000..a84abf1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/node_modules/source-map/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require("./lib/source-map-generator").SourceMapGenerator; +exports.SourceMapConsumer = require("./lib/source-map-consumer").SourceMapConsumer; +exports.SourceNode = require("./lib/source-node").SourceNode; diff --git a/node_modules/mathjs/examples/node_modules/terser/package.json b/node_modules/mathjs/examples/node_modules/terser/package.json new file mode 100644 index 0000000..9bea454 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/package.json @@ -0,0 +1,152 @@ +{ + "name": "terser", + "description": "JavaScript parser, mangler/compressor and beautifier toolkit for ES6+", + "homepage": "https://terser.org", + "author": "Mihai Bazon (http://lisperator.net/)", + "license": "BSD-2-Clause", + "version": "5.12.1", + "engines": { + "node": ">=10" + }, + "maintainers": [ + "Fábio Santos " + ], + "repository": "https://github.com/terser/terser", + "main": "dist/bundle.min.js", + "type": "module", + "module": "./main.js", + "exports": { + ".": [ + { + "import": "./main.js", + "require": "./dist/bundle.min.js" + }, + "./dist/bundle.min.js" + ], + "./package": "./package.json", + "./package.json": "./package.json", + "./bin/terser": "./bin/terser" + }, + "types": "tools/terser.d.ts", + "bin": { + "terser": "bin/terser" + }, + "files": [ + "bin", + "dist", + "lib", + "tools", + "LICENSE", + "README.md", + "CHANGELOG.md", + "PATRONS.md", + "main.js" + ], + "dependencies": { + "acorn": "^8.5.0", + "commander": "^2.20.0", + "source-map": "~0.7.2", + "source-map-support": "~0.5.20" + }, + "devDependencies": { + "@ls-lint/ls-lint": "^1.10.0", + "astring": "^1.7.5", + "eslint": "^7.32.0", + "eslump": "^3.0.0", + "esm": "^3.2.25", + "mocha": "^9.2.0", + "pre-commit": "^1.2.2", + "rimraf": "^3.0.2", + "rollup": "2.56.3", + "semver": "^7.3.4" + }, + "scripts": { + "test": "node test/compress.js && mocha test/mocha", + "test:compress": "node test/compress.js", + "test:mocha": "mocha test/mocha", + "lint": "eslint lib", + "lint-fix": "eslint --fix lib", + "ls-lint": "ls-lint", + "build": "rimraf dist/bundle* && rollup --config --silent", + "prepare": "npm run build", + "postversion": "echo 'Remember to update the changelog!'" + }, + "keywords": [ + "uglify", + "terser", + "uglify-es", + "uglify-js", + "minify", + "minifier", + "javascript", + "ecmascript", + "es5", + "es6", + "es7", + "es8", + "es2015", + "es2016", + "es2017", + "async", + "await" + ], + "eslintConfig": { + "parserOptions": { + "sourceType": "module", + "ecmaVersion": 2020 + }, + "env": { + "node": true, + "browser": true, + "es2020": true + }, + "globals": { + "describe": false, + "it": false, + "require": false, + "before": false, + "after": false, + "global": false, + "process": false + }, + "rules": { + "brace-style": [ + "error", + "1tbs", + { + "allowSingleLine": true + } + ], + "quotes": [ + "error", + "double", + "avoid-escape" + ], + "no-debugger": "error", + "no-undef": "error", + "no-unused-vars": [ + "error", + { + "varsIgnorePattern": "^_" + } + ], + "no-tabs": "error", + "semi": [ + "error", + "always" + ], + "no-extra-semi": "error", + "no-irregular-whitespace": "error", + "space-before-blocks": [ + "error", + "always" + ] + } + }, + "pre-commit": [ + "build", + "lint-fix", + "ls-lint", + "test" + ] +} diff --git a/node_modules/mathjs/examples/node_modules/terser/tools/domprops.js b/node_modules/mathjs/examples/node_modules/terser/tools/domprops.js new file mode 100644 index 0000000..aa51fb6 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/tools/domprops.js @@ -0,0 +1,7771 @@ +export var domprops = [ + "$&", + "$'", + "$*", + "$+", + "$1", + "$2", + "$3", + "$4", + "$5", + "$6", + "$7", + "$8", + "$9", + "$_", + "$`", + "$input", + "-moz-animation", + "-moz-animation-delay", + "-moz-animation-direction", + "-moz-animation-duration", + "-moz-animation-fill-mode", + "-moz-animation-iteration-count", + "-moz-animation-name", + "-moz-animation-play-state", + "-moz-animation-timing-function", + "-moz-appearance", + "-moz-backface-visibility", + "-moz-border-end", + "-moz-border-end-color", + "-moz-border-end-style", + "-moz-border-end-width", + "-moz-border-image", + "-moz-border-start", + "-moz-border-start-color", + "-moz-border-start-style", + "-moz-border-start-width", + "-moz-box-align", + "-moz-box-direction", + "-moz-box-flex", + "-moz-box-ordinal-group", + "-moz-box-orient", + "-moz-box-pack", + "-moz-box-sizing", + "-moz-float-edge", + "-moz-font-feature-settings", + "-moz-font-language-override", + "-moz-force-broken-image-icon", + "-moz-hyphens", + "-moz-image-region", + "-moz-margin-end", + "-moz-margin-start", + "-moz-orient", + "-moz-osx-font-smoothing", + "-moz-outline-radius", + "-moz-outline-radius-bottomleft", + "-moz-outline-radius-bottomright", + "-moz-outline-radius-topleft", + "-moz-outline-radius-topright", + "-moz-padding-end", + "-moz-padding-start", + "-moz-perspective", + "-moz-perspective-origin", + "-moz-tab-size", + "-moz-text-size-adjust", + "-moz-transform", + "-moz-transform-origin", + "-moz-transform-style", + "-moz-transition", + "-moz-transition-delay", + "-moz-transition-duration", + "-moz-transition-property", + "-moz-transition-timing-function", + "-moz-user-focus", + "-moz-user-input", + "-moz-user-modify", + "-moz-user-select", + "-moz-window-dragging", + "-webkit-align-content", + "-webkit-align-items", + "-webkit-align-self", + "-webkit-animation", + "-webkit-animation-delay", + "-webkit-animation-direction", + "-webkit-animation-duration", + "-webkit-animation-fill-mode", + "-webkit-animation-iteration-count", + "-webkit-animation-name", + "-webkit-animation-play-state", + "-webkit-animation-timing-function", + "-webkit-appearance", + "-webkit-backface-visibility", + "-webkit-background-clip", + "-webkit-background-origin", + "-webkit-background-size", + "-webkit-border-bottom-left-radius", + "-webkit-border-bottom-right-radius", + "-webkit-border-image", + "-webkit-border-radius", + "-webkit-border-top-left-radius", + "-webkit-border-top-right-radius", + "-webkit-box-align", + "-webkit-box-direction", + "-webkit-box-flex", + "-webkit-box-ordinal-group", + "-webkit-box-orient", + "-webkit-box-pack", + "-webkit-box-shadow", + "-webkit-box-sizing", + "-webkit-filter", + "-webkit-flex", + "-webkit-flex-basis", + "-webkit-flex-direction", + "-webkit-flex-flow", + "-webkit-flex-grow", + "-webkit-flex-shrink", + "-webkit-flex-wrap", + "-webkit-justify-content", + "-webkit-line-clamp", + "-webkit-mask", + "-webkit-mask-clip", + "-webkit-mask-composite", + "-webkit-mask-image", + "-webkit-mask-origin", + "-webkit-mask-position", + "-webkit-mask-position-x", + "-webkit-mask-position-y", + "-webkit-mask-repeat", + "-webkit-mask-size", + "-webkit-order", + "-webkit-perspective", + "-webkit-perspective-origin", + "-webkit-text-fill-color", + "-webkit-text-size-adjust", + "-webkit-text-stroke", + "-webkit-text-stroke-color", + "-webkit-text-stroke-width", + "-webkit-transform", + "-webkit-transform-origin", + "-webkit-transform-style", + "-webkit-transition", + "-webkit-transition-delay", + "-webkit-transition-duration", + "-webkit-transition-property", + "-webkit-transition-timing-function", + "-webkit-user-select", + "0", + "1", + "10", + "11", + "12", + "13", + "14", + "15", + "16", + "17", + "18", + "19", + "2", + "20", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "@@iterator", + "ABORT_ERR", + "ACTIVE", + "ACTIVE_ATTRIBUTES", + "ACTIVE_TEXTURE", + "ACTIVE_UNIFORMS", + "ACTIVE_UNIFORM_BLOCKS", + "ADDITION", + "ALIASED_LINE_WIDTH_RANGE", + "ALIASED_POINT_SIZE_RANGE", + "ALLOW_KEYBOARD_INPUT", + "ALLPASS", + "ALPHA", + "ALPHA_BITS", + "ALREADY_SIGNALED", + "ALT_MASK", + "ALWAYS", + "ANY_SAMPLES_PASSED", + "ANY_SAMPLES_PASSED_CONSERVATIVE", + "ANY_TYPE", + "ANY_UNORDERED_NODE_TYPE", + "ARRAY_BUFFER", + "ARRAY_BUFFER_BINDING", + "ATTACHED_SHADERS", + "ATTRIBUTE_NODE", + "AT_TARGET", + "AbortController", + "AbortSignal", + "AbsoluteOrientationSensor", + "AbstractRange", + "Accelerometer", + "AddSearchProvider", + "AggregateError", + "AnalyserNode", + "Animation", + "AnimationEffect", + "AnimationEvent", + "AnimationPlaybackEvent", + "AnimationTimeline", + "AnonXMLHttpRequest", + "Any", + "ApplicationCache", + "ApplicationCacheErrorEvent", + "Array", + "ArrayBuffer", + "ArrayType", + "Atomics", + "Attr", + "Audio", + "AudioBuffer", + "AudioBufferSourceNode", + "AudioContext", + "AudioDestinationNode", + "AudioListener", + "AudioNode", + "AudioParam", + "AudioParamMap", + "AudioProcessingEvent", + "AudioScheduledSourceNode", + "AudioStreamTrack", + "AudioWorklet", + "AudioWorkletNode", + "AuthenticatorAssertionResponse", + "AuthenticatorAttestationResponse", + "AuthenticatorResponse", + "AutocompleteErrorEvent", + "BACK", + "BAD_BOUNDARYPOINTS_ERR", + "BAD_REQUEST", + "BANDPASS", + "BLEND", + "BLEND_COLOR", + "BLEND_DST_ALPHA", + "BLEND_DST_RGB", + "BLEND_EQUATION", + "BLEND_EQUATION_ALPHA", + "BLEND_EQUATION_RGB", + "BLEND_SRC_ALPHA", + "BLEND_SRC_RGB", + "BLUE_BITS", + "BLUR", + "BOOL", + "BOOLEAN_TYPE", + "BOOL_VEC2", + "BOOL_VEC3", + "BOOL_VEC4", + "BOTH", + "BROWSER_DEFAULT_WEBGL", + "BUBBLING_PHASE", + "BUFFER_SIZE", + "BUFFER_USAGE", + "BYTE", + "BYTES_PER_ELEMENT", + "BackgroundFetchManager", + "BackgroundFetchRecord", + "BackgroundFetchRegistration", + "BarProp", + "BarcodeDetector", + "BaseAudioContext", + "BaseHref", + "BatteryManager", + "BeforeInstallPromptEvent", + "BeforeLoadEvent", + "BeforeUnloadEvent", + "BigInt", + "BigInt64Array", + "BigUint64Array", + "BiquadFilterNode", + "Blob", + "BlobEvent", + "Bluetooth", + "BluetoothCharacteristicProperties", + "BluetoothDevice", + "BluetoothRemoteGATTCharacteristic", + "BluetoothRemoteGATTDescriptor", + "BluetoothRemoteGATTServer", + "BluetoothRemoteGATTService", + "BluetoothUUID", + "Boolean", + "BroadcastChannel", + "ByteLengthQueuingStrategy", + "CAPTURING_PHASE", + "CCW", + "CDATASection", + "CDATA_SECTION_NODE", + "CHANGE", + "CHARSET_RULE", + "CHECKING", + "CLAMP_TO_EDGE", + "CLICK", + "CLOSED", + "CLOSING", + "COLOR", + "COLOR_ATTACHMENT0", + "COLOR_ATTACHMENT1", + "COLOR_ATTACHMENT10", + "COLOR_ATTACHMENT11", + "COLOR_ATTACHMENT12", + "COLOR_ATTACHMENT13", + "COLOR_ATTACHMENT14", + "COLOR_ATTACHMENT15", + "COLOR_ATTACHMENT2", + "COLOR_ATTACHMENT3", + "COLOR_ATTACHMENT4", + "COLOR_ATTACHMENT5", + "COLOR_ATTACHMENT6", + "COLOR_ATTACHMENT7", + "COLOR_ATTACHMENT8", + "COLOR_ATTACHMENT9", + "COLOR_BUFFER_BIT", + "COLOR_CLEAR_VALUE", + "COLOR_WRITEMASK", + "COMMENT_NODE", + "COMPARE_REF_TO_TEXTURE", + "COMPILE_STATUS", + "COMPRESSED_RGBA_S3TC_DXT1_EXT", + "COMPRESSED_RGBA_S3TC_DXT3_EXT", + "COMPRESSED_RGBA_S3TC_DXT5_EXT", + "COMPRESSED_RGB_S3TC_DXT1_EXT", + "COMPRESSED_TEXTURE_FORMATS", + "CONDITION_SATISFIED", + "CONFIGURATION_UNSUPPORTED", + "CONNECTING", + "CONSTANT_ALPHA", + "CONSTANT_COLOR", + "CONSTRAINT_ERR", + "CONTEXT_LOST_WEBGL", + "CONTROL_MASK", + "COPY_READ_BUFFER", + "COPY_READ_BUFFER_BINDING", + "COPY_WRITE_BUFFER", + "COPY_WRITE_BUFFER_BINDING", + "COUNTER_STYLE_RULE", + "CSS", + "CSS2Properties", + "CSSAnimation", + "CSSCharsetRule", + "CSSConditionRule", + "CSSCounterStyleRule", + "CSSFontFaceRule", + "CSSFontFeatureValuesRule", + "CSSGroupingRule", + "CSSImageValue", + "CSSImportRule", + "CSSKeyframeRule", + "CSSKeyframesRule", + "CSSKeywordValue", + "CSSMathInvert", + "CSSMathMax", + "CSSMathMin", + "CSSMathNegate", + "CSSMathProduct", + "CSSMathSum", + "CSSMathValue", + "CSSMatrixComponent", + "CSSMediaRule", + "CSSMozDocumentRule", + "CSSNameSpaceRule", + "CSSNamespaceRule", + "CSSNumericArray", + "CSSNumericValue", + "CSSPageRule", + "CSSPerspective", + "CSSPositionValue", + "CSSPrimitiveValue", + "CSSRotate", + "CSSRule", + "CSSRuleList", + "CSSScale", + "CSSSkew", + "CSSSkewX", + "CSSSkewY", + "CSSStyleDeclaration", + "CSSStyleRule", + "CSSStyleSheet", + "CSSStyleValue", + "CSSSupportsRule", + "CSSTransformComponent", + "CSSTransformValue", + "CSSTransition", + "CSSTranslate", + "CSSUnitValue", + "CSSUnknownRule", + "CSSUnparsedValue", + "CSSValue", + "CSSValueList", + "CSSVariableReferenceValue", + "CSSVariablesDeclaration", + "CSSVariablesRule", + "CSSViewportRule", + "CSS_ATTR", + "CSS_CM", + "CSS_COUNTER", + "CSS_CUSTOM", + "CSS_DEG", + "CSS_DIMENSION", + "CSS_EMS", + "CSS_EXS", + "CSS_FILTER_BLUR", + "CSS_FILTER_BRIGHTNESS", + "CSS_FILTER_CONTRAST", + "CSS_FILTER_CUSTOM", + "CSS_FILTER_DROP_SHADOW", + "CSS_FILTER_GRAYSCALE", + "CSS_FILTER_HUE_ROTATE", + "CSS_FILTER_INVERT", + "CSS_FILTER_OPACITY", + "CSS_FILTER_REFERENCE", + "CSS_FILTER_SATURATE", + "CSS_FILTER_SEPIA", + "CSS_GRAD", + "CSS_HZ", + "CSS_IDENT", + "CSS_IN", + "CSS_INHERIT", + "CSS_KHZ", + "CSS_MATRIX", + "CSS_MATRIX3D", + "CSS_MM", + "CSS_MS", + "CSS_NUMBER", + "CSS_PC", + "CSS_PERCENTAGE", + "CSS_PERSPECTIVE", + "CSS_PRIMITIVE_VALUE", + "CSS_PT", + "CSS_PX", + "CSS_RAD", + "CSS_RECT", + "CSS_RGBCOLOR", + "CSS_ROTATE", + "CSS_ROTATE3D", + "CSS_ROTATEX", + "CSS_ROTATEY", + "CSS_ROTATEZ", + "CSS_S", + "CSS_SCALE", + "CSS_SCALE3D", + "CSS_SCALEX", + "CSS_SCALEY", + "CSS_SCALEZ", + "CSS_SKEW", + "CSS_SKEWX", + "CSS_SKEWY", + "CSS_STRING", + "CSS_TRANSLATE", + "CSS_TRANSLATE3D", + "CSS_TRANSLATEX", + "CSS_TRANSLATEY", + "CSS_TRANSLATEZ", + "CSS_UNKNOWN", + "CSS_URI", + "CSS_VALUE_LIST", + "CSS_VH", + "CSS_VMAX", + "CSS_VMIN", + "CSS_VW", + "CULL_FACE", + "CULL_FACE_MODE", + "CURRENT_PROGRAM", + "CURRENT_QUERY", + "CURRENT_VERTEX_ATTRIB", + "CUSTOM", + "CW", + "Cache", + "CacheStorage", + "CanvasCaptureMediaStream", + "CanvasCaptureMediaStreamTrack", + "CanvasGradient", + "CanvasPattern", + "CanvasRenderingContext2D", + "CaretPosition", + "ChannelMergerNode", + "ChannelSplitterNode", + "CharacterData", + "ClientRect", + "ClientRectList", + "Clipboard", + "ClipboardEvent", + "ClipboardItem", + "CloseEvent", + "Collator", + "CommandEvent", + "Comment", + "CompileError", + "CompositionEvent", + "CompressionStream", + "Console", + "ConstantSourceNode", + "Controllers", + "ConvolverNode", + "CountQueuingStrategy", + "Counter", + "Credential", + "CredentialsContainer", + "Crypto", + "CryptoKey", + "CustomElementRegistry", + "CustomEvent", + "DATABASE_ERR", + "DATA_CLONE_ERR", + "DATA_ERR", + "DBLCLICK", + "DECR", + "DECR_WRAP", + "DELETE_STATUS", + "DEPTH", + "DEPTH24_STENCIL8", + "DEPTH32F_STENCIL8", + "DEPTH_ATTACHMENT", + "DEPTH_BITS", + "DEPTH_BUFFER_BIT", + "DEPTH_CLEAR_VALUE", + "DEPTH_COMPONENT", + "DEPTH_COMPONENT16", + "DEPTH_COMPONENT24", + "DEPTH_COMPONENT32F", + "DEPTH_FUNC", + "DEPTH_RANGE", + "DEPTH_STENCIL", + "DEPTH_STENCIL_ATTACHMENT", + "DEPTH_TEST", + "DEPTH_WRITEMASK", + "DEVICE_INELIGIBLE", + "DIRECTION_DOWN", + "DIRECTION_LEFT", + "DIRECTION_RIGHT", + "DIRECTION_UP", + "DISABLED", + "DISPATCH_REQUEST_ERR", + "DITHER", + "DOCUMENT_FRAGMENT_NODE", + "DOCUMENT_NODE", + "DOCUMENT_POSITION_CONTAINED_BY", + "DOCUMENT_POSITION_CONTAINS", + "DOCUMENT_POSITION_DISCONNECTED", + "DOCUMENT_POSITION_FOLLOWING", + "DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC", + "DOCUMENT_POSITION_PRECEDING", + "DOCUMENT_TYPE_NODE", + "DOMCursor", + "DOMError", + "DOMException", + "DOMImplementation", + "DOMImplementationLS", + "DOMMatrix", + "DOMMatrixReadOnly", + "DOMParser", + "DOMPoint", + "DOMPointReadOnly", + "DOMQuad", + "DOMRect", + "DOMRectList", + "DOMRectReadOnly", + "DOMRequest", + "DOMSTRING_SIZE_ERR", + "DOMSettableTokenList", + "DOMStringList", + "DOMStringMap", + "DOMTokenList", + "DOMTransactionEvent", + "DOM_DELTA_LINE", + "DOM_DELTA_PAGE", + "DOM_DELTA_PIXEL", + "DOM_INPUT_METHOD_DROP", + "DOM_INPUT_METHOD_HANDWRITING", + "DOM_INPUT_METHOD_IME", + "DOM_INPUT_METHOD_KEYBOARD", + "DOM_INPUT_METHOD_MULTIMODAL", + "DOM_INPUT_METHOD_OPTION", + "DOM_INPUT_METHOD_PASTE", + "DOM_INPUT_METHOD_SCRIPT", + "DOM_INPUT_METHOD_UNKNOWN", + "DOM_INPUT_METHOD_VOICE", + "DOM_KEY_LOCATION_JOYSTICK", + "DOM_KEY_LOCATION_LEFT", + "DOM_KEY_LOCATION_MOBILE", + "DOM_KEY_LOCATION_NUMPAD", + "DOM_KEY_LOCATION_RIGHT", + "DOM_KEY_LOCATION_STANDARD", + "DOM_VK_0", + "DOM_VK_1", + "DOM_VK_2", + "DOM_VK_3", + "DOM_VK_4", + "DOM_VK_5", + "DOM_VK_6", + "DOM_VK_7", + "DOM_VK_8", + "DOM_VK_9", + "DOM_VK_A", + "DOM_VK_ACCEPT", + "DOM_VK_ADD", + "DOM_VK_ALT", + "DOM_VK_ALTGR", + "DOM_VK_AMPERSAND", + "DOM_VK_ASTERISK", + "DOM_VK_AT", + "DOM_VK_ATTN", + "DOM_VK_B", + "DOM_VK_BACKSPACE", + "DOM_VK_BACK_QUOTE", + "DOM_VK_BACK_SLASH", + "DOM_VK_BACK_SPACE", + "DOM_VK_C", + "DOM_VK_CANCEL", + "DOM_VK_CAPS_LOCK", + "DOM_VK_CIRCUMFLEX", + "DOM_VK_CLEAR", + "DOM_VK_CLOSE_BRACKET", + "DOM_VK_CLOSE_CURLY_BRACKET", + "DOM_VK_CLOSE_PAREN", + "DOM_VK_COLON", + "DOM_VK_COMMA", + "DOM_VK_CONTEXT_MENU", + "DOM_VK_CONTROL", + "DOM_VK_CONVERT", + "DOM_VK_CRSEL", + "DOM_VK_CTRL", + "DOM_VK_D", + "DOM_VK_DECIMAL", + "DOM_VK_DELETE", + "DOM_VK_DIVIDE", + "DOM_VK_DOLLAR", + "DOM_VK_DOUBLE_QUOTE", + "DOM_VK_DOWN", + "DOM_VK_E", + "DOM_VK_EISU", + "DOM_VK_END", + "DOM_VK_ENTER", + "DOM_VK_EQUALS", + "DOM_VK_EREOF", + "DOM_VK_ESCAPE", + "DOM_VK_EXCLAMATION", + "DOM_VK_EXECUTE", + "DOM_VK_EXSEL", + "DOM_VK_F", + "DOM_VK_F1", + "DOM_VK_F10", + "DOM_VK_F11", + "DOM_VK_F12", + "DOM_VK_F13", + "DOM_VK_F14", + "DOM_VK_F15", + "DOM_VK_F16", + "DOM_VK_F17", + "DOM_VK_F18", + "DOM_VK_F19", + "DOM_VK_F2", + "DOM_VK_F20", + "DOM_VK_F21", + "DOM_VK_F22", + "DOM_VK_F23", + "DOM_VK_F24", + "DOM_VK_F25", + "DOM_VK_F26", + "DOM_VK_F27", + "DOM_VK_F28", + "DOM_VK_F29", + "DOM_VK_F3", + "DOM_VK_F30", + "DOM_VK_F31", + "DOM_VK_F32", + "DOM_VK_F33", + "DOM_VK_F34", + "DOM_VK_F35", + "DOM_VK_F36", + "DOM_VK_F4", + "DOM_VK_F5", + "DOM_VK_F6", + "DOM_VK_F7", + "DOM_VK_F8", + "DOM_VK_F9", + "DOM_VK_FINAL", + "DOM_VK_FRONT", + "DOM_VK_G", + "DOM_VK_GREATER_THAN", + "DOM_VK_H", + "DOM_VK_HANGUL", + "DOM_VK_HANJA", + "DOM_VK_HASH", + "DOM_VK_HELP", + "DOM_VK_HK_TOGGLE", + "DOM_VK_HOME", + "DOM_VK_HYPHEN_MINUS", + "DOM_VK_I", + "DOM_VK_INSERT", + "DOM_VK_J", + "DOM_VK_JUNJA", + "DOM_VK_K", + "DOM_VK_KANA", + "DOM_VK_KANJI", + "DOM_VK_L", + "DOM_VK_LEFT", + "DOM_VK_LEFT_TAB", + "DOM_VK_LESS_THAN", + "DOM_VK_M", + "DOM_VK_META", + "DOM_VK_MODECHANGE", + "DOM_VK_MULTIPLY", + "DOM_VK_N", + "DOM_VK_NONCONVERT", + "DOM_VK_NUMPAD0", + "DOM_VK_NUMPAD1", + "DOM_VK_NUMPAD2", + "DOM_VK_NUMPAD3", + "DOM_VK_NUMPAD4", + "DOM_VK_NUMPAD5", + "DOM_VK_NUMPAD6", + "DOM_VK_NUMPAD7", + "DOM_VK_NUMPAD8", + "DOM_VK_NUMPAD9", + "DOM_VK_NUM_LOCK", + "DOM_VK_O", + "DOM_VK_OEM_1", + "DOM_VK_OEM_102", + "DOM_VK_OEM_2", + "DOM_VK_OEM_3", + "DOM_VK_OEM_4", + "DOM_VK_OEM_5", + "DOM_VK_OEM_6", + "DOM_VK_OEM_7", + "DOM_VK_OEM_8", + "DOM_VK_OEM_COMMA", + "DOM_VK_OEM_MINUS", + "DOM_VK_OEM_PERIOD", + "DOM_VK_OEM_PLUS", + "DOM_VK_OPEN_BRACKET", + "DOM_VK_OPEN_CURLY_BRACKET", + "DOM_VK_OPEN_PAREN", + "DOM_VK_P", + "DOM_VK_PA1", + "DOM_VK_PAGEDOWN", + "DOM_VK_PAGEUP", + "DOM_VK_PAGE_DOWN", + "DOM_VK_PAGE_UP", + "DOM_VK_PAUSE", + "DOM_VK_PERCENT", + "DOM_VK_PERIOD", + "DOM_VK_PIPE", + "DOM_VK_PLAY", + "DOM_VK_PLUS", + "DOM_VK_PRINT", + "DOM_VK_PRINTSCREEN", + "DOM_VK_PROCESSKEY", + "DOM_VK_PROPERITES", + "DOM_VK_Q", + "DOM_VK_QUESTION_MARK", + "DOM_VK_QUOTE", + "DOM_VK_R", + "DOM_VK_REDO", + "DOM_VK_RETURN", + "DOM_VK_RIGHT", + "DOM_VK_S", + "DOM_VK_SCROLL_LOCK", + "DOM_VK_SELECT", + "DOM_VK_SEMICOLON", + "DOM_VK_SEPARATOR", + "DOM_VK_SHIFT", + "DOM_VK_SLASH", + "DOM_VK_SLEEP", + "DOM_VK_SPACE", + "DOM_VK_SUBTRACT", + "DOM_VK_T", + "DOM_VK_TAB", + "DOM_VK_TILDE", + "DOM_VK_U", + "DOM_VK_UNDERSCORE", + "DOM_VK_UNDO", + "DOM_VK_UNICODE", + "DOM_VK_UP", + "DOM_VK_V", + "DOM_VK_VOLUME_DOWN", + "DOM_VK_VOLUME_MUTE", + "DOM_VK_VOLUME_UP", + "DOM_VK_W", + "DOM_VK_WIN", + "DOM_VK_WINDOW", + "DOM_VK_WIN_ICO_00", + "DOM_VK_WIN_ICO_CLEAR", + "DOM_VK_WIN_ICO_HELP", + "DOM_VK_WIN_OEM_ATTN", + "DOM_VK_WIN_OEM_AUTO", + "DOM_VK_WIN_OEM_BACKTAB", + "DOM_VK_WIN_OEM_CLEAR", + "DOM_VK_WIN_OEM_COPY", + "DOM_VK_WIN_OEM_CUSEL", + "DOM_VK_WIN_OEM_ENLW", + "DOM_VK_WIN_OEM_FINISH", + "DOM_VK_WIN_OEM_FJ_JISHO", + "DOM_VK_WIN_OEM_FJ_LOYA", + "DOM_VK_WIN_OEM_FJ_MASSHOU", + "DOM_VK_WIN_OEM_FJ_ROYA", + "DOM_VK_WIN_OEM_FJ_TOUROKU", + "DOM_VK_WIN_OEM_JUMP", + "DOM_VK_WIN_OEM_PA1", + "DOM_VK_WIN_OEM_PA2", + "DOM_VK_WIN_OEM_PA3", + "DOM_VK_WIN_OEM_RESET", + "DOM_VK_WIN_OEM_WSCTRL", + "DOM_VK_X", + "DOM_VK_XF86XK_ADD_FAVORITE", + "DOM_VK_XF86XK_APPLICATION_LEFT", + "DOM_VK_XF86XK_APPLICATION_RIGHT", + "DOM_VK_XF86XK_AUDIO_CYCLE_TRACK", + "DOM_VK_XF86XK_AUDIO_FORWARD", + "DOM_VK_XF86XK_AUDIO_LOWER_VOLUME", + "DOM_VK_XF86XK_AUDIO_MEDIA", + "DOM_VK_XF86XK_AUDIO_MUTE", + "DOM_VK_XF86XK_AUDIO_NEXT", + "DOM_VK_XF86XK_AUDIO_PAUSE", + "DOM_VK_XF86XK_AUDIO_PLAY", + "DOM_VK_XF86XK_AUDIO_PREV", + "DOM_VK_XF86XK_AUDIO_RAISE_VOLUME", + "DOM_VK_XF86XK_AUDIO_RANDOM_PLAY", + "DOM_VK_XF86XK_AUDIO_RECORD", + "DOM_VK_XF86XK_AUDIO_REPEAT", + "DOM_VK_XF86XK_AUDIO_REWIND", + "DOM_VK_XF86XK_AUDIO_STOP", + "DOM_VK_XF86XK_AWAY", + "DOM_VK_XF86XK_BACK", + "DOM_VK_XF86XK_BACK_FORWARD", + "DOM_VK_XF86XK_BATTERY", + "DOM_VK_XF86XK_BLUE", + "DOM_VK_XF86XK_BLUETOOTH", + "DOM_VK_XF86XK_BOOK", + "DOM_VK_XF86XK_BRIGHTNESS_ADJUST", + "DOM_VK_XF86XK_CALCULATOR", + "DOM_VK_XF86XK_CALENDAR", + "DOM_VK_XF86XK_CD", + "DOM_VK_XF86XK_CLOSE", + "DOM_VK_XF86XK_COMMUNITY", + "DOM_VK_XF86XK_CONTRAST_ADJUST", + "DOM_VK_XF86XK_COPY", + "DOM_VK_XF86XK_CUT", + "DOM_VK_XF86XK_CYCLE_ANGLE", + "DOM_VK_XF86XK_DISPLAY", + "DOM_VK_XF86XK_DOCUMENTS", + "DOM_VK_XF86XK_DOS", + "DOM_VK_XF86XK_EJECT", + "DOM_VK_XF86XK_EXCEL", + "DOM_VK_XF86XK_EXPLORER", + "DOM_VK_XF86XK_FAVORITES", + "DOM_VK_XF86XK_FINANCE", + "DOM_VK_XF86XK_FORWARD", + "DOM_VK_XF86XK_FRAME_BACK", + "DOM_VK_XF86XK_FRAME_FORWARD", + "DOM_VK_XF86XK_GAME", + "DOM_VK_XF86XK_GO", + "DOM_VK_XF86XK_GREEN", + "DOM_VK_XF86XK_HIBERNATE", + "DOM_VK_XF86XK_HISTORY", + "DOM_VK_XF86XK_HOME_PAGE", + "DOM_VK_XF86XK_HOT_LINKS", + "DOM_VK_XF86XK_I_TOUCH", + "DOM_VK_XF86XK_KBD_BRIGHTNESS_DOWN", + "DOM_VK_XF86XK_KBD_BRIGHTNESS_UP", + "DOM_VK_XF86XK_KBD_LIGHT_ON_OFF", + "DOM_VK_XF86XK_LAUNCH0", + "DOM_VK_XF86XK_LAUNCH1", + "DOM_VK_XF86XK_LAUNCH2", + "DOM_VK_XF86XK_LAUNCH3", + "DOM_VK_XF86XK_LAUNCH4", + "DOM_VK_XF86XK_LAUNCH5", + "DOM_VK_XF86XK_LAUNCH6", + "DOM_VK_XF86XK_LAUNCH7", + "DOM_VK_XF86XK_LAUNCH8", + "DOM_VK_XF86XK_LAUNCH9", + "DOM_VK_XF86XK_LAUNCH_A", + "DOM_VK_XF86XK_LAUNCH_B", + "DOM_VK_XF86XK_LAUNCH_C", + "DOM_VK_XF86XK_LAUNCH_D", + "DOM_VK_XF86XK_LAUNCH_E", + "DOM_VK_XF86XK_LAUNCH_F", + "DOM_VK_XF86XK_LIGHT_BULB", + "DOM_VK_XF86XK_LOG_OFF", + "DOM_VK_XF86XK_MAIL", + "DOM_VK_XF86XK_MAIL_FORWARD", + "DOM_VK_XF86XK_MARKET", + "DOM_VK_XF86XK_MEETING", + "DOM_VK_XF86XK_MEMO", + "DOM_VK_XF86XK_MENU_KB", + "DOM_VK_XF86XK_MENU_PB", + "DOM_VK_XF86XK_MESSENGER", + "DOM_VK_XF86XK_MON_BRIGHTNESS_DOWN", + "DOM_VK_XF86XK_MON_BRIGHTNESS_UP", + "DOM_VK_XF86XK_MUSIC", + "DOM_VK_XF86XK_MY_COMPUTER", + "DOM_VK_XF86XK_MY_SITES", + "DOM_VK_XF86XK_NEW", + "DOM_VK_XF86XK_NEWS", + "DOM_VK_XF86XK_OFFICE_HOME", + "DOM_VK_XF86XK_OPEN", + "DOM_VK_XF86XK_OPEN_URL", + "DOM_VK_XF86XK_OPTION", + "DOM_VK_XF86XK_PASTE", + "DOM_VK_XF86XK_PHONE", + "DOM_VK_XF86XK_PICTURES", + "DOM_VK_XF86XK_POWER_DOWN", + "DOM_VK_XF86XK_POWER_OFF", + "DOM_VK_XF86XK_RED", + "DOM_VK_XF86XK_REFRESH", + "DOM_VK_XF86XK_RELOAD", + "DOM_VK_XF86XK_REPLY", + "DOM_VK_XF86XK_ROCKER_DOWN", + "DOM_VK_XF86XK_ROCKER_ENTER", + "DOM_VK_XF86XK_ROCKER_UP", + "DOM_VK_XF86XK_ROTATE_WINDOWS", + "DOM_VK_XF86XK_ROTATION_KB", + "DOM_VK_XF86XK_ROTATION_PB", + "DOM_VK_XF86XK_SAVE", + "DOM_VK_XF86XK_SCREEN_SAVER", + "DOM_VK_XF86XK_SCROLL_CLICK", + "DOM_VK_XF86XK_SCROLL_DOWN", + "DOM_VK_XF86XK_SCROLL_UP", + "DOM_VK_XF86XK_SEARCH", + "DOM_VK_XF86XK_SEND", + "DOM_VK_XF86XK_SHOP", + "DOM_VK_XF86XK_SPELL", + "DOM_VK_XF86XK_SPLIT_SCREEN", + "DOM_VK_XF86XK_STANDBY", + "DOM_VK_XF86XK_START", + "DOM_VK_XF86XK_STOP", + "DOM_VK_XF86XK_SUBTITLE", + "DOM_VK_XF86XK_SUPPORT", + "DOM_VK_XF86XK_SUSPEND", + "DOM_VK_XF86XK_TASK_PANE", + "DOM_VK_XF86XK_TERMINAL", + "DOM_VK_XF86XK_TIME", + "DOM_VK_XF86XK_TOOLS", + "DOM_VK_XF86XK_TOP_MENU", + "DOM_VK_XF86XK_TO_DO_LIST", + "DOM_VK_XF86XK_TRAVEL", + "DOM_VK_XF86XK_USER1KB", + "DOM_VK_XF86XK_USER2KB", + "DOM_VK_XF86XK_USER_PB", + "DOM_VK_XF86XK_UWB", + "DOM_VK_XF86XK_VENDOR_HOME", + "DOM_VK_XF86XK_VIDEO", + "DOM_VK_XF86XK_VIEW", + "DOM_VK_XF86XK_WAKE_UP", + "DOM_VK_XF86XK_WEB_CAM", + "DOM_VK_XF86XK_WHEEL_BUTTON", + "DOM_VK_XF86XK_WLAN", + "DOM_VK_XF86XK_WORD", + "DOM_VK_XF86XK_WWW", + "DOM_VK_XF86XK_XFER", + "DOM_VK_XF86XK_YELLOW", + "DOM_VK_XF86XK_ZOOM_IN", + "DOM_VK_XF86XK_ZOOM_OUT", + "DOM_VK_Y", + "DOM_VK_Z", + "DOM_VK_ZOOM", + "DONE", + "DONT_CARE", + "DOWNLOADING", + "DRAGDROP", + "DRAW_BUFFER0", + "DRAW_BUFFER1", + "DRAW_BUFFER10", + "DRAW_BUFFER11", + "DRAW_BUFFER12", + "DRAW_BUFFER13", + "DRAW_BUFFER14", + "DRAW_BUFFER15", + "DRAW_BUFFER2", + "DRAW_BUFFER3", + "DRAW_BUFFER4", + "DRAW_BUFFER5", + "DRAW_BUFFER6", + "DRAW_BUFFER7", + "DRAW_BUFFER8", + "DRAW_BUFFER9", + "DRAW_FRAMEBUFFER", + "DRAW_FRAMEBUFFER_BINDING", + "DST_ALPHA", + "DST_COLOR", + "DYNAMIC_COPY", + "DYNAMIC_DRAW", + "DYNAMIC_READ", + "DataChannel", + "DataTransfer", + "DataTransferItem", + "DataTransferItemList", + "DataView", + "Date", + "DateTimeFormat", + "DecompressionStream", + "DelayNode", + "DeprecationReportBody", + "DesktopNotification", + "DesktopNotificationCenter", + "DeviceLightEvent", + "DeviceMotionEvent", + "DeviceMotionEventAcceleration", + "DeviceMotionEventRotationRate", + "DeviceOrientationEvent", + "DeviceProximityEvent", + "DeviceStorage", + "DeviceStorageChangeEvent", + "Directory", + "DisplayNames", + "Document", + "DocumentFragment", + "DocumentTimeline", + "DocumentType", + "DragEvent", + "DynamicsCompressorNode", + "E", + "ELEMENT_ARRAY_BUFFER", + "ELEMENT_ARRAY_BUFFER_BINDING", + "ELEMENT_NODE", + "EMPTY", + "ENCODING_ERR", + "ENDED", + "END_TO_END", + "END_TO_START", + "ENTITY_NODE", + "ENTITY_REFERENCE_NODE", + "EPSILON", + "EQUAL", + "EQUALPOWER", + "ERROR", + "EXPONENTIAL_DISTANCE", + "Element", + "ElementInternals", + "ElementQuery", + "EnterPictureInPictureEvent", + "Entity", + "EntityReference", + "Error", + "ErrorEvent", + "EvalError", + "Event", + "EventException", + "EventSource", + "EventTarget", + "External", + "FASTEST", + "FIDOSDK", + "FILTER_ACCEPT", + "FILTER_INTERRUPT", + "FILTER_REJECT", + "FILTER_SKIP", + "FINISHED_STATE", + "FIRST_ORDERED_NODE_TYPE", + "FLOAT", + "FLOAT_32_UNSIGNED_INT_24_8_REV", + "FLOAT_MAT2", + "FLOAT_MAT2x3", + "FLOAT_MAT2x4", + "FLOAT_MAT3", + "FLOAT_MAT3x2", + "FLOAT_MAT3x4", + "FLOAT_MAT4", + "FLOAT_MAT4x2", + "FLOAT_MAT4x3", + "FLOAT_VEC2", + "FLOAT_VEC3", + "FLOAT_VEC4", + "FOCUS", + "FONT_FACE_RULE", + "FONT_FEATURE_VALUES_RULE", + "FRAGMENT_SHADER", + "FRAGMENT_SHADER_DERIVATIVE_HINT", + "FRAGMENT_SHADER_DERIVATIVE_HINT_OES", + "FRAMEBUFFER", + "FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE", + "FRAMEBUFFER_ATTACHMENT_BLUE_SIZE", + "FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING", + "FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE", + "FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE", + "FRAMEBUFFER_ATTACHMENT_GREEN_SIZE", + "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME", + "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE", + "FRAMEBUFFER_ATTACHMENT_RED_SIZE", + "FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL", + "FRAMEBUFFER_BINDING", + "FRAMEBUFFER_COMPLETE", + "FRAMEBUFFER_DEFAULT", + "FRAMEBUFFER_INCOMPLETE_ATTACHMENT", + "FRAMEBUFFER_INCOMPLETE_DIMENSIONS", + "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", + "FRAMEBUFFER_INCOMPLETE_MULTISAMPLE", + "FRAMEBUFFER_UNSUPPORTED", + "FRONT", + "FRONT_AND_BACK", + "FRONT_FACE", + "FUNC_ADD", + "FUNC_REVERSE_SUBTRACT", + "FUNC_SUBTRACT", + "FeaturePolicy", + "FeaturePolicyViolationReportBody", + "FederatedCredential", + "Feed", + "FeedEntry", + "File", + "FileError", + "FileList", + "FileReader", + "FileSystem", + "FileSystemDirectoryEntry", + "FileSystemDirectoryReader", + "FileSystemEntry", + "FileSystemFileEntry", + "FinalizationRegistry", + "FindInPage", + "Float32Array", + "Float64Array", + "FocusEvent", + "FontFace", + "FontFaceSet", + "FontFaceSetLoadEvent", + "FormData", + "FormDataEvent", + "FragmentDirective", + "Function", + "GENERATE_MIPMAP_HINT", + "GEQUAL", + "GREATER", + "GREEN_BITS", + "GainNode", + "Gamepad", + "GamepadAxisMoveEvent", + "GamepadButton", + "GamepadButtonEvent", + "GamepadEvent", + "GamepadHapticActuator", + "GamepadPose", + "Geolocation", + "GeolocationCoordinates", + "GeolocationPosition", + "GeolocationPositionError", + "GestureEvent", + "Global", + "Gyroscope", + "HALF_FLOAT", + "HAVE_CURRENT_DATA", + "HAVE_ENOUGH_DATA", + "HAVE_FUTURE_DATA", + "HAVE_METADATA", + "HAVE_NOTHING", + "HEADERS_RECEIVED", + "HIDDEN", + "HIERARCHY_REQUEST_ERR", + "HIGHPASS", + "HIGHSHELF", + "HIGH_FLOAT", + "HIGH_INT", + "HORIZONTAL", + "HORIZONTAL_AXIS", + "HRTF", + "HTMLAllCollection", + "HTMLAnchorElement", + "HTMLAppletElement", + "HTMLAreaElement", + "HTMLAudioElement", + "HTMLBRElement", + "HTMLBaseElement", + "HTMLBaseFontElement", + "HTMLBlockquoteElement", + "HTMLBodyElement", + "HTMLButtonElement", + "HTMLCanvasElement", + "HTMLCollection", + "HTMLCommandElement", + "HTMLContentElement", + "HTMLDListElement", + "HTMLDataElement", + "HTMLDataListElement", + "HTMLDetailsElement", + "HTMLDialogElement", + "HTMLDirectoryElement", + "HTMLDivElement", + "HTMLDocument", + "HTMLElement", + "HTMLEmbedElement", + "HTMLFieldSetElement", + "HTMLFontElement", + "HTMLFormControlsCollection", + "HTMLFormElement", + "HTMLFrameElement", + "HTMLFrameSetElement", + "HTMLHRElement", + "HTMLHeadElement", + "HTMLHeadingElement", + "HTMLHtmlElement", + "HTMLIFrameElement", + "HTMLImageElement", + "HTMLInputElement", + "HTMLIsIndexElement", + "HTMLKeygenElement", + "HTMLLIElement", + "HTMLLabelElement", + "HTMLLegendElement", + "HTMLLinkElement", + "HTMLMapElement", + "HTMLMarqueeElement", + "HTMLMediaElement", + "HTMLMenuElement", + "HTMLMenuItemElement", + "HTMLMetaElement", + "HTMLMeterElement", + "HTMLModElement", + "HTMLOListElement", + "HTMLObjectElement", + "HTMLOptGroupElement", + "HTMLOptionElement", + "HTMLOptionsCollection", + "HTMLOutputElement", + "HTMLParagraphElement", + "HTMLParamElement", + "HTMLPictureElement", + "HTMLPreElement", + "HTMLProgressElement", + "HTMLPropertiesCollection", + "HTMLQuoteElement", + "HTMLScriptElement", + "HTMLSelectElement", + "HTMLShadowElement", + "HTMLSlotElement", + "HTMLSourceElement", + "HTMLSpanElement", + "HTMLStyleElement", + "HTMLTableCaptionElement", + "HTMLTableCellElement", + "HTMLTableColElement", + "HTMLTableElement", + "HTMLTableRowElement", + "HTMLTableSectionElement", + "HTMLTemplateElement", + "HTMLTextAreaElement", + "HTMLTimeElement", + "HTMLTitleElement", + "HTMLTrackElement", + "HTMLUListElement", + "HTMLUnknownElement", + "HTMLVideoElement", + "HashChangeEvent", + "Headers", + "History", + "Hz", + "ICE_CHECKING", + "ICE_CLOSED", + "ICE_COMPLETED", + "ICE_CONNECTED", + "ICE_FAILED", + "ICE_GATHERING", + "ICE_WAITING", + "IDBCursor", + "IDBCursorWithValue", + "IDBDatabase", + "IDBDatabaseException", + "IDBFactory", + "IDBFileHandle", + "IDBFileRequest", + "IDBIndex", + "IDBKeyRange", + "IDBMutableFile", + "IDBObjectStore", + "IDBOpenDBRequest", + "IDBRequest", + "IDBTransaction", + "IDBVersionChangeEvent", + "IDLE", + "IIRFilterNode", + "IMPLEMENTATION_COLOR_READ_FORMAT", + "IMPLEMENTATION_COLOR_READ_TYPE", + "IMPORT_RULE", + "INCR", + "INCR_WRAP", + "INDEX_SIZE_ERR", + "INT", + "INTERLEAVED_ATTRIBS", + "INT_2_10_10_10_REV", + "INT_SAMPLER_2D", + "INT_SAMPLER_2D_ARRAY", + "INT_SAMPLER_3D", + "INT_SAMPLER_CUBE", + "INT_VEC2", + "INT_VEC3", + "INT_VEC4", + "INUSE_ATTRIBUTE_ERR", + "INVALID_ACCESS_ERR", + "INVALID_CHARACTER_ERR", + "INVALID_ENUM", + "INVALID_EXPRESSION_ERR", + "INVALID_FRAMEBUFFER_OPERATION", + "INVALID_INDEX", + "INVALID_MODIFICATION_ERR", + "INVALID_NODE_TYPE_ERR", + "INVALID_OPERATION", + "INVALID_STATE_ERR", + "INVALID_VALUE", + "INVERSE_DISTANCE", + "INVERT", + "IceCandidate", + "IdleDeadline", + "Image", + "ImageBitmap", + "ImageBitmapRenderingContext", + "ImageCapture", + "ImageData", + "Infinity", + "InputDeviceCapabilities", + "InputDeviceInfo", + "InputEvent", + "InputMethodContext", + "InstallTrigger", + "InstallTriggerImpl", + "Instance", + "Int16Array", + "Int32Array", + "Int8Array", + "Intent", + "InternalError", + "IntersectionObserver", + "IntersectionObserverEntry", + "Intl", + "IsSearchProviderInstalled", + "Iterator", + "JSON", + "KEEP", + "KEYDOWN", + "KEYFRAMES_RULE", + "KEYFRAME_RULE", + "KEYPRESS", + "KEYUP", + "KeyEvent", + "Keyboard", + "KeyboardEvent", + "KeyboardLayoutMap", + "KeyframeEffect", + "LENGTHADJUST_SPACING", + "LENGTHADJUST_SPACINGANDGLYPHS", + "LENGTHADJUST_UNKNOWN", + "LEQUAL", + "LESS", + "LINEAR", + "LINEAR_DISTANCE", + "LINEAR_MIPMAP_LINEAR", + "LINEAR_MIPMAP_NEAREST", + "LINES", + "LINE_LOOP", + "LINE_STRIP", + "LINE_WIDTH", + "LINK_STATUS", + "LIVE", + "LN10", + "LN2", + "LOADED", + "LOADING", + "LOG10E", + "LOG2E", + "LOWPASS", + "LOWSHELF", + "LOW_FLOAT", + "LOW_INT", + "LSException", + "LSParserFilter", + "LUMINANCE", + "LUMINANCE_ALPHA", + "LargestContentfulPaint", + "LayoutShift", + "LayoutShiftAttribution", + "LinearAccelerationSensor", + "LinkError", + "ListFormat", + "LocalMediaStream", + "Locale", + "Location", + "Lock", + "LockManager", + "MAX", + "MAX_3D_TEXTURE_SIZE", + "MAX_ARRAY_TEXTURE_LAYERS", + "MAX_CLIENT_WAIT_TIMEOUT_WEBGL", + "MAX_COLOR_ATTACHMENTS", + "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS", + "MAX_COMBINED_TEXTURE_IMAGE_UNITS", + "MAX_COMBINED_UNIFORM_BLOCKS", + "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS", + "MAX_CUBE_MAP_TEXTURE_SIZE", + "MAX_DRAW_BUFFERS", + "MAX_ELEMENTS_INDICES", + "MAX_ELEMENTS_VERTICES", + "MAX_ELEMENT_INDEX", + "MAX_FRAGMENT_INPUT_COMPONENTS", + "MAX_FRAGMENT_UNIFORM_BLOCKS", + "MAX_FRAGMENT_UNIFORM_COMPONENTS", + "MAX_FRAGMENT_UNIFORM_VECTORS", + "MAX_PROGRAM_TEXEL_OFFSET", + "MAX_RENDERBUFFER_SIZE", + "MAX_SAFE_INTEGER", + "MAX_SAMPLES", + "MAX_SERVER_WAIT_TIMEOUT", + "MAX_TEXTURE_IMAGE_UNITS", + "MAX_TEXTURE_LOD_BIAS", + "MAX_TEXTURE_MAX_ANISOTROPY_EXT", + "MAX_TEXTURE_SIZE", + "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS", + "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS", + "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS", + "MAX_UNIFORM_BLOCK_SIZE", + "MAX_UNIFORM_BUFFER_BINDINGS", + "MAX_VALUE", + "MAX_VARYING_COMPONENTS", + "MAX_VARYING_VECTORS", + "MAX_VERTEX_ATTRIBS", + "MAX_VERTEX_OUTPUT_COMPONENTS", + "MAX_VERTEX_TEXTURE_IMAGE_UNITS", + "MAX_VERTEX_UNIFORM_BLOCKS", + "MAX_VERTEX_UNIFORM_COMPONENTS", + "MAX_VERTEX_UNIFORM_VECTORS", + "MAX_VIEWPORT_DIMS", + "MEDIA_ERR_ABORTED", + "MEDIA_ERR_DECODE", + "MEDIA_ERR_ENCRYPTED", + "MEDIA_ERR_NETWORK", + "MEDIA_ERR_SRC_NOT_SUPPORTED", + "MEDIA_KEYERR_CLIENT", + "MEDIA_KEYERR_DOMAIN", + "MEDIA_KEYERR_HARDWARECHANGE", + "MEDIA_KEYERR_OUTPUT", + "MEDIA_KEYERR_SERVICE", + "MEDIA_KEYERR_UNKNOWN", + "MEDIA_RULE", + "MEDIUM_FLOAT", + "MEDIUM_INT", + "META_MASK", + "MIDIAccess", + "MIDIConnectionEvent", + "MIDIInput", + "MIDIInputMap", + "MIDIMessageEvent", + "MIDIOutput", + "MIDIOutputMap", + "MIDIPort", + "MIN", + "MIN_PROGRAM_TEXEL_OFFSET", + "MIN_SAFE_INTEGER", + "MIN_VALUE", + "MIRRORED_REPEAT", + "MODE_ASYNCHRONOUS", + "MODE_SYNCHRONOUS", + "MODIFICATION", + "MOUSEDOWN", + "MOUSEDRAG", + "MOUSEMOVE", + "MOUSEOUT", + "MOUSEOVER", + "MOUSEUP", + "MOZ_KEYFRAMES_RULE", + "MOZ_KEYFRAME_RULE", + "MOZ_SOURCE_CURSOR", + "MOZ_SOURCE_ERASER", + "MOZ_SOURCE_KEYBOARD", + "MOZ_SOURCE_MOUSE", + "MOZ_SOURCE_PEN", + "MOZ_SOURCE_TOUCH", + "MOZ_SOURCE_UNKNOWN", + "MSGESTURE_FLAG_BEGIN", + "MSGESTURE_FLAG_CANCEL", + "MSGESTURE_FLAG_END", + "MSGESTURE_FLAG_INERTIA", + "MSGESTURE_FLAG_NONE", + "MSPOINTER_TYPE_MOUSE", + "MSPOINTER_TYPE_PEN", + "MSPOINTER_TYPE_TOUCH", + "MS_ASYNC_CALLBACK_STATUS_ASSIGN_DELEGATE", + "MS_ASYNC_CALLBACK_STATUS_CANCEL", + "MS_ASYNC_CALLBACK_STATUS_CHOOSEANY", + "MS_ASYNC_CALLBACK_STATUS_ERROR", + "MS_ASYNC_CALLBACK_STATUS_JOIN", + "MS_ASYNC_OP_STATUS_CANCELED", + "MS_ASYNC_OP_STATUS_ERROR", + "MS_ASYNC_OP_STATUS_SUCCESS", + "MS_MANIPULATION_STATE_ACTIVE", + "MS_MANIPULATION_STATE_CANCELLED", + "MS_MANIPULATION_STATE_COMMITTED", + "MS_MANIPULATION_STATE_DRAGGING", + "MS_MANIPULATION_STATE_INERTIA", + "MS_MANIPULATION_STATE_PRESELECT", + "MS_MANIPULATION_STATE_SELECTING", + "MS_MANIPULATION_STATE_STOPPED", + "MS_MEDIA_ERR_ENCRYPTED", + "MS_MEDIA_KEYERR_CLIENT", + "MS_MEDIA_KEYERR_DOMAIN", + "MS_MEDIA_KEYERR_HARDWARECHANGE", + "MS_MEDIA_KEYERR_OUTPUT", + "MS_MEDIA_KEYERR_SERVICE", + "MS_MEDIA_KEYERR_UNKNOWN", + "Map", + "Math", + "MathMLElement", + "MediaCapabilities", + "MediaCapabilitiesInfo", + "MediaController", + "MediaDeviceInfo", + "MediaDevices", + "MediaElementAudioSourceNode", + "MediaEncryptedEvent", + "MediaError", + "MediaKeyError", + "MediaKeyEvent", + "MediaKeyMessageEvent", + "MediaKeyNeededEvent", + "MediaKeySession", + "MediaKeyStatusMap", + "MediaKeySystemAccess", + "MediaKeys", + "MediaList", + "MediaMetadata", + "MediaQueryList", + "MediaQueryListEvent", + "MediaRecorder", + "MediaRecorderErrorEvent", + "MediaSession", + "MediaSettingsRange", + "MediaSource", + "MediaStream", + "MediaStreamAudioDestinationNode", + "MediaStreamAudioSourceNode", + "MediaStreamEvent", + "MediaStreamTrack", + "MediaStreamTrackAudioSourceNode", + "MediaStreamTrackEvent", + "Memory", + "MessageChannel", + "MessageEvent", + "MessagePort", + "Methods", + "MimeType", + "MimeTypeArray", + "Module", + "MouseEvent", + "MouseScrollEvent", + "MozAnimation", + "MozAnimationDelay", + "MozAnimationDirection", + "MozAnimationDuration", + "MozAnimationFillMode", + "MozAnimationIterationCount", + "MozAnimationName", + "MozAnimationPlayState", + "MozAnimationTimingFunction", + "MozAppearance", + "MozBackfaceVisibility", + "MozBinding", + "MozBorderBottomColors", + "MozBorderEnd", + "MozBorderEndColor", + "MozBorderEndStyle", + "MozBorderEndWidth", + "MozBorderImage", + "MozBorderLeftColors", + "MozBorderRightColors", + "MozBorderStart", + "MozBorderStartColor", + "MozBorderStartStyle", + "MozBorderStartWidth", + "MozBorderTopColors", + "MozBoxAlign", + "MozBoxDirection", + "MozBoxFlex", + "MozBoxOrdinalGroup", + "MozBoxOrient", + "MozBoxPack", + "MozBoxSizing", + "MozCSSKeyframeRule", + "MozCSSKeyframesRule", + "MozColumnCount", + "MozColumnFill", + "MozColumnGap", + "MozColumnRule", + "MozColumnRuleColor", + "MozColumnRuleStyle", + "MozColumnRuleWidth", + "MozColumnWidth", + "MozColumns", + "MozContactChangeEvent", + "MozFloatEdge", + "MozFontFeatureSettings", + "MozFontLanguageOverride", + "MozForceBrokenImageIcon", + "MozHyphens", + "MozImageRegion", + "MozMarginEnd", + "MozMarginStart", + "MozMmsEvent", + "MozMmsMessage", + "MozMobileMessageThread", + "MozOSXFontSmoothing", + "MozOrient", + "MozOsxFontSmoothing", + "MozOutlineRadius", + "MozOutlineRadiusBottomleft", + "MozOutlineRadiusBottomright", + "MozOutlineRadiusTopleft", + "MozOutlineRadiusTopright", + "MozPaddingEnd", + "MozPaddingStart", + "MozPerspective", + "MozPerspectiveOrigin", + "MozPowerManager", + "MozSettingsEvent", + "MozSmsEvent", + "MozSmsMessage", + "MozStackSizing", + "MozTabSize", + "MozTextAlignLast", + "MozTextDecorationColor", + "MozTextDecorationLine", + "MozTextDecorationStyle", + "MozTextSizeAdjust", + "MozTransform", + "MozTransformOrigin", + "MozTransformStyle", + "MozTransition", + "MozTransitionDelay", + "MozTransitionDuration", + "MozTransitionProperty", + "MozTransitionTimingFunction", + "MozUserFocus", + "MozUserInput", + "MozUserModify", + "MozUserSelect", + "MozWindowDragging", + "MozWindowShadow", + "MutationEvent", + "MutationObserver", + "MutationRecord", + "NAMESPACE_ERR", + "NAMESPACE_RULE", + "NEAREST", + "NEAREST_MIPMAP_LINEAR", + "NEAREST_MIPMAP_NEAREST", + "NEGATIVE_INFINITY", + "NETWORK_EMPTY", + "NETWORK_ERR", + "NETWORK_IDLE", + "NETWORK_LOADED", + "NETWORK_LOADING", + "NETWORK_NO_SOURCE", + "NEVER", + "NEW", + "NEXT", + "NEXT_NO_DUPLICATE", + "NICEST", + "NODE_AFTER", + "NODE_BEFORE", + "NODE_BEFORE_AND_AFTER", + "NODE_INSIDE", + "NONE", + "NON_TRANSIENT_ERR", + "NOTATION_NODE", + "NOTCH", + "NOTEQUAL", + "NOT_ALLOWED_ERR", + "NOT_FOUND_ERR", + "NOT_READABLE_ERR", + "NOT_SUPPORTED_ERR", + "NO_DATA_ALLOWED_ERR", + "NO_ERR", + "NO_ERROR", + "NO_MODIFICATION_ALLOWED_ERR", + "NUMBER_TYPE", + "NUM_COMPRESSED_TEXTURE_FORMATS", + "NaN", + "NamedNodeMap", + "NavigationPreloadManager", + "Navigator", + "NearbyLinks", + "NetworkInformation", + "Node", + "NodeFilter", + "NodeIterator", + "NodeList", + "Notation", + "Notification", + "NotifyPaintEvent", + "Number", + "NumberFormat", + "OBJECT_TYPE", + "OBSOLETE", + "OK", + "ONE", + "ONE_MINUS_CONSTANT_ALPHA", + "ONE_MINUS_CONSTANT_COLOR", + "ONE_MINUS_DST_ALPHA", + "ONE_MINUS_DST_COLOR", + "ONE_MINUS_SRC_ALPHA", + "ONE_MINUS_SRC_COLOR", + "OPEN", + "OPENED", + "OPENING", + "ORDERED_NODE_ITERATOR_TYPE", + "ORDERED_NODE_SNAPSHOT_TYPE", + "OTHER_ERROR", + "OUT_OF_MEMORY", + "Object", + "OfflineAudioCompletionEvent", + "OfflineAudioContext", + "OfflineResourceList", + "OffscreenCanvas", + "OffscreenCanvasRenderingContext2D", + "Option", + "OrientationSensor", + "OscillatorNode", + "OverconstrainedError", + "OverflowEvent", + "PACK_ALIGNMENT", + "PACK_ROW_LENGTH", + "PACK_SKIP_PIXELS", + "PACK_SKIP_ROWS", + "PAGE_RULE", + "PARSE_ERR", + "PATHSEG_ARC_ABS", + "PATHSEG_ARC_REL", + "PATHSEG_CLOSEPATH", + "PATHSEG_CURVETO_CUBIC_ABS", + "PATHSEG_CURVETO_CUBIC_REL", + "PATHSEG_CURVETO_CUBIC_SMOOTH_ABS", + "PATHSEG_CURVETO_CUBIC_SMOOTH_REL", + "PATHSEG_CURVETO_QUADRATIC_ABS", + "PATHSEG_CURVETO_QUADRATIC_REL", + "PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS", + "PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL", + "PATHSEG_LINETO_ABS", + "PATHSEG_LINETO_HORIZONTAL_ABS", + "PATHSEG_LINETO_HORIZONTAL_REL", + "PATHSEG_LINETO_REL", + "PATHSEG_LINETO_VERTICAL_ABS", + "PATHSEG_LINETO_VERTICAL_REL", + "PATHSEG_MOVETO_ABS", + "PATHSEG_MOVETO_REL", + "PATHSEG_UNKNOWN", + "PATH_EXISTS_ERR", + "PEAKING", + "PERMISSION_DENIED", + "PERSISTENT", + "PI", + "PIXEL_PACK_BUFFER", + "PIXEL_PACK_BUFFER_BINDING", + "PIXEL_UNPACK_BUFFER", + "PIXEL_UNPACK_BUFFER_BINDING", + "PLAYING_STATE", + "POINTS", + "POLYGON_OFFSET_FACTOR", + "POLYGON_OFFSET_FILL", + "POLYGON_OFFSET_UNITS", + "POSITION_UNAVAILABLE", + "POSITIVE_INFINITY", + "PREV", + "PREV_NO_DUPLICATE", + "PROCESSING_INSTRUCTION_NODE", + "PageChangeEvent", + "PageTransitionEvent", + "PaintRequest", + "PaintRequestList", + "PannerNode", + "PasswordCredential", + "Path2D", + "PaymentAddress", + "PaymentInstruments", + "PaymentManager", + "PaymentMethodChangeEvent", + "PaymentRequest", + "PaymentRequestUpdateEvent", + "PaymentResponse", + "Performance", + "PerformanceElementTiming", + "PerformanceEntry", + "PerformanceEventTiming", + "PerformanceLongTaskTiming", + "PerformanceMark", + "PerformanceMeasure", + "PerformanceNavigation", + "PerformanceNavigationTiming", + "PerformanceObserver", + "PerformanceObserverEntryList", + "PerformancePaintTiming", + "PerformanceResourceTiming", + "PerformanceServerTiming", + "PerformanceTiming", + "PeriodicSyncManager", + "PeriodicWave", + "PermissionStatus", + "Permissions", + "PhotoCapabilities", + "PictureInPictureWindow", + "Plugin", + "PluginArray", + "PluralRules", + "PointerEvent", + "PopStateEvent", + "PopupBlockedEvent", + "Presentation", + "PresentationAvailability", + "PresentationConnection", + "PresentationConnectionAvailableEvent", + "PresentationConnectionCloseEvent", + "PresentationConnectionList", + "PresentationReceiver", + "PresentationRequest", + "ProcessingInstruction", + "ProgressEvent", + "Promise", + "PromiseRejectionEvent", + "PropertyNodeList", + "Proxy", + "PublicKeyCredential", + "PushManager", + "PushSubscription", + "PushSubscriptionOptions", + "Q", + "QUERY_RESULT", + "QUERY_RESULT_AVAILABLE", + "QUOTA_ERR", + "QUOTA_EXCEEDED_ERR", + "QueryInterface", + "R11F_G11F_B10F", + "R16F", + "R16I", + "R16UI", + "R32F", + "R32I", + "R32UI", + "R8", + "R8I", + "R8UI", + "R8_SNORM", + "RASTERIZER_DISCARD", + "READ_BUFFER", + "READ_FRAMEBUFFER", + "READ_FRAMEBUFFER_BINDING", + "READ_ONLY", + "READ_ONLY_ERR", + "READ_WRITE", + "RED", + "RED_BITS", + "RED_INTEGER", + "REMOVAL", + "RENDERBUFFER", + "RENDERBUFFER_ALPHA_SIZE", + "RENDERBUFFER_BINDING", + "RENDERBUFFER_BLUE_SIZE", + "RENDERBUFFER_DEPTH_SIZE", + "RENDERBUFFER_GREEN_SIZE", + "RENDERBUFFER_HEIGHT", + "RENDERBUFFER_INTERNAL_FORMAT", + "RENDERBUFFER_RED_SIZE", + "RENDERBUFFER_SAMPLES", + "RENDERBUFFER_STENCIL_SIZE", + "RENDERBUFFER_WIDTH", + "RENDERER", + "RENDERING_INTENT_ABSOLUTE_COLORIMETRIC", + "RENDERING_INTENT_AUTO", + "RENDERING_INTENT_PERCEPTUAL", + "RENDERING_INTENT_RELATIVE_COLORIMETRIC", + "RENDERING_INTENT_SATURATION", + "RENDERING_INTENT_UNKNOWN", + "REPEAT", + "REPLACE", + "RG", + "RG16F", + "RG16I", + "RG16UI", + "RG32F", + "RG32I", + "RG32UI", + "RG8", + "RG8I", + "RG8UI", + "RG8_SNORM", + "RGB", + "RGB10_A2", + "RGB10_A2UI", + "RGB16F", + "RGB16I", + "RGB16UI", + "RGB32F", + "RGB32I", + "RGB32UI", + "RGB565", + "RGB5_A1", + "RGB8", + "RGB8I", + "RGB8UI", + "RGB8_SNORM", + "RGB9_E5", + "RGBA", + "RGBA16F", + "RGBA16I", + "RGBA16UI", + "RGBA32F", + "RGBA32I", + "RGBA32UI", + "RGBA4", + "RGBA8", + "RGBA8I", + "RGBA8UI", + "RGBA8_SNORM", + "RGBA_INTEGER", + "RGBColor", + "RGB_INTEGER", + "RG_INTEGER", + "ROTATION_CLOCKWISE", + "ROTATION_COUNTERCLOCKWISE", + "RTCCertificate", + "RTCDTMFSender", + "RTCDTMFToneChangeEvent", + "RTCDataChannel", + "RTCDataChannelEvent", + "RTCDtlsTransport", + "RTCError", + "RTCErrorEvent", + "RTCIceCandidate", + "RTCIceTransport", + "RTCPeerConnection", + "RTCPeerConnectionIceErrorEvent", + "RTCPeerConnectionIceEvent", + "RTCRtpReceiver", + "RTCRtpSender", + "RTCRtpTransceiver", + "RTCSctpTransport", + "RTCSessionDescription", + "RTCStatsReport", + "RTCTrackEvent", + "RadioNodeList", + "Range", + "RangeError", + "RangeException", + "ReadableStream", + "ReadableStreamDefaultReader", + "RecordErrorEvent", + "Rect", + "ReferenceError", + "Reflect", + "RegExp", + "RelativeOrientationSensor", + "RelativeTimeFormat", + "RemotePlayback", + "Report", + "ReportBody", + "ReportingObserver", + "Request", + "ResizeObserver", + "ResizeObserverEntry", + "ResizeObserverSize", + "Response", + "RuntimeError", + "SAMPLER_2D", + "SAMPLER_2D_ARRAY", + "SAMPLER_2D_ARRAY_SHADOW", + "SAMPLER_2D_SHADOW", + "SAMPLER_3D", + "SAMPLER_BINDING", + "SAMPLER_CUBE", + "SAMPLER_CUBE_SHADOW", + "SAMPLES", + "SAMPLE_ALPHA_TO_COVERAGE", + "SAMPLE_BUFFERS", + "SAMPLE_COVERAGE", + "SAMPLE_COVERAGE_INVERT", + "SAMPLE_COVERAGE_VALUE", + "SAWTOOTH", + "SCHEDULED_STATE", + "SCISSOR_BOX", + "SCISSOR_TEST", + "SCROLL_PAGE_DOWN", + "SCROLL_PAGE_UP", + "SDP_ANSWER", + "SDP_OFFER", + "SDP_PRANSWER", + "SECURITY_ERR", + "SELECT", + "SEPARATE_ATTRIBS", + "SERIALIZE_ERR", + "SEVERITY_ERROR", + "SEVERITY_FATAL_ERROR", + "SEVERITY_WARNING", + "SHADER_COMPILER", + "SHADER_TYPE", + "SHADING_LANGUAGE_VERSION", + "SHIFT_MASK", + "SHORT", + "SHOWING", + "SHOW_ALL", + "SHOW_ATTRIBUTE", + "SHOW_CDATA_SECTION", + "SHOW_COMMENT", + "SHOW_DOCUMENT", + "SHOW_DOCUMENT_FRAGMENT", + "SHOW_DOCUMENT_TYPE", + "SHOW_ELEMENT", + "SHOW_ENTITY", + "SHOW_ENTITY_REFERENCE", + "SHOW_NOTATION", + "SHOW_PROCESSING_INSTRUCTION", + "SHOW_TEXT", + "SIGNALED", + "SIGNED_NORMALIZED", + "SINE", + "SOUNDFIELD", + "SQLException", + "SQRT1_2", + "SQRT2", + "SQUARE", + "SRC_ALPHA", + "SRC_ALPHA_SATURATE", + "SRC_COLOR", + "SRGB", + "SRGB8", + "SRGB8_ALPHA8", + "START_TO_END", + "START_TO_START", + "STATIC_COPY", + "STATIC_DRAW", + "STATIC_READ", + "STENCIL", + "STENCIL_ATTACHMENT", + "STENCIL_BACK_FAIL", + "STENCIL_BACK_FUNC", + "STENCIL_BACK_PASS_DEPTH_FAIL", + "STENCIL_BACK_PASS_DEPTH_PASS", + "STENCIL_BACK_REF", + "STENCIL_BACK_VALUE_MASK", + "STENCIL_BACK_WRITEMASK", + "STENCIL_BITS", + "STENCIL_BUFFER_BIT", + "STENCIL_CLEAR_VALUE", + "STENCIL_FAIL", + "STENCIL_FUNC", + "STENCIL_INDEX", + "STENCIL_INDEX8", + "STENCIL_PASS_DEPTH_FAIL", + "STENCIL_PASS_DEPTH_PASS", + "STENCIL_REF", + "STENCIL_TEST", + "STENCIL_VALUE_MASK", + "STENCIL_WRITEMASK", + "STREAM_COPY", + "STREAM_DRAW", + "STREAM_READ", + "STRING_TYPE", + "STYLE_RULE", + "SUBPIXEL_BITS", + "SUPPORTS_RULE", + "SVGAElement", + "SVGAltGlyphDefElement", + "SVGAltGlyphElement", + "SVGAltGlyphItemElement", + "SVGAngle", + "SVGAnimateColorElement", + "SVGAnimateElement", + "SVGAnimateMotionElement", + "SVGAnimateTransformElement", + "SVGAnimatedAngle", + "SVGAnimatedBoolean", + "SVGAnimatedEnumeration", + "SVGAnimatedInteger", + "SVGAnimatedLength", + "SVGAnimatedLengthList", + "SVGAnimatedNumber", + "SVGAnimatedNumberList", + "SVGAnimatedPreserveAspectRatio", + "SVGAnimatedRect", + "SVGAnimatedString", + "SVGAnimatedTransformList", + "SVGAnimationElement", + "SVGCircleElement", + "SVGClipPathElement", + "SVGColor", + "SVGComponentTransferFunctionElement", + "SVGCursorElement", + "SVGDefsElement", + "SVGDescElement", + "SVGDiscardElement", + "SVGDocument", + "SVGElement", + "SVGElementInstance", + "SVGElementInstanceList", + "SVGEllipseElement", + "SVGException", + "SVGFEBlendElement", + "SVGFEColorMatrixElement", + "SVGFEComponentTransferElement", + "SVGFECompositeElement", + "SVGFEConvolveMatrixElement", + "SVGFEDiffuseLightingElement", + "SVGFEDisplacementMapElement", + "SVGFEDistantLightElement", + "SVGFEDropShadowElement", + "SVGFEFloodElement", + "SVGFEFuncAElement", + "SVGFEFuncBElement", + "SVGFEFuncGElement", + "SVGFEFuncRElement", + "SVGFEGaussianBlurElement", + "SVGFEImageElement", + "SVGFEMergeElement", + "SVGFEMergeNodeElement", + "SVGFEMorphologyElement", + "SVGFEOffsetElement", + "SVGFEPointLightElement", + "SVGFESpecularLightingElement", + "SVGFESpotLightElement", + "SVGFETileElement", + "SVGFETurbulenceElement", + "SVGFilterElement", + "SVGFontElement", + "SVGFontFaceElement", + "SVGFontFaceFormatElement", + "SVGFontFaceNameElement", + "SVGFontFaceSrcElement", + "SVGFontFaceUriElement", + "SVGForeignObjectElement", + "SVGGElement", + "SVGGeometryElement", + "SVGGlyphElement", + "SVGGlyphRefElement", + "SVGGradientElement", + "SVGGraphicsElement", + "SVGHKernElement", + "SVGImageElement", + "SVGLength", + "SVGLengthList", + "SVGLineElement", + "SVGLinearGradientElement", + "SVGMPathElement", + "SVGMarkerElement", + "SVGMaskElement", + "SVGMatrix", + "SVGMetadataElement", + "SVGMissingGlyphElement", + "SVGNumber", + "SVGNumberList", + "SVGPaint", + "SVGPathElement", + "SVGPathSeg", + "SVGPathSegArcAbs", + "SVGPathSegArcRel", + "SVGPathSegClosePath", + "SVGPathSegCurvetoCubicAbs", + "SVGPathSegCurvetoCubicRel", + "SVGPathSegCurvetoCubicSmoothAbs", + "SVGPathSegCurvetoCubicSmoothRel", + "SVGPathSegCurvetoQuadraticAbs", + "SVGPathSegCurvetoQuadraticRel", + "SVGPathSegCurvetoQuadraticSmoothAbs", + "SVGPathSegCurvetoQuadraticSmoothRel", + "SVGPathSegLinetoAbs", + "SVGPathSegLinetoHorizontalAbs", + "SVGPathSegLinetoHorizontalRel", + "SVGPathSegLinetoRel", + "SVGPathSegLinetoVerticalAbs", + "SVGPathSegLinetoVerticalRel", + "SVGPathSegList", + "SVGPathSegMovetoAbs", + "SVGPathSegMovetoRel", + "SVGPatternElement", + "SVGPoint", + "SVGPointList", + "SVGPolygonElement", + "SVGPolylineElement", + "SVGPreserveAspectRatio", + "SVGRadialGradientElement", + "SVGRect", + "SVGRectElement", + "SVGRenderingIntent", + "SVGSVGElement", + "SVGScriptElement", + "SVGSetElement", + "SVGStopElement", + "SVGStringList", + "SVGStyleElement", + "SVGSwitchElement", + "SVGSymbolElement", + "SVGTRefElement", + "SVGTSpanElement", + "SVGTextContentElement", + "SVGTextElement", + "SVGTextPathElement", + "SVGTextPositioningElement", + "SVGTitleElement", + "SVGTransform", + "SVGTransformList", + "SVGUnitTypes", + "SVGUseElement", + "SVGVKernElement", + "SVGViewElement", + "SVGViewSpec", + "SVGZoomAndPan", + "SVGZoomEvent", + "SVG_ANGLETYPE_DEG", + "SVG_ANGLETYPE_GRAD", + "SVG_ANGLETYPE_RAD", + "SVG_ANGLETYPE_UNKNOWN", + "SVG_ANGLETYPE_UNSPECIFIED", + "SVG_CHANNEL_A", + "SVG_CHANNEL_B", + "SVG_CHANNEL_G", + "SVG_CHANNEL_R", + "SVG_CHANNEL_UNKNOWN", + "SVG_COLORTYPE_CURRENTCOLOR", + "SVG_COLORTYPE_RGBCOLOR", + "SVG_COLORTYPE_RGBCOLOR_ICCCOLOR", + "SVG_COLORTYPE_UNKNOWN", + "SVG_EDGEMODE_DUPLICATE", + "SVG_EDGEMODE_NONE", + "SVG_EDGEMODE_UNKNOWN", + "SVG_EDGEMODE_WRAP", + "SVG_FEBLEND_MODE_COLOR", + "SVG_FEBLEND_MODE_COLOR_BURN", + "SVG_FEBLEND_MODE_COLOR_DODGE", + "SVG_FEBLEND_MODE_DARKEN", + "SVG_FEBLEND_MODE_DIFFERENCE", + "SVG_FEBLEND_MODE_EXCLUSION", + "SVG_FEBLEND_MODE_HARD_LIGHT", + "SVG_FEBLEND_MODE_HUE", + "SVG_FEBLEND_MODE_LIGHTEN", + "SVG_FEBLEND_MODE_LUMINOSITY", + "SVG_FEBLEND_MODE_MULTIPLY", + "SVG_FEBLEND_MODE_NORMAL", + "SVG_FEBLEND_MODE_OVERLAY", + "SVG_FEBLEND_MODE_SATURATION", + "SVG_FEBLEND_MODE_SCREEN", + "SVG_FEBLEND_MODE_SOFT_LIGHT", + "SVG_FEBLEND_MODE_UNKNOWN", + "SVG_FECOLORMATRIX_TYPE_HUEROTATE", + "SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA", + "SVG_FECOLORMATRIX_TYPE_MATRIX", + "SVG_FECOLORMATRIX_TYPE_SATURATE", + "SVG_FECOLORMATRIX_TYPE_UNKNOWN", + "SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE", + "SVG_FECOMPONENTTRANSFER_TYPE_GAMMA", + "SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY", + "SVG_FECOMPONENTTRANSFER_TYPE_LINEAR", + "SVG_FECOMPONENTTRANSFER_TYPE_TABLE", + "SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN", + "SVG_FECOMPOSITE_OPERATOR_ARITHMETIC", + "SVG_FECOMPOSITE_OPERATOR_ATOP", + "SVG_FECOMPOSITE_OPERATOR_IN", + "SVG_FECOMPOSITE_OPERATOR_OUT", + "SVG_FECOMPOSITE_OPERATOR_OVER", + "SVG_FECOMPOSITE_OPERATOR_UNKNOWN", + "SVG_FECOMPOSITE_OPERATOR_XOR", + "SVG_INVALID_VALUE_ERR", + "SVG_LENGTHTYPE_CM", + "SVG_LENGTHTYPE_EMS", + "SVG_LENGTHTYPE_EXS", + "SVG_LENGTHTYPE_IN", + "SVG_LENGTHTYPE_MM", + "SVG_LENGTHTYPE_NUMBER", + "SVG_LENGTHTYPE_PC", + "SVG_LENGTHTYPE_PERCENTAGE", + "SVG_LENGTHTYPE_PT", + "SVG_LENGTHTYPE_PX", + "SVG_LENGTHTYPE_UNKNOWN", + "SVG_MARKERUNITS_STROKEWIDTH", + "SVG_MARKERUNITS_UNKNOWN", + "SVG_MARKERUNITS_USERSPACEONUSE", + "SVG_MARKER_ORIENT_ANGLE", + "SVG_MARKER_ORIENT_AUTO", + "SVG_MARKER_ORIENT_UNKNOWN", + "SVG_MASKTYPE_ALPHA", + "SVG_MASKTYPE_LUMINANCE", + "SVG_MATRIX_NOT_INVERTABLE", + "SVG_MEETORSLICE_MEET", + "SVG_MEETORSLICE_SLICE", + "SVG_MEETORSLICE_UNKNOWN", + "SVG_MORPHOLOGY_OPERATOR_DILATE", + "SVG_MORPHOLOGY_OPERATOR_ERODE", + "SVG_MORPHOLOGY_OPERATOR_UNKNOWN", + "SVG_PAINTTYPE_CURRENTCOLOR", + "SVG_PAINTTYPE_NONE", + "SVG_PAINTTYPE_RGBCOLOR", + "SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR", + "SVG_PAINTTYPE_UNKNOWN", + "SVG_PAINTTYPE_URI", + "SVG_PAINTTYPE_URI_CURRENTCOLOR", + "SVG_PAINTTYPE_URI_NONE", + "SVG_PAINTTYPE_URI_RGBCOLOR", + "SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR", + "SVG_PRESERVEASPECTRATIO_NONE", + "SVG_PRESERVEASPECTRATIO_UNKNOWN", + "SVG_PRESERVEASPECTRATIO_XMAXYMAX", + "SVG_PRESERVEASPECTRATIO_XMAXYMID", + "SVG_PRESERVEASPECTRATIO_XMAXYMIN", + "SVG_PRESERVEASPECTRATIO_XMIDYMAX", + "SVG_PRESERVEASPECTRATIO_XMIDYMID", + "SVG_PRESERVEASPECTRATIO_XMIDYMIN", + "SVG_PRESERVEASPECTRATIO_XMINYMAX", + "SVG_PRESERVEASPECTRATIO_XMINYMID", + "SVG_PRESERVEASPECTRATIO_XMINYMIN", + "SVG_SPREADMETHOD_PAD", + "SVG_SPREADMETHOD_REFLECT", + "SVG_SPREADMETHOD_REPEAT", + "SVG_SPREADMETHOD_UNKNOWN", + "SVG_STITCHTYPE_NOSTITCH", + "SVG_STITCHTYPE_STITCH", + "SVG_STITCHTYPE_UNKNOWN", + "SVG_TRANSFORM_MATRIX", + "SVG_TRANSFORM_ROTATE", + "SVG_TRANSFORM_SCALE", + "SVG_TRANSFORM_SKEWX", + "SVG_TRANSFORM_SKEWY", + "SVG_TRANSFORM_TRANSLATE", + "SVG_TRANSFORM_UNKNOWN", + "SVG_TURBULENCE_TYPE_FRACTALNOISE", + "SVG_TURBULENCE_TYPE_TURBULENCE", + "SVG_TURBULENCE_TYPE_UNKNOWN", + "SVG_UNIT_TYPE_OBJECTBOUNDINGBOX", + "SVG_UNIT_TYPE_UNKNOWN", + "SVG_UNIT_TYPE_USERSPACEONUSE", + "SVG_WRONG_TYPE_ERR", + "SVG_ZOOMANDPAN_DISABLE", + "SVG_ZOOMANDPAN_MAGNIFY", + "SVG_ZOOMANDPAN_UNKNOWN", + "SYNC_CONDITION", + "SYNC_FENCE", + "SYNC_FLAGS", + "SYNC_FLUSH_COMMANDS_BIT", + "SYNC_GPU_COMMANDS_COMPLETE", + "SYNC_STATUS", + "SYNTAX_ERR", + "SavedPages", + "Screen", + "ScreenOrientation", + "Script", + "ScriptProcessorNode", + "ScrollAreaEvent", + "SecurityPolicyViolationEvent", + "Selection", + "Sensor", + "SensorErrorEvent", + "ServiceWorker", + "ServiceWorkerContainer", + "ServiceWorkerRegistration", + "SessionDescription", + "Set", + "ShadowRoot", + "SharedArrayBuffer", + "SharedWorker", + "SimpleGestureEvent", + "SourceBuffer", + "SourceBufferList", + "SpeechSynthesis", + "SpeechSynthesisErrorEvent", + "SpeechSynthesisEvent", + "SpeechSynthesisUtterance", + "SpeechSynthesisVoice", + "StaticRange", + "StereoPannerNode", + "StopIteration", + "Storage", + "StorageEvent", + "StorageManager", + "String", + "StructType", + "StylePropertyMap", + "StylePropertyMapReadOnly", + "StyleSheet", + "StyleSheetList", + "SubmitEvent", + "SubtleCrypto", + "Symbol", + "SyncManager", + "SyntaxError", + "TEMPORARY", + "TEXTPATH_METHODTYPE_ALIGN", + "TEXTPATH_METHODTYPE_STRETCH", + "TEXTPATH_METHODTYPE_UNKNOWN", + "TEXTPATH_SPACINGTYPE_AUTO", + "TEXTPATH_SPACINGTYPE_EXACT", + "TEXTPATH_SPACINGTYPE_UNKNOWN", + "TEXTURE", + "TEXTURE0", + "TEXTURE1", + "TEXTURE10", + "TEXTURE11", + "TEXTURE12", + "TEXTURE13", + "TEXTURE14", + "TEXTURE15", + "TEXTURE16", + "TEXTURE17", + "TEXTURE18", + "TEXTURE19", + "TEXTURE2", + "TEXTURE20", + "TEXTURE21", + "TEXTURE22", + "TEXTURE23", + "TEXTURE24", + "TEXTURE25", + "TEXTURE26", + "TEXTURE27", + "TEXTURE28", + "TEXTURE29", + "TEXTURE3", + "TEXTURE30", + "TEXTURE31", + "TEXTURE4", + "TEXTURE5", + "TEXTURE6", + "TEXTURE7", + "TEXTURE8", + "TEXTURE9", + "TEXTURE_2D", + "TEXTURE_2D_ARRAY", + "TEXTURE_3D", + "TEXTURE_BASE_LEVEL", + "TEXTURE_BINDING_2D", + "TEXTURE_BINDING_2D_ARRAY", + "TEXTURE_BINDING_3D", + "TEXTURE_BINDING_CUBE_MAP", + "TEXTURE_COMPARE_FUNC", + "TEXTURE_COMPARE_MODE", + "TEXTURE_CUBE_MAP", + "TEXTURE_CUBE_MAP_NEGATIVE_X", + "TEXTURE_CUBE_MAP_NEGATIVE_Y", + "TEXTURE_CUBE_MAP_NEGATIVE_Z", + "TEXTURE_CUBE_MAP_POSITIVE_X", + "TEXTURE_CUBE_MAP_POSITIVE_Y", + "TEXTURE_CUBE_MAP_POSITIVE_Z", + "TEXTURE_IMMUTABLE_FORMAT", + "TEXTURE_IMMUTABLE_LEVELS", + "TEXTURE_MAG_FILTER", + "TEXTURE_MAX_ANISOTROPY_EXT", + "TEXTURE_MAX_LEVEL", + "TEXTURE_MAX_LOD", + "TEXTURE_MIN_FILTER", + "TEXTURE_MIN_LOD", + "TEXTURE_WRAP_R", + "TEXTURE_WRAP_S", + "TEXTURE_WRAP_T", + "TEXT_NODE", + "TIMEOUT", + "TIMEOUT_ERR", + "TIMEOUT_EXPIRED", + "TIMEOUT_IGNORED", + "TOO_LARGE_ERR", + "TRANSACTION_INACTIVE_ERR", + "TRANSFORM_FEEDBACK", + "TRANSFORM_FEEDBACK_ACTIVE", + "TRANSFORM_FEEDBACK_BINDING", + "TRANSFORM_FEEDBACK_BUFFER", + "TRANSFORM_FEEDBACK_BUFFER_BINDING", + "TRANSFORM_FEEDBACK_BUFFER_MODE", + "TRANSFORM_FEEDBACK_BUFFER_SIZE", + "TRANSFORM_FEEDBACK_BUFFER_START", + "TRANSFORM_FEEDBACK_PAUSED", + "TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN", + "TRANSFORM_FEEDBACK_VARYINGS", + "TRIANGLE", + "TRIANGLES", + "TRIANGLE_FAN", + "TRIANGLE_STRIP", + "TYPE_BACK_FORWARD", + "TYPE_ERR", + "TYPE_MISMATCH_ERR", + "TYPE_NAVIGATE", + "TYPE_RELOAD", + "TYPE_RESERVED", + "Table", + "TaskAttributionTiming", + "Text", + "TextDecoder", + "TextDecoderStream", + "TextEncoder", + "TextEncoderStream", + "TextEvent", + "TextMetrics", + "TextTrack", + "TextTrackCue", + "TextTrackCueList", + "TextTrackList", + "TimeEvent", + "TimeRanges", + "Touch", + "TouchEvent", + "TouchList", + "TrackEvent", + "TransformStream", + "TransitionEvent", + "TreeWalker", + "TrustedHTML", + "TrustedScript", + "TrustedScriptURL", + "TrustedTypePolicy", + "TrustedTypePolicyFactory", + "TypeError", + "TypedObject", + "U2F", + "UIEvent", + "UNCACHED", + "UNIFORM_ARRAY_STRIDE", + "UNIFORM_BLOCK_ACTIVE_UNIFORMS", + "UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES", + "UNIFORM_BLOCK_BINDING", + "UNIFORM_BLOCK_DATA_SIZE", + "UNIFORM_BLOCK_INDEX", + "UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER", + "UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER", + "UNIFORM_BUFFER", + "UNIFORM_BUFFER_BINDING", + "UNIFORM_BUFFER_OFFSET_ALIGNMENT", + "UNIFORM_BUFFER_SIZE", + "UNIFORM_BUFFER_START", + "UNIFORM_IS_ROW_MAJOR", + "UNIFORM_MATRIX_STRIDE", + "UNIFORM_OFFSET", + "UNIFORM_SIZE", + "UNIFORM_TYPE", + "UNKNOWN_ERR", + "UNKNOWN_RULE", + "UNMASKED_RENDERER_WEBGL", + "UNMASKED_VENDOR_WEBGL", + "UNORDERED_NODE_ITERATOR_TYPE", + "UNORDERED_NODE_SNAPSHOT_TYPE", + "UNPACK_ALIGNMENT", + "UNPACK_COLORSPACE_CONVERSION_WEBGL", + "UNPACK_FLIP_Y_WEBGL", + "UNPACK_IMAGE_HEIGHT", + "UNPACK_PREMULTIPLY_ALPHA_WEBGL", + "UNPACK_ROW_LENGTH", + "UNPACK_SKIP_IMAGES", + "UNPACK_SKIP_PIXELS", + "UNPACK_SKIP_ROWS", + "UNSCHEDULED_STATE", + "UNSENT", + "UNSIGNALED", + "UNSIGNED_BYTE", + "UNSIGNED_INT", + "UNSIGNED_INT_10F_11F_11F_REV", + "UNSIGNED_INT_24_8", + "UNSIGNED_INT_2_10_10_10_REV", + "UNSIGNED_INT_5_9_9_9_REV", + "UNSIGNED_INT_SAMPLER_2D", + "UNSIGNED_INT_SAMPLER_2D_ARRAY", + "UNSIGNED_INT_SAMPLER_3D", + "UNSIGNED_INT_SAMPLER_CUBE", + "UNSIGNED_INT_VEC2", + "UNSIGNED_INT_VEC3", + "UNSIGNED_INT_VEC4", + "UNSIGNED_NORMALIZED", + "UNSIGNED_SHORT", + "UNSIGNED_SHORT_4_4_4_4", + "UNSIGNED_SHORT_5_5_5_1", + "UNSIGNED_SHORT_5_6_5", + "UNSPECIFIED_EVENT_TYPE_ERR", + "UPDATEREADY", + "URIError", + "URL", + "URLSearchParams", + "URLUnencoded", + "URL_MISMATCH_ERR", + "USB", + "USBAlternateInterface", + "USBConfiguration", + "USBConnectionEvent", + "USBDevice", + "USBEndpoint", + "USBInTransferResult", + "USBInterface", + "USBIsochronousInTransferPacket", + "USBIsochronousInTransferResult", + "USBIsochronousOutTransferPacket", + "USBIsochronousOutTransferResult", + "USBOutTransferResult", + "UTC", + "Uint16Array", + "Uint32Array", + "Uint8Array", + "Uint8ClampedArray", + "UserActivation", + "UserMessageHandler", + "UserMessageHandlersNamespace", + "UserProximityEvent", + "VALIDATE_STATUS", + "VALIDATION_ERR", + "VARIABLES_RULE", + "VENDOR", + "VERSION", + "VERSION_CHANGE", + "VERSION_ERR", + "VERTEX_ARRAY_BINDING", + "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING", + "VERTEX_ATTRIB_ARRAY_DIVISOR", + "VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE", + "VERTEX_ATTRIB_ARRAY_ENABLED", + "VERTEX_ATTRIB_ARRAY_INTEGER", + "VERTEX_ATTRIB_ARRAY_NORMALIZED", + "VERTEX_ATTRIB_ARRAY_POINTER", + "VERTEX_ATTRIB_ARRAY_SIZE", + "VERTEX_ATTRIB_ARRAY_STRIDE", + "VERTEX_ATTRIB_ARRAY_TYPE", + "VERTEX_SHADER", + "VERTICAL", + "VERTICAL_AXIS", + "VER_ERR", + "VIEWPORT", + "VIEWPORT_RULE", + "VRDisplay", + "VRDisplayCapabilities", + "VRDisplayEvent", + "VREyeParameters", + "VRFieldOfView", + "VRFrameData", + "VRPose", + "VRStageParameters", + "VTTCue", + "VTTRegion", + "ValidityState", + "VideoPlaybackQuality", + "VideoStreamTrack", + "VisualViewport", + "WAIT_FAILED", + "WEBKIT_FILTER_RULE", + "WEBKIT_KEYFRAMES_RULE", + "WEBKIT_KEYFRAME_RULE", + "WEBKIT_REGION_RULE", + "WRONG_DOCUMENT_ERR", + "WakeLock", + "WakeLockSentinel", + "WasmAnyRef", + "WaveShaperNode", + "WeakMap", + "WeakRef", + "WeakSet", + "WebAssembly", + "WebGL2RenderingContext", + "WebGLActiveInfo", + "WebGLBuffer", + "WebGLContextEvent", + "WebGLFramebuffer", + "WebGLProgram", + "WebGLQuery", + "WebGLRenderbuffer", + "WebGLRenderingContext", + "WebGLSampler", + "WebGLShader", + "WebGLShaderPrecisionFormat", + "WebGLSync", + "WebGLTexture", + "WebGLTransformFeedback", + "WebGLUniformLocation", + "WebGLVertexArray", + "WebGLVertexArrayObject", + "WebKitAnimationEvent", + "WebKitBlobBuilder", + "WebKitCSSFilterRule", + "WebKitCSSFilterValue", + "WebKitCSSKeyframeRule", + "WebKitCSSKeyframesRule", + "WebKitCSSMatrix", + "WebKitCSSRegionRule", + "WebKitCSSTransformValue", + "WebKitDataCue", + "WebKitGamepad", + "WebKitMediaKeyError", + "WebKitMediaKeyMessageEvent", + "WebKitMediaKeySession", + "WebKitMediaKeys", + "WebKitMediaSource", + "WebKitMutationObserver", + "WebKitNamespace", + "WebKitPlaybackTargetAvailabilityEvent", + "WebKitPoint", + "WebKitShadowRoot", + "WebKitSourceBuffer", + "WebKitSourceBufferList", + "WebKitTransitionEvent", + "WebSocket", + "WebkitAlignContent", + "WebkitAlignItems", + "WebkitAlignSelf", + "WebkitAnimation", + "WebkitAnimationDelay", + "WebkitAnimationDirection", + "WebkitAnimationDuration", + "WebkitAnimationFillMode", + "WebkitAnimationIterationCount", + "WebkitAnimationName", + "WebkitAnimationPlayState", + "WebkitAnimationTimingFunction", + "WebkitAppearance", + "WebkitBackfaceVisibility", + "WebkitBackgroundClip", + "WebkitBackgroundOrigin", + "WebkitBackgroundSize", + "WebkitBorderBottomLeftRadius", + "WebkitBorderBottomRightRadius", + "WebkitBorderImage", + "WebkitBorderRadius", + "WebkitBorderTopLeftRadius", + "WebkitBorderTopRightRadius", + "WebkitBoxAlign", + "WebkitBoxDirection", + "WebkitBoxFlex", + "WebkitBoxOrdinalGroup", + "WebkitBoxOrient", + "WebkitBoxPack", + "WebkitBoxShadow", + "WebkitBoxSizing", + "WebkitFilter", + "WebkitFlex", + "WebkitFlexBasis", + "WebkitFlexDirection", + "WebkitFlexFlow", + "WebkitFlexGrow", + "WebkitFlexShrink", + "WebkitFlexWrap", + "WebkitJustifyContent", + "WebkitLineClamp", + "WebkitMask", + "WebkitMaskClip", + "WebkitMaskComposite", + "WebkitMaskImage", + "WebkitMaskOrigin", + "WebkitMaskPosition", + "WebkitMaskPositionX", + "WebkitMaskPositionY", + "WebkitMaskRepeat", + "WebkitMaskSize", + "WebkitOrder", + "WebkitPerspective", + "WebkitPerspectiveOrigin", + "WebkitTextFillColor", + "WebkitTextSizeAdjust", + "WebkitTextStroke", + "WebkitTextStrokeColor", + "WebkitTextStrokeWidth", + "WebkitTransform", + "WebkitTransformOrigin", + "WebkitTransformStyle", + "WebkitTransition", + "WebkitTransitionDelay", + "WebkitTransitionDuration", + "WebkitTransitionProperty", + "WebkitTransitionTimingFunction", + "WebkitUserSelect", + "WheelEvent", + "Window", + "Worker", + "Worklet", + "WritableStream", + "WritableStreamDefaultWriter", + "XMLDocument", + "XMLHttpRequest", + "XMLHttpRequestEventTarget", + "XMLHttpRequestException", + "XMLHttpRequestProgressEvent", + "XMLHttpRequestUpload", + "XMLSerializer", + "XMLStylesheetProcessingInstruction", + "XPathEvaluator", + "XPathException", + "XPathExpression", + "XPathNSResolver", + "XPathResult", + "XRBoundedReferenceSpace", + "XRDOMOverlayState", + "XRFrame", + "XRHitTestResult", + "XRHitTestSource", + "XRInputSource", + "XRInputSourceArray", + "XRInputSourceEvent", + "XRInputSourcesChangeEvent", + "XRLayer", + "XRPose", + "XRRay", + "XRReferenceSpace", + "XRReferenceSpaceEvent", + "XRRenderState", + "XRRigidTransform", + "XRSession", + "XRSessionEvent", + "XRSpace", + "XRSystem", + "XRTransientInputHitTestResult", + "XRTransientInputHitTestSource", + "XRView", + "XRViewerPose", + "XRViewport", + "XRWebGLLayer", + "XSLTProcessor", + "ZERO", + "_XD0M_", + "_YD0M_", + "__defineGetter__", + "__defineSetter__", + "__lookupGetter__", + "__lookupSetter__", + "__opera", + "__proto__", + "_browserjsran", + "a", + "aLink", + "abbr", + "abort", + "aborted", + "abs", + "absolute", + "acceleration", + "accelerationIncludingGravity", + "accelerator", + "accept", + "acceptCharset", + "acceptNode", + "accessKey", + "accessKeyLabel", + "accuracy", + "acos", + "acosh", + "action", + "actionURL", + "actions", + "activated", + "active", + "activeCues", + "activeElement", + "activeSourceBuffers", + "activeSourceCount", + "activeTexture", + "activeVRDisplays", + "actualBoundingBoxAscent", + "actualBoundingBoxDescent", + "actualBoundingBoxLeft", + "actualBoundingBoxRight", + "add", + "addAll", + "addBehavior", + "addCandidate", + "addColorStop", + "addCue", + "addElement", + "addEventListener", + "addFilter", + "addFromString", + "addFromUri", + "addIceCandidate", + "addImport", + "addListener", + "addModule", + "addNamed", + "addPageRule", + "addPath", + "addPointer", + "addRange", + "addRegion", + "addRule", + "addSearchEngine", + "addSourceBuffer", + "addStream", + "addTextTrack", + "addTrack", + "addTransceiver", + "addWakeLockListener", + "added", + "addedNodes", + "additionalName", + "additiveSymbols", + "addons", + "address", + "addressLine", + "adoptNode", + "adoptedStyleSheets", + "adr", + "advance", + "after", + "album", + "alert", + "algorithm", + "align", + "align-content", + "align-items", + "align-self", + "alignContent", + "alignItems", + "alignSelf", + "alignmentBaseline", + "alinkColor", + "all", + "allSettled", + "allow", + "allowFullscreen", + "allowPaymentRequest", + "allowedDirections", + "allowedFeatures", + "allowedToPlay", + "allowsFeature", + "alpha", + "alt", + "altGraphKey", + "altHtml", + "altKey", + "altLeft", + "alternate", + "alternateSetting", + "alternates", + "altitude", + "altitudeAccuracy", + "amplitude", + "ancestorOrigins", + "anchor", + "anchorNode", + "anchorOffset", + "anchors", + "and", + "angle", + "angularAcceleration", + "angularVelocity", + "animVal", + "animate", + "animatedInstanceRoot", + "animatedNormalizedPathSegList", + "animatedPathSegList", + "animatedPoints", + "animation", + "animation-delay", + "animation-direction", + "animation-duration", + "animation-fill-mode", + "animation-iteration-count", + "animation-name", + "animation-play-state", + "animation-timing-function", + "animationDelay", + "animationDirection", + "animationDuration", + "animationFillMode", + "animationIterationCount", + "animationName", + "animationPlayState", + "animationStartTime", + "animationTimingFunction", + "animationsPaused", + "anniversary", + "antialias", + "anticipatedRemoval", + "any", + "app", + "appCodeName", + "appMinorVersion", + "appName", + "appNotifications", + "appVersion", + "appearance", + "append", + "appendBuffer", + "appendChild", + "appendData", + "appendItem", + "appendMedium", + "appendNamed", + "appendRule", + "appendStream", + "appendWindowEnd", + "appendWindowStart", + "applets", + "applicationCache", + "applicationServerKey", + "apply", + "applyConstraints", + "applyElement", + "arc", + "arcTo", + "archive", + "areas", + "arguments", + "ariaAtomic", + "ariaAutoComplete", + "ariaBusy", + "ariaChecked", + "ariaColCount", + "ariaColIndex", + "ariaColSpan", + "ariaCurrent", + "ariaDescription", + "ariaDisabled", + "ariaExpanded", + "ariaHasPopup", + "ariaHidden", + "ariaKeyShortcuts", + "ariaLabel", + "ariaLevel", + "ariaLive", + "ariaModal", + "ariaMultiLine", + "ariaMultiSelectable", + "ariaOrientation", + "ariaPlaceholder", + "ariaPosInSet", + "ariaPressed", + "ariaReadOnly", + "ariaRelevant", + "ariaRequired", + "ariaRoleDescription", + "ariaRowCount", + "ariaRowIndex", + "ariaRowSpan", + "ariaSelected", + "ariaSetSize", + "ariaSort", + "ariaValueMax", + "ariaValueMin", + "ariaValueNow", + "ariaValueText", + "arrayBuffer", + "artist", + "artwork", + "as", + "asIntN", + "asUintN", + "asin", + "asinh", + "assert", + "assign", + "assignedElements", + "assignedNodes", + "assignedSlot", + "async", + "asyncIterator", + "atEnd", + "atan", + "atan2", + "atanh", + "atob", + "attachEvent", + "attachInternals", + "attachShader", + "attachShadow", + "attachments", + "attack", + "attestationObject", + "attrChange", + "attrName", + "attributeFilter", + "attributeName", + "attributeNamespace", + "attributeOldValue", + "attributeStyleMap", + "attributes", + "attribution", + "audioBitsPerSecond", + "audioTracks", + "audioWorklet", + "authenticatedSignedWrites", + "authenticatorData", + "autoIncrement", + "autobuffer", + "autocapitalize", + "autocomplete", + "autocorrect", + "autofocus", + "automationRate", + "autoplay", + "availHeight", + "availLeft", + "availTop", + "availWidth", + "availability", + "available", + "aversion", + "ax", + "axes", + "axis", + "ay", + "azimuth", + "b", + "back", + "backface-visibility", + "backfaceVisibility", + "background", + "background-attachment", + "background-blend-mode", + "background-clip", + "background-color", + "background-image", + "background-origin", + "background-position", + "background-position-x", + "background-position-y", + "background-repeat", + "background-size", + "backgroundAttachment", + "backgroundBlendMode", + "backgroundClip", + "backgroundColor", + "backgroundFetch", + "backgroundImage", + "backgroundOrigin", + "backgroundPosition", + "backgroundPositionX", + "backgroundPositionY", + "backgroundRepeat", + "backgroundSize", + "badInput", + "badge", + "balance", + "baseFrequencyX", + "baseFrequencyY", + "baseLatency", + "baseLayer", + "baseNode", + "baseOffset", + "baseURI", + "baseVal", + "baselineShift", + "battery", + "bday", + "before", + "beginElement", + "beginElementAt", + "beginPath", + "beginQuery", + "beginTransformFeedback", + "behavior", + "behaviorCookie", + "behaviorPart", + "behaviorUrns", + "beta", + "bezierCurveTo", + "bgColor", + "bgProperties", + "bias", + "big", + "bigint64", + "biguint64", + "binaryType", + "bind", + "bindAttribLocation", + "bindBuffer", + "bindBufferBase", + "bindBufferRange", + "bindFramebuffer", + "bindRenderbuffer", + "bindSampler", + "bindTexture", + "bindTransformFeedback", + "bindVertexArray", + "blendColor", + "blendEquation", + "blendEquationSeparate", + "blendFunc", + "blendFuncSeparate", + "blink", + "blitFramebuffer", + "blob", + "block-size", + "blockDirection", + "blockSize", + "blockedURI", + "blue", + "bluetooth", + "blur", + "body", + "bodyUsed", + "bold", + "bookmarks", + "booleanValue", + "border", + "border-block", + "border-block-color", + "border-block-end", + "border-block-end-color", + "border-block-end-style", + "border-block-end-width", + "border-block-start", + "border-block-start-color", + "border-block-start-style", + "border-block-start-width", + "border-block-style", + "border-block-width", + "border-bottom", + "border-bottom-color", + "border-bottom-left-radius", + "border-bottom-right-radius", + "border-bottom-style", + "border-bottom-width", + "border-collapse", + "border-color", + "border-end-end-radius", + "border-end-start-radius", + "border-image", + "border-image-outset", + "border-image-repeat", + "border-image-slice", + "border-image-source", + "border-image-width", + "border-inline", + "border-inline-color", + "border-inline-end", + "border-inline-end-color", + "border-inline-end-style", + "border-inline-end-width", + "border-inline-start", + "border-inline-start-color", + "border-inline-start-style", + "border-inline-start-width", + "border-inline-style", + "border-inline-width", + "border-left", + "border-left-color", + "border-left-style", + "border-left-width", + "border-radius", + "border-right", + "border-right-color", + "border-right-style", + "border-right-width", + "border-spacing", + "border-start-end-radius", + "border-start-start-radius", + "border-style", + "border-top", + "border-top-color", + "border-top-left-radius", + "border-top-right-radius", + "border-top-style", + "border-top-width", + "border-width", + "borderBlock", + "borderBlockColor", + "borderBlockEnd", + "borderBlockEndColor", + "borderBlockEndStyle", + "borderBlockEndWidth", + "borderBlockStart", + "borderBlockStartColor", + "borderBlockStartStyle", + "borderBlockStartWidth", + "borderBlockStyle", + "borderBlockWidth", + "borderBottom", + "borderBottomColor", + "borderBottomLeftRadius", + "borderBottomRightRadius", + "borderBottomStyle", + "borderBottomWidth", + "borderBoxSize", + "borderCollapse", + "borderColor", + "borderColorDark", + "borderColorLight", + "borderEndEndRadius", + "borderEndStartRadius", + "borderImage", + "borderImageOutset", + "borderImageRepeat", + "borderImageSlice", + "borderImageSource", + "borderImageWidth", + "borderInline", + "borderInlineColor", + "borderInlineEnd", + "borderInlineEndColor", + "borderInlineEndStyle", + "borderInlineEndWidth", + "borderInlineStart", + "borderInlineStartColor", + "borderInlineStartStyle", + "borderInlineStartWidth", + "borderInlineStyle", + "borderInlineWidth", + "borderLeft", + "borderLeftColor", + "borderLeftStyle", + "borderLeftWidth", + "borderRadius", + "borderRight", + "borderRightColor", + "borderRightStyle", + "borderRightWidth", + "borderSpacing", + "borderStartEndRadius", + "borderStartStartRadius", + "borderStyle", + "borderTop", + "borderTopColor", + "borderTopLeftRadius", + "borderTopRightRadius", + "borderTopStyle", + "borderTopWidth", + "borderWidth", + "bottom", + "bottomMargin", + "bound", + "boundElements", + "boundingClientRect", + "boundingHeight", + "boundingLeft", + "boundingTop", + "boundingWidth", + "bounds", + "boundsGeometry", + "box-decoration-break", + "box-shadow", + "box-sizing", + "boxDecorationBreak", + "boxShadow", + "boxSizing", + "break-after", + "break-before", + "break-inside", + "breakAfter", + "breakBefore", + "breakInside", + "broadcast", + "browserLanguage", + "btoa", + "bubbles", + "buffer", + "bufferData", + "bufferDepth", + "bufferSize", + "bufferSubData", + "buffered", + "bufferedAmount", + "bufferedAmountLowThreshold", + "buildID", + "buildNumber", + "button", + "buttonID", + "buttons", + "byteLength", + "byteOffset", + "bytesWritten", + "c", + "cache", + "caches", + "call", + "caller", + "canBeFormatted", + "canBeMounted", + "canBeShared", + "canHaveChildren", + "canHaveHTML", + "canInsertDTMF", + "canMakePayment", + "canPlayType", + "canPresent", + "canTrickleIceCandidates", + "cancel", + "cancelAndHoldAtTime", + "cancelAnimationFrame", + "cancelBubble", + "cancelIdleCallback", + "cancelScheduledValues", + "cancelVideoFrameCallback", + "cancelWatchAvailability", + "cancelable", + "candidate", + "canonicalUUID", + "canvas", + "capabilities", + "caption", + "caption-side", + "captionSide", + "capture", + "captureEvents", + "captureStackTrace", + "captureStream", + "caret-color", + "caretBidiLevel", + "caretColor", + "caretPositionFromPoint", + "caretRangeFromPoint", + "cast", + "catch", + "category", + "cbrt", + "cd", + "ceil", + "cellIndex", + "cellPadding", + "cellSpacing", + "cells", + "ch", + "chOff", + "chain", + "challenge", + "changeType", + "changedTouches", + "channel", + "channelCount", + "channelCountMode", + "channelInterpretation", + "char", + "charAt", + "charCode", + "charCodeAt", + "charIndex", + "charLength", + "characterData", + "characterDataOldValue", + "characterSet", + "characteristic", + "charging", + "chargingTime", + "charset", + "check", + "checkEnclosure", + "checkFramebufferStatus", + "checkIntersection", + "checkValidity", + "checked", + "childElementCount", + "childList", + "childNodes", + "children", + "chrome", + "ciphertext", + "cite", + "city", + "claimInterface", + "claimed", + "classList", + "className", + "classid", + "clear", + "clearAppBadge", + "clearAttributes", + "clearBufferfi", + "clearBufferfv", + "clearBufferiv", + "clearBufferuiv", + "clearColor", + "clearData", + "clearDepth", + "clearHalt", + "clearImmediate", + "clearInterval", + "clearLiveSeekableRange", + "clearMarks", + "clearMaxGCPauseAccumulator", + "clearMeasures", + "clearParameters", + "clearRect", + "clearResourceTimings", + "clearShadow", + "clearStencil", + "clearTimeout", + "clearWatch", + "click", + "clickCount", + "clientDataJSON", + "clientHeight", + "clientInformation", + "clientLeft", + "clientRect", + "clientRects", + "clientTop", + "clientWaitSync", + "clientWidth", + "clientX", + "clientY", + "clip", + "clip-path", + "clip-rule", + "clipBottom", + "clipLeft", + "clipPath", + "clipPathUnits", + "clipRight", + "clipRule", + "clipTop", + "clipboard", + "clipboardData", + "clone", + "cloneContents", + "cloneNode", + "cloneRange", + "close", + "closePath", + "closed", + "closest", + "clz", + "clz32", + "cm", + "cmp", + "code", + "codeBase", + "codePointAt", + "codeType", + "colSpan", + "collapse", + "collapseToEnd", + "collapseToStart", + "collapsed", + "collect", + "colno", + "color", + "color-adjust", + "color-interpolation", + "color-interpolation-filters", + "colorAdjust", + "colorDepth", + "colorInterpolation", + "colorInterpolationFilters", + "colorMask", + "colorType", + "cols", + "column-count", + "column-fill", + "column-gap", + "column-rule", + "column-rule-color", + "column-rule-style", + "column-rule-width", + "column-span", + "column-width", + "columnCount", + "columnFill", + "columnGap", + "columnNumber", + "columnRule", + "columnRuleColor", + "columnRuleStyle", + "columnRuleWidth", + "columnSpan", + "columnWidth", + "columns", + "command", + "commit", + "commitPreferences", + "commitStyles", + "commonAncestorContainer", + "compact", + "compareBoundaryPoints", + "compareDocumentPosition", + "compareEndPoints", + "compareExchange", + "compareNode", + "comparePoint", + "compatMode", + "compatible", + "compile", + "compileShader", + "compileStreaming", + "complete", + "component", + "componentFromPoint", + "composed", + "composedPath", + "composite", + "compositionEndOffset", + "compositionStartOffset", + "compressedTexImage2D", + "compressedTexImage3D", + "compressedTexSubImage2D", + "compressedTexSubImage3D", + "computedStyleMap", + "concat", + "conditionText", + "coneInnerAngle", + "coneOuterAngle", + "coneOuterGain", + "configuration", + "configurationName", + "configurationValue", + "configurations", + "confirm", + "confirmComposition", + "confirmSiteSpecificTrackingException", + "confirmWebWideTrackingException", + "connect", + "connectEnd", + "connectShark", + "connectStart", + "connected", + "connection", + "connectionList", + "connectionSpeed", + "connectionState", + "connections", + "console", + "consolidate", + "constraint", + "constrictionActive", + "construct", + "constructor", + "contactID", + "contain", + "containerId", + "containerName", + "containerSrc", + "containerType", + "contains", + "containsNode", + "content", + "contentBoxSize", + "contentDocument", + "contentEditable", + "contentHint", + "contentOverflow", + "contentRect", + "contentScriptType", + "contentStyleType", + "contentType", + "contentWindow", + "context", + "contextMenu", + "contextmenu", + "continue", + "continuePrimaryKey", + "continuous", + "control", + "controlTransferIn", + "controlTransferOut", + "controller", + "controls", + "controlsList", + "convertPointFromNode", + "convertQuadFromNode", + "convertRectFromNode", + "convertToBlob", + "convertToSpecifiedUnits", + "cookie", + "cookieEnabled", + "coords", + "copyBufferSubData", + "copyFromChannel", + "copyTexImage2D", + "copyTexSubImage2D", + "copyTexSubImage3D", + "copyToChannel", + "copyWithin", + "correspondingElement", + "correspondingUseElement", + "corruptedVideoFrames", + "cos", + "cosh", + "count", + "countReset", + "counter-increment", + "counter-reset", + "counter-set", + "counterIncrement", + "counterReset", + "counterSet", + "country", + "cpuClass", + "cpuSleepAllowed", + "create", + "createAnalyser", + "createAnswer", + "createAttribute", + "createAttributeNS", + "createBiquadFilter", + "createBuffer", + "createBufferSource", + "createCDATASection", + "createCSSStyleSheet", + "createCaption", + "createChannelMerger", + "createChannelSplitter", + "createComment", + "createConstantSource", + "createContextualFragment", + "createControlRange", + "createConvolver", + "createDTMFSender", + "createDataChannel", + "createDelay", + "createDelayNode", + "createDocument", + "createDocumentFragment", + "createDocumentType", + "createDynamicsCompressor", + "createElement", + "createElementNS", + "createEntityReference", + "createEvent", + "createEventObject", + "createExpression", + "createFramebuffer", + "createFunction", + "createGain", + "createGainNode", + "createHTML", + "createHTMLDocument", + "createIIRFilter", + "createImageBitmap", + "createImageData", + "createIndex", + "createJavaScriptNode", + "createLinearGradient", + "createMediaElementSource", + "createMediaKeys", + "createMediaStreamDestination", + "createMediaStreamSource", + "createMediaStreamTrackSource", + "createMutableFile", + "createNSResolver", + "createNodeIterator", + "createNotification", + "createObjectStore", + "createObjectURL", + "createOffer", + "createOscillator", + "createPanner", + "createPattern", + "createPeriodicWave", + "createPolicy", + "createPopup", + "createProcessingInstruction", + "createProgram", + "createQuery", + "createRadialGradient", + "createRange", + "createRangeCollection", + "createReader", + "createRenderbuffer", + "createSVGAngle", + "createSVGLength", + "createSVGMatrix", + "createSVGNumber", + "createSVGPathSegArcAbs", + "createSVGPathSegArcRel", + "createSVGPathSegClosePath", + "createSVGPathSegCurvetoCubicAbs", + "createSVGPathSegCurvetoCubicRel", + "createSVGPathSegCurvetoCubicSmoothAbs", + "createSVGPathSegCurvetoCubicSmoothRel", + "createSVGPathSegCurvetoQuadraticAbs", + "createSVGPathSegCurvetoQuadraticRel", + "createSVGPathSegCurvetoQuadraticSmoothAbs", + "createSVGPathSegCurvetoQuadraticSmoothRel", + "createSVGPathSegLinetoAbs", + "createSVGPathSegLinetoHorizontalAbs", + "createSVGPathSegLinetoHorizontalRel", + "createSVGPathSegLinetoRel", + "createSVGPathSegLinetoVerticalAbs", + "createSVGPathSegLinetoVerticalRel", + "createSVGPathSegMovetoAbs", + "createSVGPathSegMovetoRel", + "createSVGPoint", + "createSVGRect", + "createSVGTransform", + "createSVGTransformFromMatrix", + "createSampler", + "createScript", + "createScriptProcessor", + "createScriptURL", + "createSession", + "createShader", + "createShadowRoot", + "createStereoPanner", + "createStyleSheet", + "createTBody", + "createTFoot", + "createTHead", + "createTextNode", + "createTextRange", + "createTexture", + "createTouch", + "createTouchList", + "createTransformFeedback", + "createTreeWalker", + "createVertexArray", + "createWaveShaper", + "creationTime", + "credentials", + "crossOrigin", + "crossOriginIsolated", + "crypto", + "csi", + "csp", + "cssFloat", + "cssRules", + "cssText", + "cssValueType", + "ctrlKey", + "ctrlLeft", + "cues", + "cullFace", + "currentDirection", + "currentLocalDescription", + "currentNode", + "currentPage", + "currentRect", + "currentRemoteDescription", + "currentScale", + "currentScript", + "currentSrc", + "currentState", + "currentStyle", + "currentTarget", + "currentTime", + "currentTranslate", + "currentView", + "cursor", + "curve", + "customElements", + "customError", + "cx", + "cy", + "d", + "data", + "dataFld", + "dataFormatAs", + "dataLoss", + "dataLossMessage", + "dataPageSize", + "dataSrc", + "dataTransfer", + "database", + "databases", + "dataset", + "dateTime", + "db", + "debug", + "debuggerEnabled", + "declare", + "decode", + "decodeAudioData", + "decodeURI", + "decodeURIComponent", + "decodedBodySize", + "decoding", + "decodingInfo", + "decrypt", + "default", + "defaultCharset", + "defaultChecked", + "defaultMuted", + "defaultPlaybackRate", + "defaultPolicy", + "defaultPrevented", + "defaultRequest", + "defaultSelected", + "defaultStatus", + "defaultURL", + "defaultValue", + "defaultView", + "defaultstatus", + "defer", + "define", + "defineMagicFunction", + "defineMagicVariable", + "defineProperties", + "defineProperty", + "deg", + "delay", + "delayTime", + "delegatesFocus", + "delete", + "deleteBuffer", + "deleteCaption", + "deleteCell", + "deleteContents", + "deleteData", + "deleteDatabase", + "deleteFramebuffer", + "deleteFromDocument", + "deleteIndex", + "deleteMedium", + "deleteObjectStore", + "deleteProgram", + "deleteProperty", + "deleteQuery", + "deleteRenderbuffer", + "deleteRow", + "deleteRule", + "deleteSampler", + "deleteShader", + "deleteSync", + "deleteTFoot", + "deleteTHead", + "deleteTexture", + "deleteTransformFeedback", + "deleteVertexArray", + "deliverChangeRecords", + "delivery", + "deliveryInfo", + "deliveryStatus", + "deliveryTimestamp", + "delta", + "deltaMode", + "deltaX", + "deltaY", + "deltaZ", + "dependentLocality", + "depthFar", + "depthFunc", + "depthMask", + "depthNear", + "depthRange", + "deref", + "deriveBits", + "deriveKey", + "description", + "deselectAll", + "designMode", + "desiredSize", + "destination", + "destinationURL", + "detach", + "detachEvent", + "detachShader", + "detail", + "details", + "detect", + "detune", + "device", + "deviceClass", + "deviceId", + "deviceMemory", + "devicePixelContentBoxSize", + "devicePixelRatio", + "deviceProtocol", + "deviceSubclass", + "deviceVersionMajor", + "deviceVersionMinor", + "deviceVersionSubminor", + "deviceXDPI", + "deviceYDPI", + "didTimeout", + "diffuseConstant", + "digest", + "dimensions", + "dir", + "dirName", + "direction", + "dirxml", + "disable", + "disablePictureInPicture", + "disableRemotePlayback", + "disableVertexAttribArray", + "disabled", + "dischargingTime", + "disconnect", + "disconnectShark", + "dispatchEvent", + "display", + "displayId", + "displayName", + "disposition", + "distanceModel", + "div", + "divisor", + "djsapi", + "djsproxy", + "doImport", + "doNotTrack", + "doScroll", + "doctype", + "document", + "documentElement", + "documentMode", + "documentURI", + "dolphin", + "dolphinGameCenter", + "dolphininfo", + "dolphinmeta", + "domComplete", + "domContentLoadedEventEnd", + "domContentLoadedEventStart", + "domInteractive", + "domLoading", + "domOverlayState", + "domain", + "domainLookupEnd", + "domainLookupStart", + "dominant-baseline", + "dominantBaseline", + "done", + "dopplerFactor", + "dotAll", + "downDegrees", + "downlink", + "download", + "downloadTotal", + "downloaded", + "dpcm", + "dpi", + "dppx", + "dragDrop", + "draggable", + "drawArrays", + "drawArraysInstanced", + "drawArraysInstancedANGLE", + "drawBuffers", + "drawCustomFocusRing", + "drawElements", + "drawElementsInstanced", + "drawElementsInstancedANGLE", + "drawFocusIfNeeded", + "drawImage", + "drawImageFromRect", + "drawRangeElements", + "drawSystemFocusRing", + "drawingBufferHeight", + "drawingBufferWidth", + "dropEffect", + "droppedVideoFrames", + "dropzone", + "dtmf", + "dump", + "dumpProfile", + "duplicate", + "durability", + "duration", + "dvname", + "dvnum", + "dx", + "dy", + "dynsrc", + "e", + "edgeMode", + "effect", + "effectAllowed", + "effectiveDirective", + "effectiveType", + "elapsedTime", + "element", + "elementFromPoint", + "elementTiming", + "elements", + "elementsFromPoint", + "elevation", + "ellipse", + "em", + "email", + "embeds", + "emma", + "empty", + "empty-cells", + "emptyCells", + "emptyHTML", + "emptyScript", + "emulatedPosition", + "enable", + "enableBackground", + "enableDelegations", + "enableStyleSheetsForSet", + "enableVertexAttribArray", + "enabled", + "enabledPlugin", + "encode", + "encodeInto", + "encodeURI", + "encodeURIComponent", + "encodedBodySize", + "encoding", + "encodingInfo", + "encrypt", + "enctype", + "end", + "endContainer", + "endElement", + "endElementAt", + "endOfStream", + "endOffset", + "endQuery", + "endTime", + "endTransformFeedback", + "ended", + "endpoint", + "endpointNumber", + "endpoints", + "endsWith", + "enterKeyHint", + "entities", + "entries", + "entryType", + "enumerate", + "enumerateDevices", + "enumerateEditable", + "environmentBlendMode", + "equals", + "error", + "errorCode", + "errorDetail", + "errorText", + "escape", + "estimate", + "eval", + "evaluate", + "event", + "eventPhase", + "every", + "ex", + "exception", + "exchange", + "exec", + "execCommand", + "execCommandShowHelp", + "execScript", + "exitFullscreen", + "exitPictureInPicture", + "exitPointerLock", + "exitPresent", + "exp", + "expand", + "expandEntityReferences", + "expando", + "expansion", + "expiration", + "expirationTime", + "expires", + "expiryDate", + "explicitOriginalTarget", + "expm1", + "exponent", + "exponentialRampToValueAtTime", + "exportKey", + "exports", + "extend", + "extensions", + "extentNode", + "extentOffset", + "external", + "externalResourcesRequired", + "extractContents", + "extractable", + "eye", + "f", + "face", + "factoryReset", + "failureReason", + "fallback", + "family", + "familyName", + "farthestViewportElement", + "fastSeek", + "fatal", + "featureId", + "featurePolicy", + "featureSettings", + "features", + "fenceSync", + "fetch", + "fetchStart", + "fftSize", + "fgColor", + "fieldOfView", + "file", + "fileCreatedDate", + "fileHandle", + "fileModifiedDate", + "fileName", + "fileSize", + "fileUpdatedDate", + "filename", + "files", + "filesystem", + "fill", + "fill-opacity", + "fill-rule", + "fillLightMode", + "fillOpacity", + "fillRect", + "fillRule", + "fillStyle", + "fillText", + "filter", + "filterResX", + "filterResY", + "filterUnits", + "filters", + "finally", + "find", + "findIndex", + "findRule", + "findText", + "finish", + "finished", + "fireEvent", + "firesTouchEvents", + "firstChild", + "firstElementChild", + "firstPage", + "fixed", + "flags", + "flat", + "flatMap", + "flex", + "flex-basis", + "flex-direction", + "flex-flow", + "flex-grow", + "flex-shrink", + "flex-wrap", + "flexBasis", + "flexDirection", + "flexFlow", + "flexGrow", + "flexShrink", + "flexWrap", + "flipX", + "flipY", + "float", + "float32", + "float64", + "flood-color", + "flood-opacity", + "floodColor", + "floodOpacity", + "floor", + "flush", + "focus", + "focusNode", + "focusOffset", + "font", + "font-family", + "font-feature-settings", + "font-kerning", + "font-language-override", + "font-optical-sizing", + "font-size", + "font-size-adjust", + "font-stretch", + "font-style", + "font-synthesis", + "font-variant", + "font-variant-alternates", + "font-variant-caps", + "font-variant-east-asian", + "font-variant-ligatures", + "font-variant-numeric", + "font-variant-position", + "font-variation-settings", + "font-weight", + "fontFamily", + "fontFeatureSettings", + "fontKerning", + "fontLanguageOverride", + "fontOpticalSizing", + "fontSize", + "fontSizeAdjust", + "fontSmoothingEnabled", + "fontStretch", + "fontStyle", + "fontSynthesis", + "fontVariant", + "fontVariantAlternates", + "fontVariantCaps", + "fontVariantEastAsian", + "fontVariantLigatures", + "fontVariantNumeric", + "fontVariantPosition", + "fontVariationSettings", + "fontWeight", + "fontcolor", + "fontfaces", + "fonts", + "fontsize", + "for", + "forEach", + "force", + "forceRedraw", + "form", + "formAction", + "formData", + "formEnctype", + "formMethod", + "formNoValidate", + "formTarget", + "format", + "formatToParts", + "forms", + "forward", + "forwardX", + "forwardY", + "forwardZ", + "foundation", + "fr", + "fragmentDirective", + "frame", + "frameBorder", + "frameElement", + "frameSpacing", + "framebuffer", + "framebufferHeight", + "framebufferRenderbuffer", + "framebufferTexture2D", + "framebufferTextureLayer", + "framebufferWidth", + "frames", + "freeSpace", + "freeze", + "frequency", + "frequencyBinCount", + "from", + "fromCharCode", + "fromCodePoint", + "fromElement", + "fromEntries", + "fromFloat32Array", + "fromFloat64Array", + "fromMatrix", + "fromPoint", + "fromQuad", + "fromRect", + "frontFace", + "fround", + "fullPath", + "fullScreen", + "fullscreen", + "fullscreenElement", + "fullscreenEnabled", + "fx", + "fy", + "gain", + "gamepad", + "gamma", + "gap", + "gatheringState", + "gatt", + "genderIdentity", + "generateCertificate", + "generateKey", + "generateMipmap", + "generateRequest", + "geolocation", + "gestureObject", + "get", + "getActiveAttrib", + "getActiveUniform", + "getActiveUniformBlockName", + "getActiveUniformBlockParameter", + "getActiveUniforms", + "getAdjacentText", + "getAll", + "getAllKeys", + "getAllResponseHeaders", + "getAllowlistForFeature", + "getAnimations", + "getAsFile", + "getAsString", + "getAttachedShaders", + "getAttribLocation", + "getAttribute", + "getAttributeNS", + "getAttributeNames", + "getAttributeNode", + "getAttributeNodeNS", + "getAttributeType", + "getAudioTracks", + "getAvailability", + "getBBox", + "getBattery", + "getBigInt64", + "getBigUint64", + "getBlob", + "getBookmark", + "getBoundingClientRect", + "getBounds", + "getBoxQuads", + "getBufferParameter", + "getBufferSubData", + "getByteFrequencyData", + "getByteTimeDomainData", + "getCSSCanvasContext", + "getCTM", + "getCandidateWindowClientRect", + "getCanonicalLocales", + "getCapabilities", + "getChannelData", + "getCharNumAtPosition", + "getCharacteristic", + "getCharacteristics", + "getClientExtensionResults", + "getClientRect", + "getClientRects", + "getCoalescedEvents", + "getCompositionAlternatives", + "getComputedStyle", + "getComputedTextLength", + "getComputedTiming", + "getConfiguration", + "getConstraints", + "getContext", + "getContextAttributes", + "getContributingSources", + "getCounterValue", + "getCueAsHTML", + "getCueById", + "getCurrentPosition", + "getCurrentTime", + "getData", + "getDatabaseNames", + "getDate", + "getDay", + "getDefaultComputedStyle", + "getDescriptor", + "getDescriptors", + "getDestinationInsertionPoints", + "getDevices", + "getDirectory", + "getDisplayMedia", + "getDistributedNodes", + "getEditable", + "getElementById", + "getElementsByClassName", + "getElementsByName", + "getElementsByTagName", + "getElementsByTagNameNS", + "getEnclosureList", + "getEndPositionOfChar", + "getEntries", + "getEntriesByName", + "getEntriesByType", + "getError", + "getExtension", + "getExtentOfChar", + "getEyeParameters", + "getFeature", + "getFile", + "getFiles", + "getFilesAndDirectories", + "getFingerprints", + "getFloat32", + "getFloat64", + "getFloatFrequencyData", + "getFloatTimeDomainData", + "getFloatValue", + "getFragDataLocation", + "getFrameData", + "getFramebufferAttachmentParameter", + "getFrequencyResponse", + "getFullYear", + "getGamepads", + "getHitTestResults", + "getHitTestResultsForTransientInput", + "getHours", + "getIdentityAssertion", + "getIds", + "getImageData", + "getIndexedParameter", + "getInstalledRelatedApps", + "getInt16", + "getInt32", + "getInt8", + "getInternalformatParameter", + "getIntersectionList", + "getItem", + "getItems", + "getKey", + "getKeyframes", + "getLayers", + "getLayoutMap", + "getLineDash", + "getLocalCandidates", + "getLocalParameters", + "getLocalStreams", + "getMarks", + "getMatchedCSSRules", + "getMaxGCPauseSinceClear", + "getMeasures", + "getMetadata", + "getMilliseconds", + "getMinutes", + "getModifierState", + "getMonth", + "getNamedItem", + "getNamedItemNS", + "getNativeFramebufferScaleFactor", + "getNotifications", + "getNotifier", + "getNumberOfChars", + "getOffsetReferenceSpace", + "getOutputTimestamp", + "getOverrideHistoryNavigationMode", + "getOverrideStyle", + "getOwnPropertyDescriptor", + "getOwnPropertyDescriptors", + "getOwnPropertyNames", + "getOwnPropertySymbols", + "getParameter", + "getParameters", + "getParent", + "getPathSegAtLength", + "getPhotoCapabilities", + "getPhotoSettings", + "getPointAtLength", + "getPose", + "getPredictedEvents", + "getPreference", + "getPreferenceDefault", + "getPresentationAttribute", + "getPreventDefault", + "getPrimaryService", + "getPrimaryServices", + "getProgramInfoLog", + "getProgramParameter", + "getPropertyCSSValue", + "getPropertyPriority", + "getPropertyShorthand", + "getPropertyType", + "getPropertyValue", + "getPrototypeOf", + "getQuery", + "getQueryParameter", + "getRGBColorValue", + "getRandomValues", + "getRangeAt", + "getReader", + "getReceivers", + "getRectValue", + "getRegistration", + "getRegistrations", + "getRemoteCandidates", + "getRemoteCertificates", + "getRemoteParameters", + "getRemoteStreams", + "getRenderbufferParameter", + "getResponseHeader", + "getRoot", + "getRootNode", + "getRotationOfChar", + "getSVGDocument", + "getSamplerParameter", + "getScreenCTM", + "getSeconds", + "getSelectedCandidatePair", + "getSelection", + "getSenders", + "getService", + "getSettings", + "getShaderInfoLog", + "getShaderParameter", + "getShaderPrecisionFormat", + "getShaderSource", + "getSimpleDuration", + "getSiteIcons", + "getSources", + "getSpeculativeParserUrls", + "getStartPositionOfChar", + "getStartTime", + "getState", + "getStats", + "getStatusForPolicy", + "getStorageUpdates", + "getStreamById", + "getStringValue", + "getSubStringLength", + "getSubscription", + "getSupportedConstraints", + "getSupportedExtensions", + "getSupportedFormats", + "getSyncParameter", + "getSynchronizationSources", + "getTags", + "getTargetRanges", + "getTexParameter", + "getTime", + "getTimezoneOffset", + "getTiming", + "getTotalLength", + "getTrackById", + "getTracks", + "getTransceivers", + "getTransform", + "getTransformFeedbackVarying", + "getTransformToElement", + "getTransports", + "getType", + "getTypeMapping", + "getUTCDate", + "getUTCDay", + "getUTCFullYear", + "getUTCHours", + "getUTCMilliseconds", + "getUTCMinutes", + "getUTCMonth", + "getUTCSeconds", + "getUint16", + "getUint32", + "getUint8", + "getUniform", + "getUniformBlockIndex", + "getUniformIndices", + "getUniformLocation", + "getUserMedia", + "getVRDisplays", + "getValues", + "getVarDate", + "getVariableValue", + "getVertexAttrib", + "getVertexAttribOffset", + "getVideoPlaybackQuality", + "getVideoTracks", + "getViewerPose", + "getViewport", + "getVoices", + "getWakeLockState", + "getWriter", + "getYear", + "givenName", + "global", + "globalAlpha", + "globalCompositeOperation", + "globalThis", + "glyphOrientationHorizontal", + "glyphOrientationVertical", + "glyphRef", + "go", + "grabFrame", + "grad", + "gradientTransform", + "gradientUnits", + "grammars", + "green", + "grid", + "grid-area", + "grid-auto-columns", + "grid-auto-flow", + "grid-auto-rows", + "grid-column", + "grid-column-end", + "grid-column-gap", + "grid-column-start", + "grid-gap", + "grid-row", + "grid-row-end", + "grid-row-gap", + "grid-row-start", + "grid-template", + "grid-template-areas", + "grid-template-columns", + "grid-template-rows", + "gridArea", + "gridAutoColumns", + "gridAutoFlow", + "gridAutoRows", + "gridColumn", + "gridColumnEnd", + "gridColumnGap", + "gridColumnStart", + "gridGap", + "gridRow", + "gridRowEnd", + "gridRowGap", + "gridRowStart", + "gridTemplate", + "gridTemplateAreas", + "gridTemplateColumns", + "gridTemplateRows", + "gripSpace", + "group", + "groupCollapsed", + "groupEnd", + "groupId", + "hadRecentInput", + "hand", + "handedness", + "hapticActuators", + "hardwareConcurrency", + "has", + "hasAttribute", + "hasAttributeNS", + "hasAttributes", + "hasBeenActive", + "hasChildNodes", + "hasComposition", + "hasEnrolledInstrument", + "hasExtension", + "hasExternalDisplay", + "hasFeature", + "hasFocus", + "hasInstance", + "hasLayout", + "hasOrientation", + "hasOwnProperty", + "hasPointerCapture", + "hasPosition", + "hasReading", + "hasStorageAccess", + "hash", + "head", + "headers", + "heading", + "height", + "hidden", + "hide", + "hideFocus", + "high", + "highWaterMark", + "hint", + "history", + "honorificPrefix", + "honorificSuffix", + "horizontalOverflow", + "host", + "hostCandidate", + "hostname", + "href", + "hrefTranslate", + "hreflang", + "hspace", + "html5TagCheckInerface", + "htmlFor", + "htmlText", + "httpEquiv", + "httpRequestStatusCode", + "hwTimestamp", + "hyphens", + "hypot", + "iccId", + "iceConnectionState", + "iceGatheringState", + "iceTransport", + "icon", + "iconURL", + "id", + "identifier", + "identity", + "idpLoginUrl", + "ignoreBOM", + "ignoreCase", + "ignoreDepthValues", + "image-orientation", + "image-rendering", + "imageHeight", + "imageOrientation", + "imageRendering", + "imageSizes", + "imageSmoothingEnabled", + "imageSmoothingQuality", + "imageSrcset", + "imageWidth", + "images", + "ime-mode", + "imeMode", + "implementation", + "importKey", + "importNode", + "importStylesheet", + "imports", + "impp", + "imul", + "in", + "in1", + "in2", + "inBandMetadataTrackDispatchType", + "inRange", + "includes", + "incremental", + "indeterminate", + "index", + "indexNames", + "indexOf", + "indexedDB", + "indicate", + "inertiaDestinationX", + "inertiaDestinationY", + "info", + "init", + "initAnimationEvent", + "initBeforeLoadEvent", + "initClipboardEvent", + "initCloseEvent", + "initCommandEvent", + "initCompositionEvent", + "initCustomEvent", + "initData", + "initDataType", + "initDeviceMotionEvent", + "initDeviceOrientationEvent", + "initDragEvent", + "initErrorEvent", + "initEvent", + "initFocusEvent", + "initGestureEvent", + "initHashChangeEvent", + "initKeyEvent", + "initKeyboardEvent", + "initMSManipulationEvent", + "initMessageEvent", + "initMouseEvent", + "initMouseScrollEvent", + "initMouseWheelEvent", + "initMutationEvent", + "initNSMouseEvent", + "initOverflowEvent", + "initPageEvent", + "initPageTransitionEvent", + "initPointerEvent", + "initPopStateEvent", + "initProgressEvent", + "initScrollAreaEvent", + "initSimpleGestureEvent", + "initStorageEvent", + "initTextEvent", + "initTimeEvent", + "initTouchEvent", + "initTransitionEvent", + "initUIEvent", + "initWebKitAnimationEvent", + "initWebKitTransitionEvent", + "initWebKitWheelEvent", + "initWheelEvent", + "initialTime", + "initialize", + "initiatorType", + "inline-size", + "inlineSize", + "inlineVerticalFieldOfView", + "inner", + "innerHTML", + "innerHeight", + "innerText", + "innerWidth", + "input", + "inputBuffer", + "inputEncoding", + "inputMethod", + "inputMode", + "inputSource", + "inputSources", + "inputType", + "inputs", + "insertAdjacentElement", + "insertAdjacentHTML", + "insertAdjacentText", + "insertBefore", + "insertCell", + "insertDTMF", + "insertData", + "insertItemBefore", + "insertNode", + "insertRow", + "insertRule", + "inset", + "inset-block", + "inset-block-end", + "inset-block-start", + "inset-inline", + "inset-inline-end", + "inset-inline-start", + "insetBlock", + "insetBlockEnd", + "insetBlockStart", + "insetInline", + "insetInlineEnd", + "insetInlineStart", + "installing", + "instanceRoot", + "instantiate", + "instantiateStreaming", + "instruments", + "int16", + "int32", + "int8", + "integrity", + "interactionMode", + "intercept", + "interfaceClass", + "interfaceName", + "interfaceNumber", + "interfaceProtocol", + "interfaceSubclass", + "interfaces", + "interimResults", + "internalSubset", + "interpretation", + "intersectionRatio", + "intersectionRect", + "intersectsNode", + "interval", + "invalidIteratorState", + "invalidateFramebuffer", + "invalidateSubFramebuffer", + "inverse", + "invertSelf", + "is", + "is2D", + "isActive", + "isAlternate", + "isArray", + "isBingCurrentSearchDefault", + "isBuffer", + "isCandidateWindowVisible", + "isChar", + "isCollapsed", + "isComposing", + "isConcatSpreadable", + "isConnected", + "isContentEditable", + "isContentHandlerRegistered", + "isContextLost", + "isDefaultNamespace", + "isDirectory", + "isDisabled", + "isEnabled", + "isEqual", + "isEqualNode", + "isExtensible", + "isExternalCTAP2SecurityKeySupported", + "isFile", + "isFinite", + "isFramebuffer", + "isFrozen", + "isGenerator", + "isHTML", + "isHistoryNavigation", + "isId", + "isIdentity", + "isInjected", + "isInteger", + "isIntersecting", + "isLockFree", + "isMap", + "isMultiLine", + "isNaN", + "isOpen", + "isPointInFill", + "isPointInPath", + "isPointInRange", + "isPointInStroke", + "isPrefAlternate", + "isPresenting", + "isPrimary", + "isProgram", + "isPropertyImplicit", + "isProtocolHandlerRegistered", + "isPrototypeOf", + "isQuery", + "isRenderbuffer", + "isSafeInteger", + "isSameNode", + "isSampler", + "isScript", + "isScriptURL", + "isSealed", + "isSecureContext", + "isSessionSupported", + "isShader", + "isSupported", + "isSync", + "isTextEdit", + "isTexture", + "isTransformFeedback", + "isTrusted", + "isTypeSupported", + "isUserVerifyingPlatformAuthenticatorAvailable", + "isVertexArray", + "isView", + "isVisible", + "isochronousTransferIn", + "isochronousTransferOut", + "isolation", + "italics", + "item", + "itemId", + "itemProp", + "itemRef", + "itemScope", + "itemType", + "itemValue", + "items", + "iterateNext", + "iterationComposite", + "iterator", + "javaEnabled", + "jobTitle", + "join", + "json", + "justify-content", + "justify-items", + "justify-self", + "justifyContent", + "justifyItems", + "justifySelf", + "k1", + "k2", + "k3", + "k4", + "kHz", + "keepalive", + "kernelMatrix", + "kernelUnitLengthX", + "kernelUnitLengthY", + "kerning", + "key", + "keyCode", + "keyFor", + "keyIdentifier", + "keyLightEnabled", + "keyLocation", + "keyPath", + "keyStatuses", + "keySystem", + "keyText", + "keyUsage", + "keyboard", + "keys", + "keytype", + "kind", + "knee", + "label", + "labels", + "lang", + "language", + "languages", + "largeArcFlag", + "lastChild", + "lastElementChild", + "lastEventId", + "lastIndex", + "lastIndexOf", + "lastInputTime", + "lastMatch", + "lastMessageSubject", + "lastMessageType", + "lastModified", + "lastModifiedDate", + "lastPage", + "lastParen", + "lastState", + "lastStyleSheetSet", + "latitude", + "layerX", + "layerY", + "layoutFlow", + "layoutGrid", + "layoutGridChar", + "layoutGridLine", + "layoutGridMode", + "layoutGridType", + "lbound", + "left", + "leftContext", + "leftDegrees", + "leftMargin", + "leftProjectionMatrix", + "leftViewMatrix", + "length", + "lengthAdjust", + "lengthComputable", + "letter-spacing", + "letterSpacing", + "level", + "lighting-color", + "lightingColor", + "limitingConeAngle", + "line", + "line-break", + "line-height", + "lineAlign", + "lineBreak", + "lineCap", + "lineDashOffset", + "lineHeight", + "lineJoin", + "lineNumber", + "lineTo", + "lineWidth", + "linearAcceleration", + "linearRampToValueAtTime", + "linearVelocity", + "lineno", + "lines", + "link", + "linkColor", + "linkProgram", + "links", + "list", + "list-style", + "list-style-image", + "list-style-position", + "list-style-type", + "listStyle", + "listStyleImage", + "listStylePosition", + "listStyleType", + "listener", + "load", + "loadEventEnd", + "loadEventStart", + "loadTime", + "loadTimes", + "loaded", + "loading", + "localDescription", + "localName", + "localService", + "localStorage", + "locale", + "localeCompare", + "location", + "locationbar", + "lock", + "locked", + "lockedFile", + "locks", + "log", + "log10", + "log1p", + "log2", + "logicalXDPI", + "logicalYDPI", + "longDesc", + "longitude", + "lookupNamespaceURI", + "lookupPrefix", + "loop", + "loopEnd", + "loopStart", + "looping", + "low", + "lower", + "lowerBound", + "lowerOpen", + "lowsrc", + "m11", + "m12", + "m13", + "m14", + "m21", + "m22", + "m23", + "m24", + "m31", + "m32", + "m33", + "m34", + "m41", + "m42", + "m43", + "m44", + "makeXRCompatible", + "manifest", + "manufacturer", + "manufacturerName", + "map", + "mapping", + "margin", + "margin-block", + "margin-block-end", + "margin-block-start", + "margin-bottom", + "margin-inline", + "margin-inline-end", + "margin-inline-start", + "margin-left", + "margin-right", + "margin-top", + "marginBlock", + "marginBlockEnd", + "marginBlockStart", + "marginBottom", + "marginHeight", + "marginInline", + "marginInlineEnd", + "marginInlineStart", + "marginLeft", + "marginRight", + "marginTop", + "marginWidth", + "mark", + "marker", + "marker-end", + "marker-mid", + "marker-offset", + "marker-start", + "markerEnd", + "markerHeight", + "markerMid", + "markerOffset", + "markerStart", + "markerUnits", + "markerWidth", + "marks", + "mask", + "mask-clip", + "mask-composite", + "mask-image", + "mask-mode", + "mask-origin", + "mask-position", + "mask-position-x", + "mask-position-y", + "mask-repeat", + "mask-size", + "mask-type", + "maskClip", + "maskComposite", + "maskContentUnits", + "maskImage", + "maskMode", + "maskOrigin", + "maskPosition", + "maskPositionX", + "maskPositionY", + "maskRepeat", + "maskSize", + "maskType", + "maskUnits", + "match", + "matchAll", + "matchMedia", + "matchMedium", + "matches", + "matrix", + "matrixTransform", + "max", + "max-block-size", + "max-height", + "max-inline-size", + "max-width", + "maxActions", + "maxAlternatives", + "maxBlockSize", + "maxChannelCount", + "maxChannels", + "maxConnectionsPerServer", + "maxDecibels", + "maxDistance", + "maxHeight", + "maxInlineSize", + "maxLayers", + "maxLength", + "maxMessageSize", + "maxPacketLifeTime", + "maxRetransmits", + "maxTouchPoints", + "maxValue", + "maxWidth", + "measure", + "measureText", + "media", + "mediaCapabilities", + "mediaDevices", + "mediaElement", + "mediaGroup", + "mediaKeys", + "mediaSession", + "mediaStream", + "mediaText", + "meetOrSlice", + "memory", + "menubar", + "mergeAttributes", + "message", + "messageClass", + "messageHandlers", + "messageType", + "metaKey", + "metadata", + "method", + "methodDetails", + "methodName", + "mid", + "mimeType", + "mimeTypes", + "min", + "min-block-size", + "min-height", + "min-inline-size", + "min-width", + "minBlockSize", + "minDecibels", + "minHeight", + "minInlineSize", + "minLength", + "minValue", + "minWidth", + "miterLimit", + "mix-blend-mode", + "mixBlendMode", + "mm", + "mode", + "modify", + "mount", + "move", + "moveBy", + "moveEnd", + "moveFirst", + "moveFocusDown", + "moveFocusLeft", + "moveFocusRight", + "moveFocusUp", + "moveNext", + "moveRow", + "moveStart", + "moveTo", + "moveToBookmark", + "moveToElementText", + "moveToPoint", + "movementX", + "movementY", + "mozAdd", + "mozAnimationStartTime", + "mozAnon", + "mozApps", + "mozAudioCaptured", + "mozAudioChannelType", + "mozAutoplayEnabled", + "mozCancelAnimationFrame", + "mozCancelFullScreen", + "mozCancelRequestAnimationFrame", + "mozCaptureStream", + "mozCaptureStreamUntilEnded", + "mozClearDataAt", + "mozContact", + "mozContacts", + "mozCreateFileHandle", + "mozCurrentTransform", + "mozCurrentTransformInverse", + "mozCursor", + "mozDash", + "mozDashOffset", + "mozDecodedFrames", + "mozExitPointerLock", + "mozFillRule", + "mozFragmentEnd", + "mozFrameDelay", + "mozFullScreen", + "mozFullScreenElement", + "mozFullScreenEnabled", + "mozGetAll", + "mozGetAllKeys", + "mozGetAsFile", + "mozGetDataAt", + "mozGetMetadata", + "mozGetUserMedia", + "mozHasAudio", + "mozHasItem", + "mozHidden", + "mozImageSmoothingEnabled", + "mozIndexedDB", + "mozInnerScreenX", + "mozInnerScreenY", + "mozInputSource", + "mozIsTextField", + "mozItem", + "mozItemCount", + "mozItems", + "mozLength", + "mozLockOrientation", + "mozMatchesSelector", + "mozMovementX", + "mozMovementY", + "mozOpaque", + "mozOrientation", + "mozPaintCount", + "mozPaintedFrames", + "mozParsedFrames", + "mozPay", + "mozPointerLockElement", + "mozPresentedFrames", + "mozPreservesPitch", + "mozPressure", + "mozPrintCallback", + "mozRTCIceCandidate", + "mozRTCPeerConnection", + "mozRTCSessionDescription", + "mozRemove", + "mozRequestAnimationFrame", + "mozRequestFullScreen", + "mozRequestPointerLock", + "mozSetDataAt", + "mozSetImageElement", + "mozSourceNode", + "mozSrcObject", + "mozSystem", + "mozTCPSocket", + "mozTextStyle", + "mozTypesAt", + "mozUnlockOrientation", + "mozUserCancelled", + "mozVisibilityState", + "ms", + "msAnimation", + "msAnimationDelay", + "msAnimationDirection", + "msAnimationDuration", + "msAnimationFillMode", + "msAnimationIterationCount", + "msAnimationName", + "msAnimationPlayState", + "msAnimationStartTime", + "msAnimationTimingFunction", + "msBackfaceVisibility", + "msBlockProgression", + "msCSSOMElementFloatMetrics", + "msCaching", + "msCachingEnabled", + "msCancelRequestAnimationFrame", + "msCapsLockWarningOff", + "msClearImmediate", + "msClose", + "msContentZoomChaining", + "msContentZoomFactor", + "msContentZoomLimit", + "msContentZoomLimitMax", + "msContentZoomLimitMin", + "msContentZoomSnap", + "msContentZoomSnapPoints", + "msContentZoomSnapType", + "msContentZooming", + "msConvertURL", + "msCrypto", + "msDoNotTrack", + "msElementsFromPoint", + "msElementsFromRect", + "msExitFullscreen", + "msExtendedCode", + "msFillRule", + "msFirstPaint", + "msFlex", + "msFlexAlign", + "msFlexDirection", + "msFlexFlow", + "msFlexItemAlign", + "msFlexLinePack", + "msFlexNegative", + "msFlexOrder", + "msFlexPack", + "msFlexPositive", + "msFlexPreferredSize", + "msFlexWrap", + "msFlowFrom", + "msFlowInto", + "msFontFeatureSettings", + "msFullscreenElement", + "msFullscreenEnabled", + "msGetInputContext", + "msGetRegionContent", + "msGetUntransformedBounds", + "msGraphicsTrustStatus", + "msGridColumn", + "msGridColumnAlign", + "msGridColumnSpan", + "msGridColumns", + "msGridRow", + "msGridRowAlign", + "msGridRowSpan", + "msGridRows", + "msHidden", + "msHighContrastAdjust", + "msHyphenateLimitChars", + "msHyphenateLimitLines", + "msHyphenateLimitZone", + "msHyphens", + "msImageSmoothingEnabled", + "msImeAlign", + "msIndexedDB", + "msInterpolationMode", + "msIsStaticHTML", + "msKeySystem", + "msKeys", + "msLaunchUri", + "msLockOrientation", + "msManipulationViewsEnabled", + "msMatchMedia", + "msMatchesSelector", + "msMaxTouchPoints", + "msOrientation", + "msOverflowStyle", + "msPerspective", + "msPerspectiveOrigin", + "msPlayToDisabled", + "msPlayToPreferredSourceUri", + "msPlayToPrimary", + "msPointerEnabled", + "msRegionOverflow", + "msReleasePointerCapture", + "msRequestAnimationFrame", + "msRequestFullscreen", + "msSaveBlob", + "msSaveOrOpenBlob", + "msScrollChaining", + "msScrollLimit", + "msScrollLimitXMax", + "msScrollLimitXMin", + "msScrollLimitYMax", + "msScrollLimitYMin", + "msScrollRails", + "msScrollSnapPointsX", + "msScrollSnapPointsY", + "msScrollSnapType", + "msScrollSnapX", + "msScrollSnapY", + "msScrollTranslation", + "msSetImmediate", + "msSetMediaKeys", + "msSetPointerCapture", + "msTextCombineHorizontal", + "msTextSizeAdjust", + "msToBlob", + "msTouchAction", + "msTouchSelect", + "msTraceAsyncCallbackCompleted", + "msTraceAsyncCallbackStarting", + "msTraceAsyncOperationCompleted", + "msTraceAsyncOperationStarting", + "msTransform", + "msTransformOrigin", + "msTransformStyle", + "msTransition", + "msTransitionDelay", + "msTransitionDuration", + "msTransitionProperty", + "msTransitionTimingFunction", + "msUnlockOrientation", + "msUpdateAsyncCallbackRelation", + "msUserSelect", + "msVisibilityState", + "msWrapFlow", + "msWrapMargin", + "msWrapThrough", + "msWriteProfilerMark", + "msZoom", + "msZoomTo", + "mt", + "mul", + "multiEntry", + "multiSelectionObj", + "multiline", + "multiple", + "multiply", + "multiplySelf", + "mutableFile", + "muted", + "n", + "name", + "nameProp", + "namedItem", + "namedRecordset", + "names", + "namespaceURI", + "namespaces", + "naturalHeight", + "naturalWidth", + "navigate", + "navigation", + "navigationMode", + "navigationPreload", + "navigationStart", + "navigator", + "near", + "nearestViewportElement", + "negative", + "negotiated", + "netscape", + "networkState", + "newScale", + "newTranslate", + "newURL", + "newValue", + "newValueSpecifiedUnits", + "newVersion", + "newhome", + "next", + "nextElementSibling", + "nextHopProtocol", + "nextNode", + "nextPage", + "nextSibling", + "nickname", + "noHref", + "noModule", + "noResize", + "noShade", + "noValidate", + "noWrap", + "node", + "nodeName", + "nodeType", + "nodeValue", + "nonce", + "normalize", + "normalizedPathSegList", + "notationName", + "notations", + "note", + "noteGrainOn", + "noteOff", + "noteOn", + "notify", + "now", + "numOctaves", + "number", + "numberOfChannels", + "numberOfInputs", + "numberOfItems", + "numberOfOutputs", + "numberValue", + "oMatchesSelector", + "object", + "object-fit", + "object-position", + "objectFit", + "objectPosition", + "objectStore", + "objectStoreNames", + "objectType", + "observe", + "of", + "offscreenBuffering", + "offset", + "offset-anchor", + "offset-distance", + "offset-path", + "offset-rotate", + "offsetAnchor", + "offsetDistance", + "offsetHeight", + "offsetLeft", + "offsetNode", + "offsetParent", + "offsetPath", + "offsetRotate", + "offsetTop", + "offsetWidth", + "offsetX", + "offsetY", + "ok", + "oldURL", + "oldValue", + "oldVersion", + "olderShadowRoot", + "onLine", + "onabort", + "onabsolutedeviceorientation", + "onactivate", + "onactive", + "onaddsourcebuffer", + "onaddstream", + "onaddtrack", + "onafterprint", + "onafterscriptexecute", + "onafterupdate", + "onanimationcancel", + "onanimationend", + "onanimationiteration", + "onanimationstart", + "onappinstalled", + "onaudioend", + "onaudioprocess", + "onaudiostart", + "onautocomplete", + "onautocompleteerror", + "onauxclick", + "onbeforeactivate", + "onbeforecopy", + "onbeforecut", + "onbeforedeactivate", + "onbeforeeditfocus", + "onbeforeinstallprompt", + "onbeforepaste", + "onbeforeprint", + "onbeforescriptexecute", + "onbeforeunload", + "onbeforeupdate", + "onbeforexrselect", + "onbegin", + "onblocked", + "onblur", + "onbounce", + "onboundary", + "onbufferedamountlow", + "oncached", + "oncancel", + "oncandidatewindowhide", + "oncandidatewindowshow", + "oncandidatewindowupdate", + "oncanplay", + "oncanplaythrough", + "once", + "oncellchange", + "onchange", + "oncharacteristicvaluechanged", + "onchargingchange", + "onchargingtimechange", + "onchecking", + "onclick", + "onclose", + "onclosing", + "oncompassneedscalibration", + "oncomplete", + "onconnect", + "onconnecting", + "onconnectionavailable", + "onconnectionstatechange", + "oncontextmenu", + "oncontrollerchange", + "oncontrolselect", + "oncopy", + "oncuechange", + "oncut", + "ondataavailable", + "ondatachannel", + "ondatasetchanged", + "ondatasetcomplete", + "ondblclick", + "ondeactivate", + "ondevicechange", + "ondevicelight", + "ondevicemotion", + "ondeviceorientation", + "ondeviceorientationabsolute", + "ondeviceproximity", + "ondischargingtimechange", + "ondisconnect", + "ondisplay", + "ondownloading", + "ondrag", + "ondragend", + "ondragenter", + "ondragexit", + "ondragleave", + "ondragover", + "ondragstart", + "ondrop", + "ondurationchange", + "onemptied", + "onencrypted", + "onend", + "onended", + "onenter", + "onenterpictureinpicture", + "onerror", + "onerrorupdate", + "onexit", + "onfilterchange", + "onfinish", + "onfocus", + "onfocusin", + "onfocusout", + "onformdata", + "onfreeze", + "onfullscreenchange", + "onfullscreenerror", + "ongatheringstatechange", + "ongattserverdisconnected", + "ongesturechange", + "ongestureend", + "ongesturestart", + "ongotpointercapture", + "onhashchange", + "onhelp", + "onicecandidate", + "onicecandidateerror", + "oniceconnectionstatechange", + "onicegatheringstatechange", + "oninactive", + "oninput", + "oninputsourceschange", + "oninvalid", + "onkeydown", + "onkeypress", + "onkeystatuseschange", + "onkeyup", + "onlanguagechange", + "onlayoutcomplete", + "onleavepictureinpicture", + "onlevelchange", + "onload", + "onloadeddata", + "onloadedmetadata", + "onloadend", + "onloading", + "onloadingdone", + "onloadingerror", + "onloadstart", + "onlosecapture", + "onlostpointercapture", + "only", + "onmark", + "onmessage", + "onmessageerror", + "onmidimessage", + "onmousedown", + "onmouseenter", + "onmouseleave", + "onmousemove", + "onmouseout", + "onmouseover", + "onmouseup", + "onmousewheel", + "onmove", + "onmoveend", + "onmovestart", + "onmozfullscreenchange", + "onmozfullscreenerror", + "onmozorientationchange", + "onmozpointerlockchange", + "onmozpointerlockerror", + "onmscontentzoom", + "onmsfullscreenchange", + "onmsfullscreenerror", + "onmsgesturechange", + "onmsgesturedoubletap", + "onmsgestureend", + "onmsgesturehold", + "onmsgesturestart", + "onmsgesturetap", + "onmsgotpointercapture", + "onmsinertiastart", + "onmslostpointercapture", + "onmsmanipulationstatechanged", + "onmsneedkey", + "onmsorientationchange", + "onmspointercancel", + "onmspointerdown", + "onmspointerenter", + "onmspointerhover", + "onmspointerleave", + "onmspointermove", + "onmspointerout", + "onmspointerover", + "onmspointerup", + "onmssitemodejumplistitemremoved", + "onmsthumbnailclick", + "onmute", + "onnegotiationneeded", + "onnomatch", + "onnoupdate", + "onobsolete", + "onoffline", + "ononline", + "onopen", + "onorientationchange", + "onpagechange", + "onpagehide", + "onpageshow", + "onpaste", + "onpause", + "onpayerdetailchange", + "onpaymentmethodchange", + "onplay", + "onplaying", + "onpluginstreamstart", + "onpointercancel", + "onpointerdown", + "onpointerenter", + "onpointerleave", + "onpointerlockchange", + "onpointerlockerror", + "onpointermove", + "onpointerout", + "onpointerover", + "onpointerrawupdate", + "onpointerup", + "onpopstate", + "onprocessorerror", + "onprogress", + "onpropertychange", + "onratechange", + "onreading", + "onreadystatechange", + "onrejectionhandled", + "onrelease", + "onremove", + "onremovesourcebuffer", + "onremovestream", + "onremovetrack", + "onrepeat", + "onreset", + "onresize", + "onresizeend", + "onresizestart", + "onresourcetimingbufferfull", + "onresult", + "onresume", + "onrowenter", + "onrowexit", + "onrowsdelete", + "onrowsinserted", + "onscroll", + "onsearch", + "onsecuritypolicyviolation", + "onseeked", + "onseeking", + "onselect", + "onselectedcandidatepairchange", + "onselectend", + "onselectionchange", + "onselectstart", + "onshippingaddresschange", + "onshippingoptionchange", + "onshow", + "onsignalingstatechange", + "onsoundend", + "onsoundstart", + "onsourceclose", + "onsourceclosed", + "onsourceended", + "onsourceopen", + "onspeechend", + "onspeechstart", + "onsqueeze", + "onsqueezeend", + "onsqueezestart", + "onstalled", + "onstart", + "onstatechange", + "onstop", + "onstorage", + "onstoragecommit", + "onsubmit", + "onsuccess", + "onsuspend", + "onterminate", + "ontextinput", + "ontimeout", + "ontimeupdate", + "ontoggle", + "ontonechange", + "ontouchcancel", + "ontouchend", + "ontouchmove", + "ontouchstart", + "ontrack", + "ontransitioncancel", + "ontransitionend", + "ontransitionrun", + "ontransitionstart", + "onunhandledrejection", + "onunload", + "onunmute", + "onupdate", + "onupdateend", + "onupdatefound", + "onupdateready", + "onupdatestart", + "onupgradeneeded", + "onuserproximity", + "onversionchange", + "onvisibilitychange", + "onvoiceschanged", + "onvolumechange", + "onvrdisplayactivate", + "onvrdisplayconnect", + "onvrdisplaydeactivate", + "onvrdisplaydisconnect", + "onvrdisplaypresentchange", + "onwaiting", + "onwaitingforkey", + "onwarning", + "onwebkitanimationend", + "onwebkitanimationiteration", + "onwebkitanimationstart", + "onwebkitcurrentplaybacktargetiswirelesschanged", + "onwebkitfullscreenchange", + "onwebkitfullscreenerror", + "onwebkitkeyadded", + "onwebkitkeyerror", + "onwebkitkeymessage", + "onwebkitneedkey", + "onwebkitorientationchange", + "onwebkitplaybacktargetavailabilitychanged", + "onwebkitpointerlockchange", + "onwebkitpointerlockerror", + "onwebkitresourcetimingbufferfull", + "onwebkittransitionend", + "onwheel", + "onzoom", + "opacity", + "open", + "openCursor", + "openDatabase", + "openKeyCursor", + "opened", + "opener", + "opera", + "operationType", + "operator", + "opr", + "optimum", + "options", + "or", + "order", + "orderX", + "orderY", + "ordered", + "org", + "organization", + "orient", + "orientAngle", + "orientType", + "orientation", + "orientationX", + "orientationY", + "orientationZ", + "origin", + "originalPolicy", + "originalTarget", + "orphans", + "oscpu", + "outerHTML", + "outerHeight", + "outerText", + "outerWidth", + "outline", + "outline-color", + "outline-offset", + "outline-style", + "outline-width", + "outlineColor", + "outlineOffset", + "outlineStyle", + "outlineWidth", + "outputBuffer", + "outputLatency", + "outputs", + "overflow", + "overflow-anchor", + "overflow-block", + "overflow-inline", + "overflow-wrap", + "overflow-x", + "overflow-y", + "overflowAnchor", + "overflowBlock", + "overflowInline", + "overflowWrap", + "overflowX", + "overflowY", + "overrideMimeType", + "oversample", + "overscroll-behavior", + "overscroll-behavior-block", + "overscroll-behavior-inline", + "overscroll-behavior-x", + "overscroll-behavior-y", + "overscrollBehavior", + "overscrollBehaviorBlock", + "overscrollBehaviorInline", + "overscrollBehaviorX", + "overscrollBehaviorY", + "ownKeys", + "ownerDocument", + "ownerElement", + "ownerNode", + "ownerRule", + "ownerSVGElement", + "owningElement", + "p1", + "p2", + "p3", + "p4", + "packetSize", + "packets", + "pad", + "padEnd", + "padStart", + "padding", + "padding-block", + "padding-block-end", + "padding-block-start", + "padding-bottom", + "padding-inline", + "padding-inline-end", + "padding-inline-start", + "padding-left", + "padding-right", + "padding-top", + "paddingBlock", + "paddingBlockEnd", + "paddingBlockStart", + "paddingBottom", + "paddingInline", + "paddingInlineEnd", + "paddingInlineStart", + "paddingLeft", + "paddingRight", + "paddingTop", + "page", + "page-break-after", + "page-break-before", + "page-break-inside", + "pageBreakAfter", + "pageBreakBefore", + "pageBreakInside", + "pageCount", + "pageLeft", + "pageTop", + "pageX", + "pageXOffset", + "pageY", + "pageYOffset", + "pages", + "paint-order", + "paintOrder", + "paintRequests", + "paintType", + "paintWorklet", + "palette", + "pan", + "panningModel", + "parameters", + "parent", + "parentElement", + "parentNode", + "parentRule", + "parentStyleSheet", + "parentTextEdit", + "parentWindow", + "parse", + "parseAll", + "parseFloat", + "parseFromString", + "parseInt", + "part", + "participants", + "passive", + "password", + "pasteHTML", + "path", + "pathLength", + "pathSegList", + "pathSegType", + "pathSegTypeAsLetter", + "pathname", + "pattern", + "patternContentUnits", + "patternMismatch", + "patternTransform", + "patternUnits", + "pause", + "pauseAnimations", + "pauseOnExit", + "pauseProfilers", + "pauseTransformFeedback", + "paused", + "payerEmail", + "payerName", + "payerPhone", + "paymentManager", + "pc", + "peerIdentity", + "pending", + "pendingLocalDescription", + "pendingRemoteDescription", + "percent", + "performance", + "periodicSync", + "permission", + "permissionState", + "permissions", + "persist", + "persisted", + "personalbar", + "perspective", + "perspective-origin", + "perspectiveOrigin", + "phone", + "phoneticFamilyName", + "phoneticGivenName", + "photo", + "pictureInPictureElement", + "pictureInPictureEnabled", + "pictureInPictureWindow", + "ping", + "pipeThrough", + "pipeTo", + "pitch", + "pixelBottom", + "pixelDepth", + "pixelHeight", + "pixelLeft", + "pixelRight", + "pixelStorei", + "pixelTop", + "pixelUnitToMillimeterX", + "pixelUnitToMillimeterY", + "pixelWidth", + "place-content", + "place-items", + "place-self", + "placeContent", + "placeItems", + "placeSelf", + "placeholder", + "platform", + "platforms", + "play", + "playEffect", + "playState", + "playbackRate", + "playbackState", + "playbackTime", + "played", + "playoutDelayHint", + "playsInline", + "plugins", + "pluginspage", + "pname", + "pointer-events", + "pointerBeforeReferenceNode", + "pointerEnabled", + "pointerEvents", + "pointerId", + "pointerLockElement", + "pointerType", + "points", + "pointsAtX", + "pointsAtY", + "pointsAtZ", + "polygonOffset", + "pop", + "populateMatrix", + "popupWindowFeatures", + "popupWindowName", + "popupWindowURI", + "port", + "port1", + "port2", + "ports", + "posBottom", + "posHeight", + "posLeft", + "posRight", + "posTop", + "posWidth", + "pose", + "position", + "positionAlign", + "positionX", + "positionY", + "positionZ", + "postError", + "postMessage", + "postalCode", + "poster", + "pow", + "powerEfficient", + "powerOff", + "preMultiplySelf", + "precision", + "preferredStyleSheetSet", + "preferredStylesheetSet", + "prefix", + "preload", + "prepend", + "presentation", + "preserveAlpha", + "preserveAspectRatio", + "preserveAspectRatioString", + "pressed", + "pressure", + "prevValue", + "preventDefault", + "preventExtensions", + "preventSilentAccess", + "previousElementSibling", + "previousNode", + "previousPage", + "previousRect", + "previousScale", + "previousSibling", + "previousTranslate", + "primaryKey", + "primitiveType", + "primitiveUnits", + "principals", + "print", + "priority", + "privateKey", + "probablySupportsContext", + "process", + "processIceMessage", + "processingEnd", + "processingStart", + "product", + "productId", + "productName", + "productSub", + "profile", + "profileEnd", + "profiles", + "projectionMatrix", + "promise", + "prompt", + "properties", + "propertyIsEnumerable", + "propertyName", + "protocol", + "protocolLong", + "prototype", + "provider", + "pseudoClass", + "pseudoElement", + "pt", + "publicId", + "publicKey", + "published", + "pulse", + "push", + "pushManager", + "pushNotification", + "pushState", + "put", + "putImageData", + "px", + "quadraticCurveTo", + "qualifier", + "quaternion", + "query", + "queryCommandEnabled", + "queryCommandIndeterm", + "queryCommandState", + "queryCommandSupported", + "queryCommandText", + "queryCommandValue", + "querySelector", + "querySelectorAll", + "queueMicrotask", + "quote", + "quotes", + "r", + "r1", + "r2", + "race", + "rad", + "radiogroup", + "radiusX", + "radiusY", + "random", + "range", + "rangeCount", + "rangeMax", + "rangeMin", + "rangeOffset", + "rangeOverflow", + "rangeParent", + "rangeUnderflow", + "rate", + "ratio", + "raw", + "rawId", + "read", + "readAsArrayBuffer", + "readAsBinaryString", + "readAsBlob", + "readAsDataURL", + "readAsText", + "readBuffer", + "readEntries", + "readOnly", + "readPixels", + "readReportRequested", + "readText", + "readValue", + "readable", + "ready", + "readyState", + "reason", + "reboot", + "receivedAlert", + "receiver", + "receivers", + "recipient", + "reconnect", + "recordNumber", + "recordsAvailable", + "recordset", + "rect", + "red", + "redEyeReduction", + "redirect", + "redirectCount", + "redirectEnd", + "redirectStart", + "redirected", + "reduce", + "reduceRight", + "reduction", + "refDistance", + "refX", + "refY", + "referenceNode", + "referenceSpace", + "referrer", + "referrerPolicy", + "refresh", + "region", + "regionAnchorX", + "regionAnchorY", + "regionId", + "regions", + "register", + "registerContentHandler", + "registerElement", + "registerProperty", + "registerProtocolHandler", + "reject", + "rel", + "relList", + "relatedAddress", + "relatedNode", + "relatedPort", + "relatedTarget", + "release", + "releaseCapture", + "releaseEvents", + "releaseInterface", + "releaseLock", + "releasePointerCapture", + "releaseShaderCompiler", + "reliable", + "reliableWrite", + "reload", + "rem", + "remainingSpace", + "remote", + "remoteDescription", + "remove", + "removeAllRanges", + "removeAttribute", + "removeAttributeNS", + "removeAttributeNode", + "removeBehavior", + "removeChild", + "removeCue", + "removeEventListener", + "removeFilter", + "removeImport", + "removeItem", + "removeListener", + "removeNamedItem", + "removeNamedItemNS", + "removeNode", + "removeParameter", + "removeProperty", + "removeRange", + "removeRegion", + "removeRule", + "removeSiteSpecificTrackingException", + "removeSourceBuffer", + "removeStream", + "removeTrack", + "removeVariable", + "removeWakeLockListener", + "removeWebWideTrackingException", + "removed", + "removedNodes", + "renderHeight", + "renderState", + "renderTime", + "renderWidth", + "renderbufferStorage", + "renderbufferStorageMultisample", + "renderedBuffer", + "renderingMode", + "renotify", + "repeat", + "replace", + "replaceAdjacentText", + "replaceAll", + "replaceChild", + "replaceChildren", + "replaceData", + "replaceId", + "replaceItem", + "replaceNode", + "replaceState", + "replaceSync", + "replaceTrack", + "replaceWholeText", + "replaceWith", + "reportValidity", + "request", + "requestAnimationFrame", + "requestAutocomplete", + "requestData", + "requestDevice", + "requestFrame", + "requestFullscreen", + "requestHitTestSource", + "requestHitTestSourceForTransientInput", + "requestId", + "requestIdleCallback", + "requestMIDIAccess", + "requestMediaKeySystemAccess", + "requestPermission", + "requestPictureInPicture", + "requestPointerLock", + "requestPresent", + "requestReferenceSpace", + "requestSession", + "requestStart", + "requestStorageAccess", + "requestSubmit", + "requestVideoFrameCallback", + "requestingWindow", + "requireInteraction", + "required", + "requiredExtensions", + "requiredFeatures", + "reset", + "resetPose", + "resetTransform", + "resize", + "resizeBy", + "resizeTo", + "resolve", + "response", + "responseBody", + "responseEnd", + "responseReady", + "responseStart", + "responseText", + "responseType", + "responseURL", + "responseXML", + "restartIce", + "restore", + "result", + "resultIndex", + "resultType", + "results", + "resume", + "resumeProfilers", + "resumeTransformFeedback", + "retry", + "returnValue", + "rev", + "reverse", + "reversed", + "revocable", + "revokeObjectURL", + "rgbColor", + "right", + "rightContext", + "rightDegrees", + "rightMargin", + "rightProjectionMatrix", + "rightViewMatrix", + "role", + "rolloffFactor", + "root", + "rootBounds", + "rootElement", + "rootMargin", + "rotate", + "rotateAxisAngle", + "rotateAxisAngleSelf", + "rotateFromVector", + "rotateFromVectorSelf", + "rotateSelf", + "rotation", + "rotationAngle", + "rotationRate", + "round", + "row-gap", + "rowGap", + "rowIndex", + "rowSpan", + "rows", + "rtcpTransport", + "rtt", + "ruby-align", + "ruby-position", + "rubyAlign", + "rubyOverhang", + "rubyPosition", + "rules", + "runtime", + "runtimeStyle", + "rx", + "ry", + "s", + "safari", + "sample", + "sampleCoverage", + "sampleRate", + "samplerParameterf", + "samplerParameteri", + "sandbox", + "save", + "saveData", + "scale", + "scale3d", + "scale3dSelf", + "scaleNonUniform", + "scaleNonUniformSelf", + "scaleSelf", + "scheme", + "scissor", + "scope", + "scopeName", + "scoped", + "screen", + "screenBrightness", + "screenEnabled", + "screenLeft", + "screenPixelToMillimeterX", + "screenPixelToMillimeterY", + "screenTop", + "screenX", + "screenY", + "scriptURL", + "scripts", + "scroll", + "scroll-behavior", + "scroll-margin", + "scroll-margin-block", + "scroll-margin-block-end", + "scroll-margin-block-start", + "scroll-margin-bottom", + "scroll-margin-inline", + "scroll-margin-inline-end", + "scroll-margin-inline-start", + "scroll-margin-left", + "scroll-margin-right", + "scroll-margin-top", + "scroll-padding", + "scroll-padding-block", + "scroll-padding-block-end", + "scroll-padding-block-start", + "scroll-padding-bottom", + "scroll-padding-inline", + "scroll-padding-inline-end", + "scroll-padding-inline-start", + "scroll-padding-left", + "scroll-padding-right", + "scroll-padding-top", + "scroll-snap-align", + "scroll-snap-type", + "scrollAmount", + "scrollBehavior", + "scrollBy", + "scrollByLines", + "scrollByPages", + "scrollDelay", + "scrollHeight", + "scrollIntoView", + "scrollIntoViewIfNeeded", + "scrollLeft", + "scrollLeftMax", + "scrollMargin", + "scrollMarginBlock", + "scrollMarginBlockEnd", + "scrollMarginBlockStart", + "scrollMarginBottom", + "scrollMarginInline", + "scrollMarginInlineEnd", + "scrollMarginInlineStart", + "scrollMarginLeft", + "scrollMarginRight", + "scrollMarginTop", + "scrollMaxX", + "scrollMaxY", + "scrollPadding", + "scrollPaddingBlock", + "scrollPaddingBlockEnd", + "scrollPaddingBlockStart", + "scrollPaddingBottom", + "scrollPaddingInline", + "scrollPaddingInlineEnd", + "scrollPaddingInlineStart", + "scrollPaddingLeft", + "scrollPaddingRight", + "scrollPaddingTop", + "scrollRestoration", + "scrollSnapAlign", + "scrollSnapType", + "scrollTo", + "scrollTop", + "scrollTopMax", + "scrollWidth", + "scrollX", + "scrollY", + "scrollbar-color", + "scrollbar-width", + "scrollbar3dLightColor", + "scrollbarArrowColor", + "scrollbarBaseColor", + "scrollbarColor", + "scrollbarDarkShadowColor", + "scrollbarFaceColor", + "scrollbarHighlightColor", + "scrollbarShadowColor", + "scrollbarTrackColor", + "scrollbarWidth", + "scrollbars", + "scrolling", + "scrollingElement", + "sctp", + "sctpCauseCode", + "sdp", + "sdpLineNumber", + "sdpMLineIndex", + "sdpMid", + "seal", + "search", + "searchBox", + "searchBoxJavaBridge_", + "searchParams", + "sectionRowIndex", + "secureConnectionStart", + "security", + "seed", + "seekToNextFrame", + "seekable", + "seeking", + "select", + "selectAllChildren", + "selectAlternateInterface", + "selectConfiguration", + "selectNode", + "selectNodeContents", + "selectNodes", + "selectSingleNode", + "selectSubString", + "selected", + "selectedIndex", + "selectedOptions", + "selectedStyleSheetSet", + "selectedStylesheetSet", + "selection", + "selectionDirection", + "selectionEnd", + "selectionStart", + "selector", + "selectorText", + "self", + "send", + "sendAsBinary", + "sendBeacon", + "sender", + "sentAlert", + "sentTimestamp", + "separator", + "serialNumber", + "serializeToString", + "serverTiming", + "service", + "serviceWorker", + "session", + "sessionId", + "sessionStorage", + "set", + "setActionHandler", + "setActive", + "setAlpha", + "setAppBadge", + "setAttribute", + "setAttributeNS", + "setAttributeNode", + "setAttributeNodeNS", + "setBaseAndExtent", + "setBigInt64", + "setBigUint64", + "setBingCurrentSearchDefault", + "setCapture", + "setCodecPreferences", + "setColor", + "setCompositeOperation", + "setConfiguration", + "setCurrentTime", + "setCustomValidity", + "setData", + "setDate", + "setDragImage", + "setEnd", + "setEndAfter", + "setEndBefore", + "setEndPoint", + "setFillColor", + "setFilterRes", + "setFloat32", + "setFloat64", + "setFloatValue", + "setFormValue", + "setFullYear", + "setHeaderValue", + "setHours", + "setIdentityProvider", + "setImmediate", + "setInt16", + "setInt32", + "setInt8", + "setInterval", + "setItem", + "setKeyframes", + "setLineCap", + "setLineDash", + "setLineJoin", + "setLineWidth", + "setLiveSeekableRange", + "setLocalDescription", + "setMatrix", + "setMatrixValue", + "setMediaKeys", + "setMilliseconds", + "setMinutes", + "setMiterLimit", + "setMonth", + "setNamedItem", + "setNamedItemNS", + "setNonUserCodeExceptions", + "setOrientToAngle", + "setOrientToAuto", + "setOrientation", + "setOverrideHistoryNavigationMode", + "setPaint", + "setParameter", + "setParameters", + "setPeriodicWave", + "setPointerCapture", + "setPosition", + "setPositionState", + "setPreference", + "setProperty", + "setPrototypeOf", + "setRGBColor", + "setRGBColorICCColor", + "setRadius", + "setRangeText", + "setRemoteDescription", + "setRequestHeader", + "setResizable", + "setResourceTimingBufferSize", + "setRotate", + "setScale", + "setSeconds", + "setSelectionRange", + "setServerCertificate", + "setShadow", + "setSinkId", + "setSkewX", + "setSkewY", + "setStart", + "setStartAfter", + "setStartBefore", + "setStdDeviation", + "setStreams", + "setStringValue", + "setStrokeColor", + "setSuggestResult", + "setTargetAtTime", + "setTargetValueAtTime", + "setTime", + "setTimeout", + "setTransform", + "setTranslate", + "setUTCDate", + "setUTCFullYear", + "setUTCHours", + "setUTCMilliseconds", + "setUTCMinutes", + "setUTCMonth", + "setUTCSeconds", + "setUint16", + "setUint32", + "setUint8", + "setUri", + "setValidity", + "setValueAtTime", + "setValueCurveAtTime", + "setVariable", + "setVelocity", + "setVersion", + "setYear", + "settingName", + "settingValue", + "sex", + "shaderSource", + "shadowBlur", + "shadowColor", + "shadowOffsetX", + "shadowOffsetY", + "shadowRoot", + "shape", + "shape-image-threshold", + "shape-margin", + "shape-outside", + "shape-rendering", + "shapeImageThreshold", + "shapeMargin", + "shapeOutside", + "shapeRendering", + "sheet", + "shift", + "shiftKey", + "shiftLeft", + "shippingAddress", + "shippingOption", + "shippingType", + "show", + "showHelp", + "showModal", + "showModalDialog", + "showModelessDialog", + "showNotification", + "sidebar", + "sign", + "signal", + "signalingState", + "signature", + "silent", + "sin", + "singleNodeValue", + "sinh", + "sinkId", + "sittingToStandingTransform", + "size", + "sizeToContent", + "sizeX", + "sizeZ", + "sizes", + "skewX", + "skewXSelf", + "skewY", + "skewYSelf", + "slice", + "slope", + "slot", + "small", + "smil", + "smooth", + "smoothingTimeConstant", + "snapToLines", + "snapshotItem", + "snapshotLength", + "some", + "sort", + "sortingCode", + "source", + "sourceBuffer", + "sourceBuffers", + "sourceCapabilities", + "sourceFile", + "sourceIndex", + "sources", + "spacing", + "span", + "speak", + "speakAs", + "speaking", + "species", + "specified", + "specularConstant", + "specularExponent", + "speechSynthesis", + "speed", + "speedOfSound", + "spellcheck", + "splice", + "split", + "splitText", + "spreadMethod", + "sqrt", + "src", + "srcElement", + "srcFilter", + "srcObject", + "srcUrn", + "srcdoc", + "srclang", + "srcset", + "stack", + "stackTraceLimit", + "stacktrace", + "stageParameters", + "standalone", + "standby", + "start", + "startContainer", + "startIce", + "startMessages", + "startNotifications", + "startOffset", + "startProfiling", + "startRendering", + "startShark", + "startTime", + "startsWith", + "state", + "status", + "statusCode", + "statusMessage", + "statusText", + "statusbar", + "stdDeviationX", + "stdDeviationY", + "stencilFunc", + "stencilFuncSeparate", + "stencilMask", + "stencilMaskSeparate", + "stencilOp", + "stencilOpSeparate", + "step", + "stepDown", + "stepMismatch", + "stepUp", + "sticky", + "stitchTiles", + "stop", + "stop-color", + "stop-opacity", + "stopColor", + "stopImmediatePropagation", + "stopNotifications", + "stopOpacity", + "stopProfiling", + "stopPropagation", + "stopShark", + "stopped", + "storage", + "storageArea", + "storageName", + "storageStatus", + "store", + "storeSiteSpecificTrackingException", + "storeWebWideTrackingException", + "stpVersion", + "stream", + "streams", + "stretch", + "strike", + "string", + "stringValue", + "stringify", + "stroke", + "stroke-dasharray", + "stroke-dashoffset", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-opacity", + "stroke-width", + "strokeDasharray", + "strokeDashoffset", + "strokeLinecap", + "strokeLinejoin", + "strokeMiterlimit", + "strokeOpacity", + "strokeRect", + "strokeStyle", + "strokeText", + "strokeWidth", + "style", + "styleFloat", + "styleMap", + "styleMedia", + "styleSheet", + "styleSheetSets", + "styleSheets", + "sub", + "subarray", + "subject", + "submit", + "submitFrame", + "submitter", + "subscribe", + "substr", + "substring", + "substringData", + "subtle", + "subtree", + "suffix", + "suffixes", + "summary", + "sup", + "supported", + "supportedContentEncodings", + "supportedEntryTypes", + "supports", + "supportsSession", + "surfaceScale", + "surroundContents", + "suspend", + "suspendRedraw", + "swapCache", + "swapNode", + "sweepFlag", + "symbols", + "sync", + "sysexEnabled", + "system", + "systemCode", + "systemId", + "systemLanguage", + "systemXDPI", + "systemYDPI", + "tBodies", + "tFoot", + "tHead", + "tabIndex", + "table", + "table-layout", + "tableLayout", + "tableValues", + "tag", + "tagName", + "tagUrn", + "tags", + "taintEnabled", + "takePhoto", + "takeRecords", + "tan", + "tangentialPressure", + "tanh", + "target", + "targetElement", + "targetRayMode", + "targetRaySpace", + "targetTouches", + "targetX", + "targetY", + "tcpType", + "tee", + "tel", + "terminate", + "test", + "texImage2D", + "texImage3D", + "texParameterf", + "texParameteri", + "texStorage2D", + "texStorage3D", + "texSubImage2D", + "texSubImage3D", + "text", + "text-align", + "text-align-last", + "text-anchor", + "text-combine-upright", + "text-decoration", + "text-decoration-color", + "text-decoration-line", + "text-decoration-skip-ink", + "text-decoration-style", + "text-decoration-thickness", + "text-emphasis", + "text-emphasis-color", + "text-emphasis-position", + "text-emphasis-style", + "text-indent", + "text-justify", + "text-orientation", + "text-overflow", + "text-rendering", + "text-shadow", + "text-transform", + "text-underline-offset", + "text-underline-position", + "textAlign", + "textAlignLast", + "textAnchor", + "textAutospace", + "textBaseline", + "textCombineUpright", + "textContent", + "textDecoration", + "textDecorationBlink", + "textDecorationColor", + "textDecorationLine", + "textDecorationLineThrough", + "textDecorationNone", + "textDecorationOverline", + "textDecorationSkipInk", + "textDecorationStyle", + "textDecorationThickness", + "textDecorationUnderline", + "textEmphasis", + "textEmphasisColor", + "textEmphasisPosition", + "textEmphasisStyle", + "textIndent", + "textJustify", + "textJustifyTrim", + "textKashida", + "textKashidaSpace", + "textLength", + "textOrientation", + "textOverflow", + "textRendering", + "textShadow", + "textTracks", + "textTransform", + "textUnderlineOffset", + "textUnderlinePosition", + "then", + "threadId", + "threshold", + "thresholds", + "tiltX", + "tiltY", + "time", + "timeEnd", + "timeLog", + "timeOrigin", + "timeRemaining", + "timeStamp", + "timecode", + "timeline", + "timelineTime", + "timeout", + "timestamp", + "timestampOffset", + "timing", + "title", + "to", + "toArray", + "toBlob", + "toDataURL", + "toDateString", + "toElement", + "toExponential", + "toFixed", + "toFloat32Array", + "toFloat64Array", + "toGMTString", + "toISOString", + "toJSON", + "toLocaleDateString", + "toLocaleFormat", + "toLocaleLowerCase", + "toLocaleString", + "toLocaleTimeString", + "toLocaleUpperCase", + "toLowerCase", + "toMatrix", + "toMethod", + "toPrecision", + "toPrimitive", + "toSdp", + "toSource", + "toStaticHTML", + "toString", + "toStringTag", + "toSum", + "toTimeString", + "toUTCString", + "toUpperCase", + "toggle", + "toggleAttribute", + "toggleLongPressEnabled", + "tone", + "toneBuffer", + "tooLong", + "tooShort", + "toolbar", + "top", + "topMargin", + "total", + "totalFrameDelay", + "totalVideoFrames", + "touch-action", + "touchAction", + "touched", + "touches", + "trace", + "track", + "trackVisibility", + "transaction", + "transactions", + "transceiver", + "transferControlToOffscreen", + "transferFromImageBitmap", + "transferImageBitmap", + "transferIn", + "transferOut", + "transferSize", + "transferToImageBitmap", + "transform", + "transform-box", + "transform-origin", + "transform-style", + "transformBox", + "transformFeedbackVaryings", + "transformOrigin", + "transformPoint", + "transformString", + "transformStyle", + "transformToDocument", + "transformToFragment", + "transition", + "transition-delay", + "transition-duration", + "transition-property", + "transition-timing-function", + "transitionDelay", + "transitionDuration", + "transitionProperty", + "transitionTimingFunction", + "translate", + "translateSelf", + "translationX", + "translationY", + "transport", + "trim", + "trimEnd", + "trimLeft", + "trimRight", + "trimStart", + "trueSpeed", + "trunc", + "truncate", + "trustedTypes", + "turn", + "twist", + "type", + "typeDetail", + "typeMismatch", + "typeMustMatch", + "types", + "u2f", + "ubound", + "uint16", + "uint32", + "uint8", + "uint8Clamped", + "undefined", + "unescape", + "uneval", + "unicode", + "unicode-bidi", + "unicodeBidi", + "unicodeRange", + "uniform1f", + "uniform1fv", + "uniform1i", + "uniform1iv", + "uniform1ui", + "uniform1uiv", + "uniform2f", + "uniform2fv", + "uniform2i", + "uniform2iv", + "uniform2ui", + "uniform2uiv", + "uniform3f", + "uniform3fv", + "uniform3i", + "uniform3iv", + "uniform3ui", + "uniform3uiv", + "uniform4f", + "uniform4fv", + "uniform4i", + "uniform4iv", + "uniform4ui", + "uniform4uiv", + "uniformBlockBinding", + "uniformMatrix2fv", + "uniformMatrix2x3fv", + "uniformMatrix2x4fv", + "uniformMatrix3fv", + "uniformMatrix3x2fv", + "uniformMatrix3x4fv", + "uniformMatrix4fv", + "uniformMatrix4x2fv", + "uniformMatrix4x3fv", + "unique", + "uniqueID", + "uniqueNumber", + "unit", + "unitType", + "units", + "unloadEventEnd", + "unloadEventStart", + "unlock", + "unmount", + "unobserve", + "unpause", + "unpauseAnimations", + "unreadCount", + "unregister", + "unregisterContentHandler", + "unregisterProtocolHandler", + "unscopables", + "unselectable", + "unshift", + "unsubscribe", + "unsuspendRedraw", + "unsuspendRedrawAll", + "unwatch", + "unwrapKey", + "upDegrees", + "upX", + "upY", + "upZ", + "update", + "updateCommands", + "updateIce", + "updateInterval", + "updatePlaybackRate", + "updateRenderState", + "updateSettings", + "updateTiming", + "updateViaCache", + "updateWith", + "updated", + "updating", + "upgrade", + "upload", + "uploadTotal", + "uploaded", + "upper", + "upperBound", + "upperOpen", + "uri", + "url", + "urn", + "urns", + "usages", + "usb", + "usbVersionMajor", + "usbVersionMinor", + "usbVersionSubminor", + "useCurrentView", + "useMap", + "useProgram", + "usedSpace", + "user-select", + "userActivation", + "userAgent", + "userChoice", + "userHandle", + "userHint", + "userLanguage", + "userSelect", + "userVisibleOnly", + "username", + "usernameFragment", + "utterance", + "uuid", + "v8BreakIterator", + "vAlign", + "vLink", + "valid", + "validate", + "validateProgram", + "validationMessage", + "validity", + "value", + "valueAsDate", + "valueAsNumber", + "valueAsString", + "valueInSpecifiedUnits", + "valueMissing", + "valueOf", + "valueText", + "valueType", + "values", + "variable", + "variant", + "variationSettings", + "vector-effect", + "vectorEffect", + "velocityAngular", + "velocityExpansion", + "velocityX", + "velocityY", + "vendor", + "vendorId", + "vendorSub", + "verify", + "version", + "vertexAttrib1f", + "vertexAttrib1fv", + "vertexAttrib2f", + "vertexAttrib2fv", + "vertexAttrib3f", + "vertexAttrib3fv", + "vertexAttrib4f", + "vertexAttrib4fv", + "vertexAttribDivisor", + "vertexAttribDivisorANGLE", + "vertexAttribI4i", + "vertexAttribI4iv", + "vertexAttribI4ui", + "vertexAttribI4uiv", + "vertexAttribIPointer", + "vertexAttribPointer", + "vertical", + "vertical-align", + "verticalAlign", + "verticalOverflow", + "vh", + "vibrate", + "vibrationActuator", + "videoBitsPerSecond", + "videoHeight", + "videoTracks", + "videoWidth", + "view", + "viewBox", + "viewBoxString", + "viewTarget", + "viewTargetString", + "viewport", + "viewportAnchorX", + "viewportAnchorY", + "viewportElement", + "views", + "violatedDirective", + "visibility", + "visibilityState", + "visible", + "visualViewport", + "vlinkColor", + "vmax", + "vmin", + "voice", + "voiceURI", + "volume", + "vrml", + "vspace", + "vw", + "w", + "wait", + "waitSync", + "waiting", + "wake", + "wakeLock", + "wand", + "warn", + "wasClean", + "wasDiscarded", + "watch", + "watchAvailability", + "watchPosition", + "webdriver", + "webkitAddKey", + "webkitAlignContent", + "webkitAlignItems", + "webkitAlignSelf", + "webkitAnimation", + "webkitAnimationDelay", + "webkitAnimationDirection", + "webkitAnimationDuration", + "webkitAnimationFillMode", + "webkitAnimationIterationCount", + "webkitAnimationName", + "webkitAnimationPlayState", + "webkitAnimationTimingFunction", + "webkitAppearance", + "webkitAudioContext", + "webkitAudioDecodedByteCount", + "webkitAudioPannerNode", + "webkitBackfaceVisibility", + "webkitBackground", + "webkitBackgroundAttachment", + "webkitBackgroundClip", + "webkitBackgroundColor", + "webkitBackgroundImage", + "webkitBackgroundOrigin", + "webkitBackgroundPosition", + "webkitBackgroundPositionX", + "webkitBackgroundPositionY", + "webkitBackgroundRepeat", + "webkitBackgroundSize", + "webkitBackingStorePixelRatio", + "webkitBorderBottomLeftRadius", + "webkitBorderBottomRightRadius", + "webkitBorderImage", + "webkitBorderImageOutset", + "webkitBorderImageRepeat", + "webkitBorderImageSlice", + "webkitBorderImageSource", + "webkitBorderImageWidth", + "webkitBorderRadius", + "webkitBorderTopLeftRadius", + "webkitBorderTopRightRadius", + "webkitBoxAlign", + "webkitBoxDirection", + "webkitBoxFlex", + "webkitBoxOrdinalGroup", + "webkitBoxOrient", + "webkitBoxPack", + "webkitBoxShadow", + "webkitBoxSizing", + "webkitCancelAnimationFrame", + "webkitCancelFullScreen", + "webkitCancelKeyRequest", + "webkitCancelRequestAnimationFrame", + "webkitClearResourceTimings", + "webkitClosedCaptionsVisible", + "webkitConvertPointFromNodeToPage", + "webkitConvertPointFromPageToNode", + "webkitCreateShadowRoot", + "webkitCurrentFullScreenElement", + "webkitCurrentPlaybackTargetIsWireless", + "webkitDecodedFrameCount", + "webkitDirectionInvertedFromDevice", + "webkitDisplayingFullscreen", + "webkitDroppedFrameCount", + "webkitEnterFullScreen", + "webkitEnterFullscreen", + "webkitEntries", + "webkitExitFullScreen", + "webkitExitFullscreen", + "webkitExitPointerLock", + "webkitFilter", + "webkitFlex", + "webkitFlexBasis", + "webkitFlexDirection", + "webkitFlexFlow", + "webkitFlexGrow", + "webkitFlexShrink", + "webkitFlexWrap", + "webkitFullScreenKeyboardInputAllowed", + "webkitFullscreenElement", + "webkitFullscreenEnabled", + "webkitGenerateKeyRequest", + "webkitGetAsEntry", + "webkitGetDatabaseNames", + "webkitGetEntries", + "webkitGetEntriesByName", + "webkitGetEntriesByType", + "webkitGetFlowByName", + "webkitGetGamepads", + "webkitGetImageDataHD", + "webkitGetNamedFlows", + "webkitGetRegionFlowRanges", + "webkitGetUserMedia", + "webkitHasClosedCaptions", + "webkitHidden", + "webkitIDBCursor", + "webkitIDBDatabase", + "webkitIDBDatabaseError", + "webkitIDBDatabaseException", + "webkitIDBFactory", + "webkitIDBIndex", + "webkitIDBKeyRange", + "webkitIDBObjectStore", + "webkitIDBRequest", + "webkitIDBTransaction", + "webkitImageSmoothingEnabled", + "webkitIndexedDB", + "webkitInitMessageEvent", + "webkitIsFullScreen", + "webkitJustifyContent", + "webkitKeys", + "webkitLineClamp", + "webkitLineDashOffset", + "webkitLockOrientation", + "webkitMask", + "webkitMaskClip", + "webkitMaskComposite", + "webkitMaskImage", + "webkitMaskOrigin", + "webkitMaskPosition", + "webkitMaskPositionX", + "webkitMaskPositionY", + "webkitMaskRepeat", + "webkitMaskSize", + "webkitMatchesSelector", + "webkitMediaStream", + "webkitNotifications", + "webkitOfflineAudioContext", + "webkitOrder", + "webkitOrientation", + "webkitPeerConnection00", + "webkitPersistentStorage", + "webkitPerspective", + "webkitPerspectiveOrigin", + "webkitPointerLockElement", + "webkitPostMessage", + "webkitPreservesPitch", + "webkitPutImageDataHD", + "webkitRTCPeerConnection", + "webkitRegionOverset", + "webkitRelativePath", + "webkitRequestAnimationFrame", + "webkitRequestFileSystem", + "webkitRequestFullScreen", + "webkitRequestFullscreen", + "webkitRequestPointerLock", + "webkitResolveLocalFileSystemURL", + "webkitSetMediaKeys", + "webkitSetResourceTimingBufferSize", + "webkitShadowRoot", + "webkitShowPlaybackTargetPicker", + "webkitSlice", + "webkitSpeechGrammar", + "webkitSpeechGrammarList", + "webkitSpeechRecognition", + "webkitSpeechRecognitionError", + "webkitSpeechRecognitionEvent", + "webkitStorageInfo", + "webkitSupportsFullscreen", + "webkitTemporaryStorage", + "webkitTextFillColor", + "webkitTextSizeAdjust", + "webkitTextStroke", + "webkitTextStrokeColor", + "webkitTextStrokeWidth", + "webkitTransform", + "webkitTransformOrigin", + "webkitTransformStyle", + "webkitTransition", + "webkitTransitionDelay", + "webkitTransitionDuration", + "webkitTransitionProperty", + "webkitTransitionTimingFunction", + "webkitURL", + "webkitUnlockOrientation", + "webkitUserSelect", + "webkitVideoDecodedByteCount", + "webkitVisibilityState", + "webkitWirelessVideoPlaybackDisabled", + "webkitdirectory", + "webkitdropzone", + "webstore", + "weight", + "whatToShow", + "wheelDelta", + "wheelDeltaX", + "wheelDeltaY", + "whenDefined", + "which", + "white-space", + "whiteSpace", + "wholeText", + "widows", + "width", + "will-change", + "willChange", + "willValidate", + "window", + "withCredentials", + "word-break", + "word-spacing", + "word-wrap", + "wordBreak", + "wordSpacing", + "wordWrap", + "workerStart", + "wrap", + "wrapKey", + "writable", + "writableAuxiliaries", + "write", + "writeText", + "writeValue", + "writeWithoutResponse", + "writeln", + "writing-mode", + "writingMode", + "x", + "x1", + "x2", + "xChannelSelector", + "xmlEncoding", + "xmlStandalone", + "xmlVersion", + "xmlbase", + "xmllang", + "xmlspace", + "xor", + "xr", + "y", + "y1", + "y2", + "yChannelSelector", + "yandex", + "z", + "z-index", + "zIndex", + "zoom", + "zoomAndPan", + "zoomRectScreen", +]; diff --git a/node_modules/mathjs/examples/node_modules/terser/tools/exit.cjs b/node_modules/mathjs/examples/node_modules/terser/tools/exit.cjs new file mode 100644 index 0000000..46a970b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/tools/exit.cjs @@ -0,0 +1,7 @@ +// workaround for tty output truncation upon process.exit() +// https://github.com/nodejs/node/issues/6456 + +[process.stdout, process.stderr].forEach((s) => { + s && s.isTTY && s._handle && s._handle.setBlocking && + s._handle.setBlocking(true) +}); diff --git a/node_modules/mathjs/examples/node_modules/terser/tools/props.html b/node_modules/mathjs/examples/node_modules/terser/tools/props.html new file mode 100644 index 0000000..eeae8a6 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/tools/props.html @@ -0,0 +1,55 @@ + + + + + + + diff --git a/node_modules/mathjs/examples/node_modules/terser/tools/terser.d.ts b/node_modules/mathjs/examples/node_modules/terser/tools/terser.d.ts new file mode 100644 index 0000000..af7c94d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/terser/tools/terser.d.ts @@ -0,0 +1,207 @@ +/// + +import { RawSourceMap } from 'source-map'; + +export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020; + +export interface ParseOptions { + bare_returns?: boolean; + ecma?: ECMA; + html5_comments?: boolean; + shebang?: boolean; +} + +export interface CompressOptions { + arguments?: boolean; + arrows?: boolean; + booleans_as_integers?: boolean; + booleans?: boolean; + collapse_vars?: boolean; + comparisons?: boolean; + computed_props?: boolean; + conditionals?: boolean; + dead_code?: boolean; + defaults?: boolean; + directives?: boolean; + drop_console?: boolean; + drop_debugger?: boolean; + ecma?: ECMA; + evaluate?: boolean; + expression?: boolean; + global_defs?: object; + hoist_funs?: boolean; + hoist_props?: boolean; + hoist_vars?: boolean; + ie8?: boolean; + if_return?: boolean; + inline?: boolean | InlineFunctions; + join_vars?: boolean; + keep_classnames?: boolean | RegExp; + keep_fargs?: boolean; + keep_fnames?: boolean | RegExp; + keep_infinity?: boolean; + loops?: boolean; + module?: boolean; + negate_iife?: boolean; + passes?: number; + properties?: boolean; + pure_funcs?: string[]; + pure_getters?: boolean | 'strict'; + reduce_funcs?: boolean; + reduce_vars?: boolean; + sequences?: boolean | number; + side_effects?: boolean; + switches?: boolean; + toplevel?: boolean; + top_retain?: null | string | string[] | RegExp; + typeofs?: boolean; + unsafe_arrows?: boolean; + unsafe?: boolean; + unsafe_comps?: boolean; + unsafe_Function?: boolean; + unsafe_math?: boolean; + unsafe_symbols?: boolean; + unsafe_methods?: boolean; + unsafe_proto?: boolean; + unsafe_regexp?: boolean; + unsafe_undefined?: boolean; + unused?: boolean; +} + +export enum InlineFunctions { + Disabled = 0, + SimpleFunctions = 1, + WithArguments = 2, + WithArgumentsAndVariables = 3 +} + +export interface MangleOptions { + eval?: boolean; + keep_classnames?: boolean | RegExp; + keep_fnames?: boolean | RegExp; + module?: boolean; + nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler; + properties?: boolean | ManglePropertiesOptions; + reserved?: string[]; + safari10?: boolean; + toplevel?: boolean; +} + +/** + * An identifier mangler for which the output is invariant with respect to the source code. + */ +export interface SimpleIdentifierMangler { + /** + * Obtains the nth most favored (usually shortest) identifier to rename a variable to. + * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word. + * This function is expected to be stable; Evaluating get(n) === get(n) should always return true. + * @param n The ordinal of the identifier. + */ + get(n: number): string; +} + +/** + * An identifier mangler that leverages character frequency analysis to determine identifier precedence. + */ +export interface WeightedIdentifierMangler extends SimpleIdentifierMangler { + /** + * Modifies the internal weighting of the input characters by the specified delta. + * Will be invoked on the entire printed AST, and then deduct mangleable identifiers. + * @param chars The characters to modify the weighting of. + * @param delta The numeric weight to add to the characters. + */ + consider(chars: string, delta: number): number; + /** + * Resets character weights. + */ + reset(): void; + /** + * Sorts identifiers by character frequency, in preparation for calls to get(n). + */ + sort(): void; +} + +export interface ManglePropertiesOptions { + builtins?: boolean; + debug?: boolean; + keep_quoted?: boolean | 'strict'; + nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler; + regex?: RegExp | string; + reserved?: string[]; +} + +export interface FormatOptions { + ascii_only?: boolean; + /** @deprecated Not implemented anymore */ + beautify?: boolean; + braces?: boolean; + comments?: boolean | 'all' | 'some' | RegExp | ( (node: any, comment: { + value: string, + type: 'comment1' | 'comment2' | 'comment3' | 'comment4', + pos: number, + line: number, + col: number, + }) => boolean ); + ecma?: ECMA; + ie8?: boolean; + indent_level?: number; + indent_start?: number; + inline_script?: boolean; + keep_quoted_props?: boolean; + max_line_len?: number | false; + preamble?: string; + preserve_annotations?: boolean; + quote_keys?: boolean; + quote_style?: OutputQuoteStyle; + safari10?: boolean; + semicolons?: boolean; + shebang?: boolean; + shorthand?: boolean; + source_map?: SourceMapOptions; + webkit?: boolean; + width?: number; + wrap_iife?: boolean; + wrap_func_args?: boolean; +} + +export enum OutputQuoteStyle { + PreferDouble = 0, + AlwaysSingle = 1, + AlwaysDouble = 2, + AlwaysOriginal = 3 +} + +export interface MinifyOptions { + compress?: boolean | CompressOptions; + ecma?: ECMA; + enclose?: boolean | string; + ie8?: boolean; + keep_classnames?: boolean | RegExp; + keep_fnames?: boolean | RegExp; + mangle?: boolean | MangleOptions; + module?: boolean; + nameCache?: object; + format?: FormatOptions; + /** @deprecated */ + output?: FormatOptions; + parse?: ParseOptions; + safari10?: boolean; + sourceMap?: boolean | SourceMapOptions; + toplevel?: boolean; +} + +export interface MinifyOutput { + code?: string; + map?: RawSourceMap | string; +} + +export interface SourceMapOptions { + /** Source map object, 'inline' or source map file content */ + content?: RawSourceMap | string; + includeSources?: boolean; + filename?: string; + root?: string; + url?: string | 'inline'; +} + +export function minify(files: string | string[] | { [file: string]: string }, options?: MinifyOptions): Promise; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/LICENSE b/node_modules/mathjs/examples/node_modules/uri-js/LICENSE new file mode 100644 index 0000000..9338bde --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/LICENSE @@ -0,0 +1,11 @@ +Copyright 2011 Gary Court. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY GARY COURT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Gary Court. diff --git a/node_modules/mathjs/examples/node_modules/uri-js/README.md b/node_modules/mathjs/examples/node_modules/uri-js/README.md new file mode 100644 index 0000000..43e648b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/README.md @@ -0,0 +1,203 @@ +# URI.js + +URI.js is an [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) compliant, scheme extendable URI parsing/validating/resolving library for all JavaScript environments (browsers, Node.js, etc). +It is also compliant with the IRI ([RFC 3987](http://www.ietf.org/rfc/rfc3987.txt)), IDNA ([RFC 5890](http://www.ietf.org/rfc/rfc5890.txt)), IPv6 Address ([RFC 5952](http://www.ietf.org/rfc/rfc5952.txt)), IPv6 Zone Identifier ([RFC 6874](http://www.ietf.org/rfc/rfc6874.txt)) specifications. + +URI.js has an extensive test suite, and works in all (Node.js, web) environments. It weighs in at 6.4kb (gzipped, 17kb deflated). + +## API + +### Parsing + + URI.parse("uri://user:pass@example.com:123/one/two.three?q1=a1&q2=a2#body"); + //returns: + //{ + // scheme : "uri", + // userinfo : "user:pass", + // host : "example.com", + // port : 123, + // path : "/one/two.three", + // query : "q1=a1&q2=a2", + // fragment : "body" + //} + +### Serializing + + URI.serialize({scheme : "http", host : "example.com", fragment : "footer"}) === "http://example.com/#footer" + +### Resolving + + URI.resolve("uri://a/b/c/d?q", "../../g") === "uri://a/g" + +### Normalizing + + URI.normalize("HTTP://ABC.com:80/%7Esmith/home.html") === "http://abc.com/~smith/home.html" + +### Comparison + + URI.equal("example://a/b/c/%7Bfoo%7D", "eXAMPLE://a/./b/../b/%63/%7bfoo%7d") === true + +### IP Support + + //IPv4 normalization + URI.normalize("//192.068.001.000") === "//192.68.1.0" + + //IPv6 normalization + URI.normalize("//[2001:0:0DB8::0:0001]") === "//[2001:0:db8::1]" + + //IPv6 zone identifier support + URI.parse("//[2001:db8::7%25en1]"); + //returns: + //{ + // host : "2001:db8::7%en1" + //} + +### IRI Support + + //convert IRI to URI + URI.serialize(URI.parse("http://examplé.org/rosé")) === "http://xn--exampl-gva.org/ros%C3%A9" + //convert URI to IRI + URI.serialize(URI.parse("http://xn--exampl-gva.org/ros%C3%A9"), {iri:true}) === "http://examplé.org/rosé" + +### Options + +All of the above functions can accept an additional options argument that is an object that can contain one or more of the following properties: + +* `scheme` (string) + + Indicates the scheme that the URI should be treated as, overriding the URI's normal scheme parsing behavior. + +* `reference` (string) + + If set to `"suffix"`, it indicates that the URI is in the suffix format, and the validator will use the option's `scheme` property to determine the URI's scheme. + +* `tolerant` (boolean, false) + + If set to `true`, the parser will relax URI resolving rules. + +* `absolutePath` (boolean, false) + + If set to `true`, the serializer will not resolve a relative `path` component. + +* `iri` (boolean, false) + + If set to `true`, the serializer will unescape non-ASCII characters as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). + +* `unicodeSupport` (boolean, false) + + If set to `true`, the parser will unescape non-ASCII characters in the parsed output as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). + +* `domainHost` (boolean, false) + + If set to `true`, the library will treat the `host` component as a domain name, and convert IDNs (International Domain Names) as per [RFC 5891](http://www.ietf.org/rfc/rfc5891.txt). + +## Scheme Extendable + +URI.js supports inserting custom [scheme](http://en.wikipedia.org/wiki/URI_scheme) dependent processing rules. Currently, URI.js has built in support for the following schemes: + +* http \[[RFC 2616](http://www.ietf.org/rfc/rfc2616.txt)\] +* https \[[RFC 2818](http://www.ietf.org/rfc/rfc2818.txt)\] +* ws \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] +* wss \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] +* mailto \[[RFC 6068](http://www.ietf.org/rfc/rfc6068.txt)\] +* urn \[[RFC 2141](http://www.ietf.org/rfc/rfc2141.txt)\] +* urn:uuid \[[RFC 4122](http://www.ietf.org/rfc/rfc4122.txt)\] + +### HTTP/HTTPS Support + + URI.equal("HTTP://ABC.COM:80", "http://abc.com/") === true + URI.equal("https://abc.com", "HTTPS://ABC.COM:443/") === true + +### WS/WSS Support + + URI.parse("wss://example.com/foo?bar=baz"); + //returns: + //{ + // scheme : "wss", + // host: "example.com", + // resourceName: "/foo?bar=baz", + // secure: true, + //} + + URI.equal("WS://ABC.COM:80/chat#one", "ws://abc.com/chat") === true + +### Mailto Support + + URI.parse("mailto:alpha@example.com,bravo@example.com?subject=SUBSCRIBE&body=Sign%20me%20up!"); + //returns: + //{ + // scheme : "mailto", + // to : ["alpha@example.com", "bravo@example.com"], + // subject : "SUBSCRIBE", + // body : "Sign me up!" + //} + + URI.serialize({ + scheme : "mailto", + to : ["alpha@example.com"], + subject : "REMOVE", + body : "Please remove me", + headers : { + cc : "charlie@example.com" + } + }) === "mailto:alpha@example.com?cc=charlie@example.com&subject=REMOVE&body=Please%20remove%20me" + +### URN Support + + URI.parse("urn:example:foo"); + //returns: + //{ + // scheme : "urn", + // nid : "example", + // nss : "foo", + //} + +#### URN UUID Support + + URI.parse("urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); + //returns: + //{ + // scheme : "urn", + // nid : "uuid", + // uuid : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", + //} + +## Usage + +To load in a browser, use the following tag: + + + +To load in a CommonJS/Module environment, first install with npm/yarn by running on the command line: + + npm install uri-js + # OR + yarn add uri-js + +Then, in your code, load it using: + + const URI = require("uri-js"); + +If you are writing your code in ES6+ (ESNEXT) or TypeScript, you would load it using: + + import * as URI from "uri-js"; + +Or you can load just what you need using named exports: + + import { parse, serialize, resolve, resolveComponents, normalize, equal, removeDotSegments, pctEncChar, pctDecChars, escapeComponent, unescapeComponent } from "uri-js"; + +## Breaking changes + +### Breaking changes from 3.x + +URN parsing has been completely changed to better align with the specification. Scheme is now always `urn`, but has two new properties: `nid` which contains the Namspace Identifier, and `nss` which contains the Namespace Specific String. The `nss` property will be removed by higher order scheme handlers, such as the UUID URN scheme handler. + +The UUID of a URN can now be found in the `uuid` property. + +### Breaking changes from 2.x + +URI validation has been removed as it was slow, exposed a vulnerabilty, and was generally not useful. + +### Breaking changes from 1.x + +The `errors` array on parsed components is now an `error` string. diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.d.ts new file mode 100644 index 0000000..da51e23 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.d.ts @@ -0,0 +1,59 @@ +export interface URIComponents { + scheme?: string; + userinfo?: string; + host?: string; + port?: number | string; + path?: string; + query?: string; + fragment?: string; + reference?: string; + error?: string; +} +export interface URIOptions { + scheme?: string; + reference?: string; + tolerant?: boolean; + absolutePath?: boolean; + iri?: boolean; + unicodeSupport?: boolean; + domainHost?: boolean; +} +export interface URISchemeHandler { + scheme: string; + parse(components: ParentComponents, options: Options): Components; + serialize(components: Components, options: Options): ParentComponents; + unicodeSupport?: boolean; + domainHost?: boolean; + absolutePath?: boolean; +} +export interface URIRegExps { + NOT_SCHEME: RegExp; + NOT_USERINFO: RegExp; + NOT_HOST: RegExp; + NOT_PATH: RegExp; + NOT_PATH_NOSCHEME: RegExp; + NOT_QUERY: RegExp; + NOT_FRAGMENT: RegExp; + ESCAPE: RegExp; + UNRESERVED: RegExp; + OTHER_CHARS: RegExp; + PCT_ENCODED: RegExp; + IPV4ADDRESS: RegExp; + IPV6ADDRESS: RegExp; +} +export declare const SCHEMES: { + [scheme: string]: URISchemeHandler; +}; +export declare function pctEncChar(chr: string): string; +export declare function pctDecChars(str: string): string; +export declare function parse(uriString: string, options?: URIOptions): URIComponents; +export declare function removeDotSegments(input: string): string; +export declare function serialize(components: URIComponents, options?: URIOptions): string; +export declare function resolveComponents(base: URIComponents, relative: URIComponents, options?: URIOptions, skipNormalization?: boolean): URIComponents; +export declare function resolve(baseURI: string, relativeURI: string, options?: URIOptions): string; +export declare function normalize(uri: string, options?: URIOptions): string; +export declare function normalize(uri: URIComponents, options?: URIOptions): URIComponents; +export declare function equal(uriA: string, uriB: string, options?: URIOptions): boolean; +export declare function equal(uriA: URIComponents, uriB: URIComponents, options?: URIOptions): boolean; +export declare function escapeComponent(str: string, options?: URIOptions): string; +export declare function unescapeComponent(str: string, options?: URIOptions): string; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.js new file mode 100644 index 0000000..0706116 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.js @@ -0,0 +1,1443 @@ +/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.URI = global.URI || {}))); +}(this, (function (exports) { 'use strict'; + +function merge() { + for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { + sets[_key] = arguments[_key]; + } + + if (sets.length > 1) { + sets[0] = sets[0].slice(0, -1); + var xl = sets.length - 1; + for (var x = 1; x < xl; ++x) { + sets[x] = sets[x].slice(1, -1); + } + sets[xl] = sets[xl].slice(1); + return sets.join(''); + } else { + return sets[0]; + } +} +function subexp(str) { + return "(?:" + str + ")"; +} +function typeOf(o) { + return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); +} +function toUpperCase(str) { + return str.toUpperCase(); +} +function toArray(obj) { + return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; +} +function assign(target, source) { + var obj = target; + if (source) { + for (var key in source) { + obj[key] = source[key]; + } + } + return obj; +} + +function buildExps(isIRI) { + var ALPHA$$ = "[A-Za-z]", + CR$ = "[\\x0D]", + DIGIT$$ = "[0-9]", + DQUOTE$$ = "[\\x22]", + HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), + //case-insensitive + LF$$ = "[\\x0A]", + SP$$ = "[\\x20]", + PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), + //expanded + GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", + SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", + RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), + UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", + //subset, excludes bidi control characters + IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", + //subset + UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), + SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), + USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), + DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), + DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), + //relaxed parsing rules + IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), + H16$ = subexp(HEXDIG$$ + "{1,4}"), + LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), + IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), + // 6( h16 ":" ) ls32 + IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), + // "::" 5( h16 ":" ) ls32 + IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), + //[ h16 ] "::" 4( h16 ":" ) ls32 + IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), + //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), + //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), + //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), + //[ *4( h16 ":" ) h16 ] "::" ls32 + IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), + //[ *5( h16 ":" ) h16 ] "::" h16 + IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), + //[ *6( h16 ":" ) h16 ] "::" + IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), + ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), + //RFC 6874 + IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), + //RFC 6874 + IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), + //RFC 6874, with relaxed parsing rules + IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), + IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), + //RFC 6874 + REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), + HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), + PORT$ = subexp(DIGIT$$ + "*"), + AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), + PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), + SEGMENT$ = subexp(PCHAR$ + "*"), + SEGMENT_NZ$ = subexp(PCHAR$ + "+"), + SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), + PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), + PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), + //simplified + PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), + //simplified + PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), + //simplified + PATH_EMPTY$ = "(?!" + PCHAR$ + ")", + PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), + FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), + HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), + RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), + ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), + GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", + SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; + return { + NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), + NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), + NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), + ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), + UNRESERVED: new RegExp(UNRESERVED$$, "g"), + OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), + PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), + IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), + IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules + }; +} +var URI_PROTOCOL = buildExps(false); + +var IRI_PROTOCOL = buildExps(true); + +var slicedToArray = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if (Symbol.iterator in Object(arr)) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); + + + + + + + + + + + + + +var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); + } +}; + +/** Highest positive signed 32-bit float value */ + +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +var base = 36; +var tMin = 1; +var tMax = 26; +var skew = 38; +var damp = 700; +var initialBias = 72; +var initialN = 128; // 0x80 +var delimiter = '-'; // '\x2D' + +/** Regular expressions */ +var regexPunycode = /^xn--/; +var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error$1(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + var result = []; + var length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + var output = []; + var counter = 0; + var length = string.length; + while (counter < length) { + var value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +var ucs2encode = function ucs2encode(array) { + return String.fromCodePoint.apply(String, toConsumableArray(array)); +}; + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +var basicToDigit = function basicToDigit(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +var digitToBasic = function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +var adapt = function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +var decode = function decode(input) { + // Don't use UCS-2. + var output = []; + var inputLength = input.length; + var i = 0; + var n = initialN; + var bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + var basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (var j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error$1('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + var oldi = i; + for (var w = 1, k = base;; /* no condition */k += base) { + + if (index >= inputLength) { + error$1('invalid-input'); + } + + var digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error$1('overflow'); + } + + i += digit * w; + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + + if (digit < t) { + break; + } + + var baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error$1('overflow'); + } + + w *= baseMinusT; + } + + var out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error$1('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + + return String.fromCodePoint.apply(String, output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +var encode = function encode(input) { + var output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + var inputLength = input.length; + + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; + + // Handle the basic code points. + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _currentValue2 = _step.value; + + if (_currentValue2 < 0x80) { + output.push(stringFromCharCode(_currentValue2)); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var basicLength = output.length; + var handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + var m = maxInt; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var currentValue = _step2.value; + + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error$1('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _currentValue = _step3.value; + + if (_currentValue < n && ++delta > maxInt) { + error$1('overflow'); + } + if (_currentValue == n) { + // Represent delta as a generalized variable-length integer. + var q = delta; + for (var k = base;; /* no condition */k += base) { + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + var qMinusT = q - t; + var baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + ++delta; + ++n; + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +var toUnicode = function toUnicode(input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +var toASCII = function toASCII(input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +var punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +/** + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author Gary Court + * @see http://github.com/garycourt/uri-js + */ +/** + * Copyright 2011 Gary Court. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. + */ +var SCHEMES = {}; +function pctEncChar(chr) { + var c = chr.charCodeAt(0); + var e = void 0; + if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); + return e; +} +function pctDecChars(str) { + var newStr = ""; + var i = 0; + var il = str.length; + while (i < il) { + var c = parseInt(str.substr(i + 1, 2), 16); + if (c < 128) { + newStr += String.fromCharCode(c); + i += 3; + } else if (c >= 194 && c < 224) { + if (il - i >= 6) { + var c2 = parseInt(str.substr(i + 4, 2), 16); + newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); + } else { + newStr += str.substr(i, 6); + } + i += 6; + } else if (c >= 224) { + if (il - i >= 9) { + var _c = parseInt(str.substr(i + 4, 2), 16); + var c3 = parseInt(str.substr(i + 7, 2), 16); + newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); + } else { + newStr += str.substr(i, 9); + } + i += 9; + } else { + newStr += str.substr(i, 3); + i += 3; + } + } + return newStr; +} +function _normalizeComponentEncoding(components, protocol) { + function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(protocol.UNRESERVED) ? str : decStr; + } + if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); + if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + return components; +} + +function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; +} +function _normalizeIPv4(host, protocol) { + var matches = host.match(protocol.IPV4ADDRESS) || []; + + var _matches = slicedToArray(matches, 2), + address = _matches[1]; + + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); + } else { + return host; + } +} +function _normalizeIPv6(host, protocol) { + var matches = host.match(protocol.IPV6ADDRESS) || []; + + var _matches2 = slicedToArray(matches, 3), + address = _matches2[1], + zone = _matches2[2]; + + if (address) { + var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), + _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), + last = _address$toLowerCase$2[0], + first = _address$toLowerCase$2[1]; + + var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; + var lastFields = last.split(":").map(_stripLeadingZeros); + var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); + var fieldCount = isLastFieldIPv4Address ? 7 : 8; + var lastFieldsStart = lastFields.length - fieldCount; + var fields = Array(fieldCount); + for (var x = 0; x < fieldCount; ++x) { + fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; + } + if (isLastFieldIPv4Address) { + fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); + } + var allZeroFields = fields.reduce(function (acc, field, index) { + if (!field || field === "0") { + var lastLongest = acc[acc.length - 1]; + if (lastLongest && lastLongest.index + lastLongest.length === index) { + lastLongest.length++; + } else { + acc.push({ index: index, length: 1 }); + } + } + return acc; + }, []); + var longestZeroFields = allZeroFields.sort(function (a, b) { + return b.length - a.length; + })[0]; + var newHost = void 0; + if (longestZeroFields && longestZeroFields.length > 1) { + var newFirst = fields.slice(0, longestZeroFields.index); + var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); + newHost = newFirst.join(":") + "::" + newLast.join(":"); + } else { + newHost = fields.join(":"); + } + if (zone) { + newHost += "%" + zone; + } + return newHost; + } else { + return host; + } +} +var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; +var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; +function parse(uriString) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var components = {}; + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; + var matches = uriString.match(URI_PARSE); + if (matches) { + if (NO_MATCH_IS_UNDEFINED) { + //store each component + components.scheme = matches[1]; + components.userinfo = matches[3]; + components.host = matches[4]; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = matches[7]; + components.fragment = matches[8]; + //fix port number + if (isNaN(components.port)) { + components.port = matches[5]; + } + } else { + //IE FIX for improper RegExp matching + //store each component + components.scheme = matches[1] || undefined; + components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; + components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; + components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; + //fix port number + if (isNaN(components.port)) { + components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; + } + } + if (components.host) { + //normalize IP hosts + components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); + } + //determine reference type + if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { + components.reference = "same-document"; + } else if (components.scheme === undefined) { + components.reference = "relative"; + } else if (components.fragment === undefined) { + components.reference = "absolute"; + } else { + components.reference = "uri"; + } + //check for reference errors + if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { + components.error = components.error || "URI is not a " + options.reference + " reference."; + } + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + //if host component is a domain name + if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { + //convert Unicode IDN -> ASCII IDN + try { + components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; + } + } + //convert IRI -> URI + _normalizeComponentEncoding(components, URI_PROTOCOL); + } else { + //normalize encodings + _normalizeComponentEncoding(components, protocol); + } + //perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(components, options); + } + } else { + components.error = components.error || "URI can not be parsed."; + } + return components; +} + +function _recomposeAuthority(components, options) { + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo); + uriTokens.push("@"); + } + if (components.host !== undefined) { + //normalize IP hosts, add brackets and escape zone separator for IPv6 + uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { + return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; + })); + } + if (typeof components.port === "number" || typeof components.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(components.port)); + } + return uriTokens.length ? uriTokens.join("") : undefined; +} + +var RDS1 = /^\.\.?\//; +var RDS2 = /^\/\.(\/|$)/; +var RDS3 = /^\/\.\.(\/|$)/; +var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; +function removeDotSegments(input) { + var output = []; + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, ""); + } else if (input.match(RDS2)) { + input = input.replace(RDS2, "/"); + } else if (input.match(RDS3)) { + input = input.replace(RDS3, "/"); + output.pop(); + } else if (input === "." || input === "..") { + input = ""; + } else { + var im = input.match(RDS5); + if (im) { + var s = im[0]; + input = input.slice(s.length); + output.push(s); + } else { + throw new Error("Unexpected dot segment condition"); + } + } + } + return output.join(""); +} + +function serialize(components) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); + if (components.host) { + //if host component is an IPv6 address + if (protocol.IPV6ADDRESS.test(components.host)) {} + //TODO: normalize IPv6 address as per RFC 5952 + + //if host component is a domain name + else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { + //convert IDN via punycode + try { + components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + } + } + //normalize encoding + _normalizeComponentEncoding(components, protocol); + if (options.reference !== "suffix" && components.scheme) { + uriTokens.push(components.scheme); + uriTokens.push(":"); + } + var authority = _recomposeAuthority(components, options); + if (authority !== undefined) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (components.path && components.path.charAt(0) !== "/") { + uriTokens.push("/"); + } + } + if (components.path !== undefined) { + var s = components.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === undefined) { + s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" + } + uriTokens.push(s); + } + if (components.query !== undefined) { + uriTokens.push("?"); + uriTokens.push(components.query); + } + if (components.fragment !== undefined) { + uriTokens.push("#"); + uriTokens.push(components.fragment); + } + return uriTokens.join(""); //merge tokens into a string +} + +function resolveComponents(base, relative) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var skipNormalization = arguments[3]; + + var target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); //normalize base components + relative = parse(serialize(relative, options), options); //normalize relative components + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== undefined) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path.charAt(0) === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + //target.authority = base.authority; + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; +} + +function resolve(baseURI, relativeURI, options) { + var schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); +} + +function normalize(uri, options) { + if (typeof uri === "string") { + uri = serialize(parse(uri, options), options); + } else if (typeOf(uri) === "object") { + uri = parse(serialize(uri, options), options); + } + return uri; +} + +function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = serialize(parse(uriA, options), options); + } else if (typeOf(uriA) === "object") { + uriA = serialize(uriA, options); + } + if (typeof uriB === "string") { + uriB = serialize(parse(uriB, options), options); + } else if (typeOf(uriB) === "object") { + uriB = serialize(uriB, options); + } + return uriA === uriB; +} + +function escapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); +} + +function unescapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); +} + +var handler = { + scheme: "http", + domainHost: true, + parse: function parse(components, options) { + //report missing host + if (!components.host) { + components.error = components.error || "HTTP URIs must have a host."; + } + return components; + }, + serialize: function serialize(components, options) { + var secure = String(components.scheme).toLowerCase() === "https"; + //normalize the default port + if (components.port === (secure ? 443 : 80) || components.port === "") { + components.port = undefined; + } + //normalize the empty path + if (!components.path) { + components.path = "/"; + } + //NOTE: We do not parse query strings for HTTP URIs + //as WWW Form Url Encoded query strings are part of the HTML4+ spec, + //and not the HTTP spec. + return components; + } +}; + +var handler$1 = { + scheme: "https", + domainHost: handler.domainHost, + parse: handler.parse, + serialize: handler.serialize +}; + +function isSecure(wsComponents) { + return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; +} +//RFC 6455 +var handler$2 = { + scheme: "ws", + domainHost: true, + parse: function parse(components, options) { + var wsComponents = components; + //indicate if the secure flag is set + wsComponents.secure = isSecure(wsComponents); + //construct resouce name + wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); + wsComponents.path = undefined; + wsComponents.query = undefined; + return wsComponents; + }, + serialize: function serialize(wsComponents, options) { + //normalize the default port + if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { + wsComponents.port = undefined; + } + //ensure scheme matches secure flag + if (typeof wsComponents.secure === 'boolean') { + wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws'; + wsComponents.secure = undefined; + } + //reconstruct path from resource name + if (wsComponents.resourceName) { + var _wsComponents$resourc = wsComponents.resourceName.split('?'), + _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), + path = _wsComponents$resourc2[0], + query = _wsComponents$resourc2[1]; + + wsComponents.path = path && path !== '/' ? path : undefined; + wsComponents.query = query; + wsComponents.resourceName = undefined; + } + //forbid fragment component + wsComponents.fragment = undefined; + return wsComponents; + } +}; + +var handler$3 = { + scheme: "wss", + domainHost: handler$2.domainHost, + parse: handler$2.parse, + serialize: handler$2.serialize +}; + +var O = {}; +var isIRI = true; +//RFC 3986 +var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; +var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive +var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded +//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = +//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) +//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext +//const VCHAR$$ = "[\\x21-\\x7E]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext +//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); +//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); +//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); +var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; +var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; +var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); +var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; +var UNRESERVED = new RegExp(UNRESERVED$$, "g"); +var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); +var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); +var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); +var NOT_HFVALUE = NOT_HFNAME; +function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(UNRESERVED) ? str : decStr; +} +var handler$4 = { + scheme: "mailto", + parse: function parse$$1(components, options) { + var mailtoComponents = components; + var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; + mailtoComponents.path = undefined; + if (mailtoComponents.query) { + var unknownHeaders = false; + var headers = {}; + var hfields = mailtoComponents.query.split("&"); + for (var x = 0, xl = hfields.length; x < xl; ++x) { + var hfield = hfields[x].split("="); + switch (hfield[0]) { + case "to": + var toAddrs = hfield[1].split(","); + for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { + to.push(toAddrs[_x]); + } + break; + case "subject": + mailtoComponents.subject = unescapeComponent(hfield[1], options); + break; + case "body": + mailtoComponents.body = unescapeComponent(hfield[1], options); + break; + default: + unknownHeaders = true; + headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); + break; + } + } + if (unknownHeaders) mailtoComponents.headers = headers; + } + mailtoComponents.query = undefined; + for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { + var addr = to[_x2].split("@"); + addr[0] = unescapeComponent(addr[0]); + if (!options.unicodeSupport) { + //convert Unicode IDN -> ASCII IDN + try { + addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); + } catch (e) { + mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; + } + } else { + addr[1] = unescapeComponent(addr[1], options).toLowerCase(); + } + to[_x2] = addr.join("@"); + } + return mailtoComponents; + }, + serialize: function serialize$$1(mailtoComponents, options) { + var components = mailtoComponents; + var to = toArray(mailtoComponents.to); + if (to) { + for (var x = 0, xl = to.length; x < xl; ++x) { + var toAddr = String(to[x]); + var atIdx = toAddr.lastIndexOf("@"); + var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); + var domain = toAddr.slice(atIdx + 1); + //convert IDN via punycode + try { + domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); + } catch (e) { + components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + to[x] = localPart + "@" + domain; + } + components.path = to.join(","); + } + var headers = mailtoComponents.headers = mailtoComponents.headers || {}; + if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; + if (mailtoComponents.body) headers["body"] = mailtoComponents.body; + var fields = []; + for (var name in headers) { + if (headers[name] !== O[name]) { + fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); + } + } + if (fields.length) { + components.query = fields.join("&"); + } + return components; + } +}; + +var URN_PARSE = /^([^\:]+)\:(.*)/; +//RFC 2141 +var handler$5 = { + scheme: "urn", + parse: function parse$$1(components, options) { + var matches = components.path && components.path.match(URN_PARSE); + var urnComponents = components; + if (matches) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = matches[1].toLowerCase(); + var nss = matches[2]; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + urnComponents.nid = nid; + urnComponents.nss = nss; + urnComponents.path = undefined; + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options); + } + } else { + urnComponents.error = urnComponents.error || "URN can not be parsed."; + } + return urnComponents; + }, + serialize: function serialize$$1(urnComponents, options) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = urnComponents.nid; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options); + } + var uriComponents = urnComponents; + var nss = urnComponents.nss; + uriComponents.path = (nid || options.nid) + ":" + nss; + return uriComponents; + } +}; + +var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; +//RFC 4122 +var handler$6 = { + scheme: "urn:uuid", + parse: function parse(urnComponents, options) { + var uuidComponents = urnComponents; + uuidComponents.uuid = uuidComponents.nss; + uuidComponents.nss = undefined; + if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { + uuidComponents.error = uuidComponents.error || "UUID is not valid."; + } + return uuidComponents; + }, + serialize: function serialize(uuidComponents, options) { + var urnComponents = uuidComponents; + //normalize UUID + urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); + return urnComponents; + } +}; + +SCHEMES[handler.scheme] = handler; +SCHEMES[handler$1.scheme] = handler$1; +SCHEMES[handler$2.scheme] = handler$2; +SCHEMES[handler$3.scheme] = handler$3; +SCHEMES[handler$4.scheme] = handler$4; +SCHEMES[handler$5.scheme] = handler$5; +SCHEMES[handler$6.scheme] = handler$6; + +exports.SCHEMES = SCHEMES; +exports.pctEncChar = pctEncChar; +exports.pctDecChars = pctDecChars; +exports.parse = parse; +exports.removeDotSegments = removeDotSegments; +exports.serialize = serialize; +exports.resolveComponents = resolveComponents; +exports.resolve = resolve; +exports.normalize = normalize; +exports.equal = equal; +exports.escapeComponent = escapeComponent; +exports.unescapeComponent = unescapeComponent; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=uri.all.js.map diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.js.map new file mode 100644 index 0000000..5b30c4e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uri.all.js","sources":["../../src/index.ts","../../src/schemes/urn-uuid.ts","../../src/schemes/urn.ts","../../src/schemes/mailto.ts","../../src/schemes/wss.ts","../../src/schemes/ws.ts","../../src/schemes/https.ts","../../src/schemes/http.ts","../../src/uri.ts","../../node_modules/punycode/punycode.es6.js","../../src/regexps-iri.ts","../../src/regexps-uri.ts","../../src/util.ts"],"sourcesContent":["import { SCHEMES } from \"./uri\";\n\nimport http from \"./schemes/http\";\nSCHEMES[http.scheme] = http;\n\nimport https from \"./schemes/https\";\nSCHEMES[https.scheme] = https;\n\nimport ws from \"./schemes/ws\";\nSCHEMES[ws.scheme] = ws;\n\nimport wss from \"./schemes/wss\";\nSCHEMES[wss.scheme] = wss;\n\nimport mailto from \"./schemes/mailto\";\nSCHEMES[mailto.scheme] = mailto;\n\nimport urn from \"./schemes/urn\";\nSCHEMES[urn.scheme] = urn;\n\nimport uuid from \"./schemes/urn-uuid\";\nSCHEMES[uuid.scheme] = uuid;\n\nexport * from \"./uri\";\n","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { URNComponents } from \"./urn\";\nimport { SCHEMES } from \"../uri\";\n\nexport interface UUIDComponents extends URNComponents {\n\tuuid?: string;\n}\n\nconst UUID = /^[0-9A-Fa-f]{8}(?:\\-[0-9A-Fa-f]{4}){3}\\-[0-9A-Fa-f]{12}$/;\nconst UUID_PARSE = /^[0-9A-Fa-f\\-]{36}/;\n\n//RFC 4122\nconst handler:URISchemeHandler = {\n\tscheme : \"urn:uuid\",\n\n\tparse : function (urnComponents:URNComponents, options:URIOptions):UUIDComponents {\n\t\tconst uuidComponents = urnComponents as UUIDComponents;\n\t\tuuidComponents.uuid = uuidComponents.nss;\n\t\tuuidComponents.nss = undefined;\n\n\t\tif (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {\n\t\t\tuuidComponents.error = uuidComponents.error || \"UUID is not valid.\";\n\t\t}\n\n\t\treturn uuidComponents;\n\t},\n\n\tserialize : function (uuidComponents:UUIDComponents, options:URIOptions):URNComponents {\n\t\tconst urnComponents = uuidComponents as URNComponents;\n\t\t//normalize UUID\n\t\turnComponents.nss = (uuidComponents.uuid || \"\").toLowerCase();\n\t\treturn urnComponents;\n\t},\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, SCHEMES } from \"../uri\";\n\nexport interface URNComponents extends URIComponents {\n\tnid?:string;\n\tnss?:string;\n}\n\nexport interface URNOptions extends URIOptions {\n\tnid?:string;\n}\n\nconst NID$ = \"(?:[0-9A-Za-z][0-9A-Za-z\\\\-]{1,31})\";\nconst PCT_ENCODED$ = \"(?:\\\\%[0-9A-Fa-f]{2})\";\nconst TRANS$$ = \"[0-9A-Za-z\\\\(\\\\)\\\\+\\\\,\\\\-\\\\.\\\\:\\\\=\\\\@\\\\;\\\\$\\\\_\\\\!\\\\*\\\\'\\\\/\\\\?\\\\#]\";\nconst NSS$ = \"(?:(?:\" + PCT_ENCODED$ + \"|\" + TRANS$$ + \")+)\";\nconst URN_SCHEME = new RegExp(\"^urn\\\\:(\" + NID$ + \")$\");\nconst URN_PATH = new RegExp(\"^(\" + NID$ + \")\\\\:(\" + NSS$ + \")$\");\nconst URN_PARSE = /^([^\\:]+)\\:(.*)/;\nconst URN_EXCLUDED = /[\\x00-\\x20\\\\\\\"\\&\\<\\>\\[\\]\\^\\`\\{\\|\\}\\~\\x7F-\\xFF]/g;\n\n//RFC 2141\nconst handler:URISchemeHandler = {\n\tscheme : \"urn\",\n\n\tparse : function (components:URIComponents, options:URNOptions):URNComponents {\n\t\tconst matches = components.path && components.path.match(URN_PARSE);\n\t\tlet urnComponents = components as URNComponents;\n\n\t\tif (matches) {\n\t\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\t\tconst nid = matches[1].toLowerCase();\n\t\t\tconst nss = matches[2];\n\t\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\t\turnComponents.nid = nid;\n\t\t\turnComponents.nss = nss;\n\t\t\turnComponents.path = undefined;\n\n\t\t\tif (schemeHandler) {\n\t\t\t\turnComponents = schemeHandler.parse(urnComponents, options) as URNComponents;\n\t\t\t}\n\t\t} else {\n\t\t\turnComponents.error = urnComponents.error || \"URN can not be parsed.\";\n\t\t}\n\n\t\treturn urnComponents;\n\t},\n\n\tserialize : function (urnComponents:URNComponents, options:URNOptions):URIComponents {\n\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\tconst nid = urnComponents.nid;\n\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\tif (schemeHandler) {\n\t\t\turnComponents = schemeHandler.serialize(urnComponents, options) as URNComponents;\n\t\t}\n\n\t\tconst uriComponents = urnComponents as URIComponents;\n\t\tconst nss = urnComponents.nss;\n\t\turiComponents.path = `${nid || options.nid}:${nss}`;\n\n\t\treturn uriComponents;\n\t},\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, pctDecChars, unescapeComponent } from \"../uri\";\nimport punycode from \"punycode\";\nimport { merge, subexp, toUpperCase, toArray } from \"../util\";\n\nexport interface MailtoHeaders {\n\t[hfname:string]:string\n}\n\nexport interface MailtoComponents extends URIComponents {\n\tto:Array,\n\theaders?:MailtoHeaders,\n\tsubject?:string,\n\tbody?:string\n}\n\nconst O:MailtoHeaders = {};\nconst isIRI = true;\n\n//RFC 3986\nconst UNRESERVED$$ = \"[A-Za-z0-9\\\\-\\\\.\\\\_\\\\~\" + (isIRI ? \"\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF\" : \"\") + \"]\";\nconst HEXDIG$$ = \"[0-9A-Fa-f]\"; //case-insensitive\nconst PCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)); //expanded\n\n//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =\n//const ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\#\\\\$\\\\%\\\\&\\\\'\\\\*\\\\+\\\\-\\\\/\\\\=\\\\?\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QTEXT$$ = \"[\\\\x01-\\\\x08\\\\x0B\\\\x0C\\\\x0E-\\\\x1F\\\\x7F]\"; //(%d1-8 / %d11-12 / %d14-31 / %d127)\n//const QTEXT$$ = merge(\"[\\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E]\", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext\n//const VCHAR$$ = \"[\\\\x21-\\\\x7E]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QP$ = subexp(\"\\\\\\\\\" + merge(\"[\\\\x00\\\\x0D\\\\x0A]\", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext\n//const FWS$ = subexp(subexp(WSP$$ + \"*\" + \"\\\\x0D\\\\x0A\") + \"?\" + WSP$$ + \"+\");\n//const QUOTED_PAIR$ = subexp(subexp(\"\\\\\\\\\" + subexp(VCHAR$$ + \"|\" + WSP$$)) + \"|\" + OBS_QP$);\n//const QUOTED_STRING$ = subexp('\\\\\"' + subexp(FWS$ + \"?\" + QCONTENT$) + \"*\" + FWS$ + \"?\" + '\\\\\"');\nconst ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\$\\\\%\\\\'\\\\*\\\\+\\\\-\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\nconst QTEXT$$ = \"[\\\\!\\\\$\\\\%\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\-\\\\.0-9\\\\<\\\\>A-Z\\\\x5E-\\\\x7E]\";\nconst VCHAR$$ = merge(QTEXT$$, \"[\\\\\\\"\\\\\\\\]\");\nconst DOT_ATOM_TEXT$ = subexp(ATEXT$$ + \"+\" + subexp(\"\\\\.\" + ATEXT$$ + \"+\") + \"*\");\nconst QUOTED_PAIR$ = subexp(\"\\\\\\\\\" + VCHAR$$);\nconst QCONTENT$ = subexp(QTEXT$$ + \"|\" + QUOTED_PAIR$);\nconst QUOTED_STRING$ = subexp('\\\\\"' + QCONTENT$ + \"*\" + '\\\\\"');\n\n//RFC 6068\nconst DTEXT_NO_OBS$$ = \"[\\\\x21-\\\\x5A\\\\x5E-\\\\x7E]\"; //%d33-90 / %d94-126\nconst SOME_DELIMS$$ = \"[\\\\!\\\\$\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\:\\\\@]\";\nconst QCHAR$ = subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$ + \"|\" + SOME_DELIMS$$);\nconst DOMAIN$ = subexp(DOT_ATOM_TEXT$ + \"|\" + \"\\\\[\" + DTEXT_NO_OBS$$ + \"*\" + \"\\\\]\");\nconst LOCAL_PART$ = subexp(DOT_ATOM_TEXT$ + \"|\" + QUOTED_STRING$);\nconst ADDR_SPEC$ = subexp(LOCAL_PART$ + \"\\\\@\" + DOMAIN$);\nconst TO$ = subexp(ADDR_SPEC$ + subexp(\"\\\\,\" + ADDR_SPEC$) + \"*\");\nconst HFNAME$ = subexp(QCHAR$ + \"*\");\nconst HFVALUE$ = HFNAME$;\nconst HFIELD$ = subexp(HFNAME$ + \"\\\\=\" + HFVALUE$);\nconst HFIELDS2$ = subexp(HFIELD$ + subexp(\"\\\\&\" + HFIELD$) + \"*\");\nconst HFIELDS$ = subexp(\"\\\\?\" + HFIELDS2$);\nconst MAILTO_URI = new RegExp(\"^mailto\\\\:\" + TO$ + \"?\" + HFIELDS$ + \"?$\");\n\nconst UNRESERVED = new RegExp(UNRESERVED$$, \"g\");\nconst PCT_ENCODED = new RegExp(PCT_ENCODED$, \"g\");\nconst NOT_LOCAL_PART = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", '[\\\\\"]', VCHAR$$), \"g\");\nconst NOT_DOMAIN = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", \"[\\\\[]\", DTEXT_NO_OBS$$, \"[\\\\]]\"), \"g\");\nconst NOT_HFNAME = new RegExp(merge(\"[^]\", UNRESERVED$$, SOME_DELIMS$$), \"g\");\nconst NOT_HFVALUE = NOT_HFNAME;\nconst TO = new RegExp(\"^\" + TO$ + \"$\");\nconst HFIELDS = new RegExp(\"^\" + HFIELDS2$ + \"$\");\n\nfunction decodeUnreserved(str:string):string {\n\tconst decStr = pctDecChars(str);\n\treturn (!decStr.match(UNRESERVED) ? str : decStr);\n}\n\nconst handler:URISchemeHandler = {\n\tscheme : \"mailto\",\n\n\tparse : function (components:URIComponents, options:URIOptions):MailtoComponents {\n\t\tconst mailtoComponents = components as MailtoComponents;\n\t\tconst to = mailtoComponents.to = (mailtoComponents.path ? mailtoComponents.path.split(\",\") : []);\n\t\tmailtoComponents.path = undefined;\n\n\t\tif (mailtoComponents.query) {\n\t\t\tlet unknownHeaders = false\n\t\t\tconst headers:MailtoHeaders = {};\n\t\t\tconst hfields = mailtoComponents.query.split(\"&\");\n\n\t\t\tfor (let x = 0, xl = hfields.length; x < xl; ++x) {\n\t\t\t\tconst hfield = hfields[x].split(\"=\");\n\n\t\t\t\tswitch (hfield[0]) {\n\t\t\t\t\tcase \"to\":\n\t\t\t\t\t\tconst toAddrs = hfield[1].split(\",\");\n\t\t\t\t\t\tfor (let x = 0, xl = toAddrs.length; x < xl; ++x) {\n\t\t\t\t\t\t\tto.push(toAddrs[x]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"subject\":\n\t\t\t\t\t\tmailtoComponents.subject = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"body\":\n\t\t\t\t\t\tmailtoComponents.body = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tunknownHeaders = true;\n\t\t\t\t\t\theaders[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (unknownHeaders) mailtoComponents.headers = headers;\n\t\t}\n\n\t\tmailtoComponents.query = undefined;\n\n\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\tconst addr = to[x].split(\"@\");\n\n\t\t\taddr[0] = unescapeComponent(addr[0]);\n\n\t\t\tif (!options.unicodeSupport) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\taddr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tmailtoComponents.error = mailtoComponents.error || \"Email address's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\taddr[1] = unescapeComponent(addr[1], options).toLowerCase();\n\t\t\t}\n\n\t\t\tto[x] = addr.join(\"@\");\n\t\t}\n\n\t\treturn mailtoComponents;\n\t},\n\n\tserialize : function (mailtoComponents:MailtoComponents, options:URIOptions):URIComponents {\n\t\tconst components = mailtoComponents as URIComponents;\n\t\tconst to = toArray(mailtoComponents.to);\n\t\tif (to) {\n\t\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\t\tconst toAddr = String(to[x]);\n\t\t\t\tconst atIdx = toAddr.lastIndexOf(\"@\");\n\t\t\t\tconst localPart = (toAddr.slice(0, atIdx)).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);\n\t\t\t\tlet domain = toAddr.slice(atIdx + 1);\n\n\t\t\t\t//convert IDN via punycode\n\t\t\t\ttry {\n\t\t\t\t\tdomain = (!options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain));\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Email address's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t\t}\n\n\t\t\t\tto[x] = localPart + \"@\" + domain;\n\t\t\t}\n\n\t\t\tcomponents.path = to.join(\",\");\n\t\t}\n\n\t\tconst headers = mailtoComponents.headers = mailtoComponents.headers || {};\n\n\t\tif (mailtoComponents.subject) headers[\"subject\"] = mailtoComponents.subject;\n\t\tif (mailtoComponents.body) headers[\"body\"] = mailtoComponents.body;\n\n\t\tconst fields = [];\n\t\tfor (const name in headers) {\n\t\t\tif (headers[name] !== O[name]) {\n\t\t\t\tfields.push(\n\t\t\t\t\tname.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) +\n\t\t\t\t\t\"=\" +\n\t\t\t\t\theaders[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (fields.length) {\n\t\t\tcomponents.query = fields.join(\"&\");\n\t\t}\n\n\t\treturn components;\n\t}\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport ws from \"./ws\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"wss\",\n\tdomainHost : ws.domainHost,\n\tparse : ws.parse,\n\tserialize : ws.serialize\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nexport interface WSComponents extends URIComponents {\n\tresourceName?: string;\n\tsecure?: boolean;\n}\n\nfunction isSecure(wsComponents:WSComponents):boolean {\n\treturn typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === \"wss\";\n}\n\n//RFC 6455\nconst handler:URISchemeHandler = {\n\tscheme : \"ws\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):WSComponents {\n\t\tconst wsComponents = components as WSComponents;\n\n\t\t//indicate if the secure flag is set\n\t\twsComponents.secure = isSecure(wsComponents);\n\n\t\t//construct resouce name\n\t\twsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '');\n\t\twsComponents.path = undefined;\n\t\twsComponents.query = undefined;\n\n\t\treturn wsComponents;\n\t},\n\n\tserialize : function (wsComponents:WSComponents, options:URIOptions):URIComponents {\n\t\t//normalize the default port\n\t\tif (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === \"\") {\n\t\t\twsComponents.port = undefined;\n\t\t}\n\n\t\t//ensure scheme matches secure flag\n\t\tif (typeof wsComponents.secure === 'boolean') {\n\t\t\twsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws');\n\t\t\twsComponents.secure = undefined;\n\t\t}\n\n\t\t//reconstruct path from resource name\n\t\tif (wsComponents.resourceName) {\n\t\t\tconst [path, query] = wsComponents.resourceName.split('?');\n\t\t\twsComponents.path = (path && path !== '/' ? path : undefined);\n\t\t\twsComponents.query = query;\n\t\t\twsComponents.resourceName = undefined;\n\t\t}\n\n\t\t//forbid fragment component\n\t\twsComponents.fragment = undefined;\n\n\t\treturn wsComponents;\n\t}\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport http from \"./http\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"https\",\n\tdomainHost : http.domainHost,\n\tparse : http.parse,\n\tserialize : http.serialize\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"http\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\t//report missing host\n\t\tif (!components.host) {\n\t\t\tcomponents.error = components.error || \"HTTP URIs must have a host.\";\n\t\t}\n\n\t\treturn components;\n\t},\n\n\tserialize : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\tconst secure = String(components.scheme).toLowerCase() === \"https\";\n\n\t\t//normalize the default port\n\t\tif (components.port === (secure ? 443 : 80) || components.port === \"\") {\n\t\t\tcomponents.port = undefined;\n\t\t}\n\t\t\n\t\t//normalize the empty path\n\t\tif (!components.path) {\n\t\t\tcomponents.path = \"/\";\n\t\t}\n\n\t\t//NOTE: We do not parse query strings for HTTP URIs\n\t\t//as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n\t\t//and not the HTTP spec.\n\n\t\treturn components;\n\t}\n};\n\nexport default handler;","/**\n * URI.js\n *\n * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.\n * @author Gary Court\n * @see http://github.com/garycourt/uri-js\n */\n\n/**\n * Copyright 2011 Gary Court. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are\n * permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of\n * conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice, this list\n * of conditions and the following disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those of the\n * authors and should not be interpreted as representing official policies, either expressed\n * or implied, of Gary Court.\n */\n\nimport URI_PROTOCOL from \"./regexps-uri\";\nimport IRI_PROTOCOL from \"./regexps-iri\";\nimport punycode from \"punycode\";\nimport { toUpperCase, typeOf, assign } from \"./util\";\n\nexport interface URIComponents {\n\tscheme?:string;\n\tuserinfo?:string;\n\thost?:string;\n\tport?:number|string;\n\tpath?:string;\n\tquery?:string;\n\tfragment?:string;\n\treference?:string;\n\terror?:string;\n}\n\nexport interface URIOptions {\n\tscheme?:string;\n\treference?:string;\n\ttolerant?:boolean;\n\tabsolutePath?:boolean;\n\tiri?:boolean;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n}\n\nexport interface URISchemeHandler {\n\tscheme:string;\n\tparse(components:ParentComponents, options:Options):Components;\n\tserialize(components:Components, options:Options):ParentComponents;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n\tabsolutePath?:boolean;\n}\n\nexport interface URIRegExps {\n\tNOT_SCHEME : RegExp,\n\tNOT_USERINFO : RegExp,\n\tNOT_HOST : RegExp,\n\tNOT_PATH : RegExp,\n\tNOT_PATH_NOSCHEME : RegExp,\n\tNOT_QUERY : RegExp,\n\tNOT_FRAGMENT : RegExp,\n\tESCAPE : RegExp,\n\tUNRESERVED : RegExp,\n\tOTHER_CHARS : RegExp,\n\tPCT_ENCODED : RegExp,\n\tIPV4ADDRESS : RegExp,\n\tIPV6ADDRESS : RegExp,\n}\n\nexport const SCHEMES:{[scheme:string]:URISchemeHandler} = {};\n\nexport function pctEncChar(chr:string):string {\n\tconst c = chr.charCodeAt(0);\n\tlet e:string;\n\n\tif (c < 16) e = \"%0\" + c.toString(16).toUpperCase();\n\telse if (c < 128) e = \"%\" + c.toString(16).toUpperCase();\n\telse if (c < 2048) e = \"%\" + ((c >> 6) | 192).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\telse e = \"%\" + ((c >> 12) | 224).toString(16).toUpperCase() + \"%\" + (((c >> 6) & 63) | 128).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\n\treturn e;\n}\n\nexport function pctDecChars(str:string):string {\n\tlet newStr = \"\";\n\tlet i = 0;\n\tconst il = str.length;\n\n\twhile (i < il) {\n\t\tconst c = parseInt(str.substr(i + 1, 2), 16);\n\n\t\tif (c < 128) {\n\t\t\tnewStr += String.fromCharCode(c);\n\t\t\ti += 3;\n\t\t}\n\t\telse if (c >= 194 && c < 224) {\n\t\t\tif ((il - i) >= 6) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 31) << 6) | (c2 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 6);\n\t\t\t}\n\t\t\ti += 6;\n\t\t}\n\t\telse if (c >= 224) {\n\t\t\tif ((il - i) >= 9) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tconst c3 = parseInt(str.substr(i + 7, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 9);\n\t\t\t}\n\t\t\ti += 9;\n\t\t}\n\t\telse {\n\t\t\tnewStr += str.substr(i, 3);\n\t\t\ti += 3;\n\t\t}\n\t}\n\n\treturn newStr;\n}\n\nfunction _normalizeComponentEncoding(components:URIComponents, protocol:URIRegExps) {\n\tfunction decodeUnreserved(str:string):string {\n\t\tconst decStr = pctDecChars(str);\n\t\treturn (!decStr.match(protocol.UNRESERVED) ? str : decStr);\n\t}\n\n\tif (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, \"\");\n\tif (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace((components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME), pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\n\treturn components;\n};\n\nfunction _stripLeadingZeros(str:string):string {\n\treturn str.replace(/^0*(.*)/, \"$1\") || \"0\";\n}\n\nfunction _normalizeIPv4(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV4ADDRESS) || [];\n\tconst [, address] = matches;\n\t\n\tif (address) {\n\t\treturn address.split(\".\").map(_stripLeadingZeros).join(\".\");\n\t} else {\n\t\treturn host;\n\t}\n}\n\nfunction _normalizeIPv6(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV6ADDRESS) || [];\n\tconst [, address, zone] = matches;\n\n\tif (address) {\n\t\tconst [last, first] = address.toLowerCase().split('::').reverse();\n\t\tconst firstFields = first ? first.split(\":\").map(_stripLeadingZeros) : [];\n\t\tconst lastFields = last.split(\":\").map(_stripLeadingZeros);\n\t\tconst isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);\n\t\tconst fieldCount = isLastFieldIPv4Address ? 7 : 8;\n\t\tconst lastFieldsStart = lastFields.length - fieldCount;\n\t\tconst fields = Array(fieldCount);\n\n\t\tfor (let x = 0; x < fieldCount; ++x) {\n\t\t\tfields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';\n\t\t}\n\n\t\tif (isLastFieldIPv4Address) {\n\t\t\tfields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);\n\t\t}\n\n\t\tconst allZeroFields = fields.reduce>((acc, field, index) => {\n\t\t\tif (!field || field === \"0\") {\n\t\t\t\tconst lastLongest = acc[acc.length - 1];\n\t\t\t\tif (lastLongest && lastLongest.index + lastLongest.length === index) {\n\t\t\t\t\tlastLongest.length++;\n\t\t\t\t} else {\n\t\t\t\t\tacc.push({ index, length : 1 });\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, []);\n\n\t\tconst longestZeroFields = allZeroFields.sort((a, b) => b.length - a.length)[0];\n\n\t\tlet newHost:string;\n\t\tif (longestZeroFields && longestZeroFields.length > 1) {\n\t\t\tconst newFirst = fields.slice(0, longestZeroFields.index) ;\n\t\t\tconst newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);\n\t\t\tnewHost = newFirst.join(\":\") + \"::\" + newLast.join(\":\");\n\t\t} else {\n\t\t\tnewHost = fields.join(\":\");\n\t\t}\n\n\t\tif (zone) {\n\t\t\tnewHost += \"%\" + zone;\n\t\t}\n\n\t\treturn newHost;\n\t} else {\n\t\treturn host;\n\t}\n}\n\nconst URI_PARSE = /^(?:([^:\\/?#]+):)?(?:\\/\\/((?:([^\\/?#@]*)@)?(\\[[^\\/?#\\]]+\\]|[^\\/?#:]*)(?:\\:(\\d*))?))?([^?#]*)(?:\\?([^#]*))?(?:#((?:.|\\n|\\r)*))?/i;\nconst NO_MATCH_IS_UNDEFINED = ((\"\").match(/(){0}/))[1] === undefined;\n\nexport function parse(uriString:string, options:URIOptions = {}):URIComponents {\n\tconst components:URIComponents = {};\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\n\tif (options.reference === \"suffix\") uriString = (options.scheme ? options.scheme + \":\" : \"\") + \"//\" + uriString;\n\n\tconst matches = uriString.match(URI_PARSE);\n\n\tif (matches) {\n\t\tif (NO_MATCH_IS_UNDEFINED) {\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1];\n\t\t\tcomponents.userinfo = matches[3];\n\t\t\tcomponents.host = matches[4];\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = matches[7];\n\t\t\tcomponents.fragment = matches[8];\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = matches[5];\n\t\t\t}\n\t\t} else { //IE FIX for improper RegExp matching\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1] || undefined;\n\t\t\tcomponents.userinfo = (uriString.indexOf(\"@\") !== -1 ? matches[3] : undefined);\n\t\t\tcomponents.host = (uriString.indexOf(\"//\") !== -1 ? matches[4] : undefined);\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = (uriString.indexOf(\"?\") !== -1 ? matches[7] : undefined);\n\t\t\tcomponents.fragment = (uriString.indexOf(\"#\") !== -1 ? matches[8] : undefined);\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = (uriString.match(/\\/\\/(?:.|\\n)*\\:(?:\\/|\\?|\\#|$)/) ? matches[4] : undefined);\n\t\t\t}\n\t\t}\n\n\t\tif (components.host) {\n\t\t\t//normalize IP hosts\n\t\t\tcomponents.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);\n\t\t}\n\n\t\t//determine reference type\n\t\tif (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {\n\t\t\tcomponents.reference = \"same-document\";\n\t\t} else if (components.scheme === undefined) {\n\t\t\tcomponents.reference = \"relative\";\n\t\t} else if (components.fragment === undefined) {\n\t\t\tcomponents.reference = \"absolute\";\n\t\t} else {\n\t\t\tcomponents.reference = \"uri\";\n\t\t}\n\n\t\t//check for reference errors\n\t\tif (options.reference && options.reference !== \"suffix\" && options.reference !== components.reference) {\n\t\t\tcomponents.error = components.error || \"URI is not a \" + options.reference + \" reference.\";\n\t\t}\n\n\t\t//find scheme handler\n\t\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t\t//check if scheme can't handle IRIs\n\t\tif (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n\t\t\t//if host component is a domain name\n\t\t\tif (components.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost))) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\tcomponents.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//convert IRI -> URI\n\t\t\t_normalizeComponentEncoding(components, URI_PROTOCOL);\n\t\t} else {\n\t\t\t//normalize encodings\n\t\t\t_normalizeComponentEncoding(components, protocol);\n\t\t}\n\n\t\t//perform scheme specific parsing\n\t\tif (schemeHandler && schemeHandler.parse) {\n\t\t\tschemeHandler.parse(components, options);\n\t\t}\n\t} else {\n\t\tcomponents.error = components.error || \"URI can not be parsed.\";\n\t}\n\n\treturn components;\n};\n\nfunction _recomposeAuthority(components:URIComponents, options:URIOptions):string|undefined {\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array = [];\n\n\tif (components.userinfo !== undefined) {\n\t\turiTokens.push(components.userinfo);\n\t\turiTokens.push(\"@\");\n\t}\n\n\tif (components.host !== undefined) {\n\t\t//normalize IP hosts, add brackets and escape zone separator for IPv6\n\t\turiTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, (_, $1, $2) => \"[\" + $1 + ($2 ? \"%25\" + $2 : \"\") + \"]\"));\n\t}\n\n\tif (typeof components.port === \"number\" || typeof components.port === \"string\") {\n\t\turiTokens.push(\":\");\n\t\turiTokens.push(String(components.port));\n\t}\n\n\treturn uriTokens.length ? uriTokens.join(\"\") : undefined;\n};\n\nconst RDS1 = /^\\.\\.?\\//;\nconst RDS2 = /^\\/\\.(\\/|$)/;\nconst RDS3 = /^\\/\\.\\.(\\/|$)/;\nconst RDS4 = /^\\.\\.?$/;\nconst RDS5 = /^\\/?(?:.|\\n)*?(?=\\/|$)/;\n\nexport function removeDotSegments(input:string):string {\n\tconst output:Array = [];\n\n\twhile (input.length) {\n\t\tif (input.match(RDS1)) {\n\t\t\tinput = input.replace(RDS1, \"\");\n\t\t} else if (input.match(RDS2)) {\n\t\t\tinput = input.replace(RDS2, \"/\");\n\t\t} else if (input.match(RDS3)) {\n\t\t\tinput = input.replace(RDS3, \"/\");\n\t\t\toutput.pop();\n\t\t} else if (input === \".\" || input === \"..\") {\n\t\t\tinput = \"\";\n\t\t} else {\n\t\t\tconst im = input.match(RDS5);\n\t\t\tif (im) {\n\t\t\t\tconst s = im[0];\n\t\t\t\tinput = input.slice(s.length);\n\t\t\t\toutput.push(s);\n\t\t\t} else {\n\t\t\t\tthrow new Error(\"Unexpected dot segment condition\");\n\t\t\t}\n\t\t}\n\t}\n\n\treturn output.join(\"\");\n};\n\nexport function serialize(components:URIComponents, options:URIOptions = {}):string {\n\tconst protocol = (options.iri ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array = [];\n\n\t//find scheme handler\n\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t//perform scheme specific serialization\n\tif (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);\n\n\tif (components.host) {\n\t\t//if host component is an IPv6 address\n\t\tif (protocol.IPV6ADDRESS.test(components.host)) {\n\t\t\t//TODO: normalize IPv6 address as per RFC 5952\n\t\t}\n\n\t\t//if host component is a domain name\n\t\telse if (options.domainHost || (schemeHandler && schemeHandler.domainHost)) {\n\t\t\t//convert IDN via punycode\n\t\t\ttry {\n\t\t\t\tcomponents.host = (!options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host));\n\t\t\t} catch (e) {\n\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t}\n\t\t}\n\t}\n\n\t//normalize encoding\n\t_normalizeComponentEncoding(components, protocol);\n\n\tif (options.reference !== \"suffix\" && components.scheme) {\n\t\turiTokens.push(components.scheme);\n\t\turiTokens.push(\":\");\n\t}\n\n\tconst authority = _recomposeAuthority(components, options);\n\tif (authority !== undefined) {\n\t\tif (options.reference !== \"suffix\") {\n\t\t\turiTokens.push(\"//\");\n\t\t}\n\n\t\turiTokens.push(authority);\n\n\t\tif (components.path && components.path.charAt(0) !== \"/\") {\n\t\t\turiTokens.push(\"/\");\n\t\t}\n\t}\n\n\tif (components.path !== undefined) {\n\t\tlet s = components.path;\n\n\t\tif (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n\t\t\ts = removeDotSegments(s);\n\t\t}\n\n\t\tif (authority === undefined) {\n\t\t\ts = s.replace(/^\\/\\//, \"/%2F\"); //don't allow the path to start with \"//\"\n\t\t}\n\n\t\turiTokens.push(s);\n\t}\n\n\tif (components.query !== undefined) {\n\t\turiTokens.push(\"?\");\n\t\turiTokens.push(components.query);\n\t}\n\n\tif (components.fragment !== undefined) {\n\t\turiTokens.push(\"#\");\n\t\turiTokens.push(components.fragment);\n\t}\n\n\treturn uriTokens.join(\"\"); //merge tokens into a string\n};\n\nexport function resolveComponents(base:URIComponents, relative:URIComponents, options:URIOptions = {}, skipNormalization?:boolean):URIComponents {\n\tconst target:URIComponents = {};\n\n\tif (!skipNormalization) {\n\t\tbase = parse(serialize(base, options), options); //normalize base components\n\t\trelative = parse(serialize(relative, options), options); //normalize relative components\n\t}\n\toptions = options || {};\n\n\tif (!options.tolerant && relative.scheme) {\n\t\ttarget.scheme = relative.scheme;\n\t\t//target.authority = relative.authority;\n\t\ttarget.userinfo = relative.userinfo;\n\t\ttarget.host = relative.host;\n\t\ttarget.port = relative.port;\n\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\ttarget.query = relative.query;\n\t} else {\n\t\tif (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n\t\t\t//target.authority = relative.authority;\n\t\t\ttarget.userinfo = relative.userinfo;\n\t\t\ttarget.host = relative.host;\n\t\t\ttarget.port = relative.port;\n\t\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\t\ttarget.query = relative.query;\n\t\t} else {\n\t\t\tif (!relative.path) {\n\t\t\t\ttarget.path = base.path;\n\t\t\t\tif (relative.query !== undefined) {\n\t\t\t\t\ttarget.query = relative.query;\n\t\t\t\t} else {\n\t\t\t\t\ttarget.query = base.query;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (relative.path.charAt(0) === \"/\") {\n\t\t\t\t\ttarget.path = removeDotSegments(relative.path);\n\t\t\t\t} else {\n\t\t\t\t\tif ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n\t\t\t\t\t\ttarget.path = \"/\" + relative.path;\n\t\t\t\t\t} else if (!base.path) {\n\t\t\t\t\t\ttarget.path = relative.path;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget.path = base.path.slice(0, base.path.lastIndexOf(\"/\") + 1) + relative.path;\n\t\t\t\t\t}\n\t\t\t\t\ttarget.path = removeDotSegments(target.path);\n\t\t\t\t}\n\t\t\t\ttarget.query = relative.query;\n\t\t\t}\n\t\t\t//target.authority = base.authority;\n\t\t\ttarget.userinfo = base.userinfo;\n\t\t\ttarget.host = base.host;\n\t\t\ttarget.port = base.port;\n\t\t}\n\t\ttarget.scheme = base.scheme;\n\t}\n\n\ttarget.fragment = relative.fragment;\n\n\treturn target;\n};\n\nexport function resolve(baseURI:string, relativeURI:string, options?:URIOptions):string {\n\tconst schemelessOptions = assign({ scheme : 'null' }, options);\n\treturn serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);\n};\n\nexport function normalize(uri:string, options?:URIOptions):string;\nexport function normalize(uri:URIComponents, options?:URIOptions):URIComponents;\nexport function normalize(uri:any, options?:URIOptions):any {\n\tif (typeof uri === \"string\") {\n\t\turi = serialize(parse(uri, options), options);\n\t} else if (typeOf(uri) === \"object\") {\n\t\turi = parse(serialize(uri, options), options);\n\t}\n\n\treturn uri;\n};\n\nexport function equal(uriA:string, uriB:string, options?: URIOptions):boolean;\nexport function equal(uriA:URIComponents, uriB:URIComponents, options?:URIOptions):boolean;\nexport function equal(uriA:any, uriB:any, options?:URIOptions):boolean {\n\tif (typeof uriA === \"string\") {\n\t\turiA = serialize(parse(uriA, options), options);\n\t} else if (typeOf(uriA) === \"object\") {\n\t\turiA = serialize(uriA, options);\n\t}\n\n\tif (typeof uriB === \"string\") {\n\t\turiB = serialize(parse(uriB, options), options);\n\t} else if (typeOf(uriB) === \"object\") {\n\t\turiB = serialize(uriB, options);\n\t}\n\n\treturn uriA === uriB;\n};\n\nexport function escapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE), pctEncChar);\n};\n\nexport function unescapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED), pctDecChars);\n};\n","'use strict';\n\n/** Highest positive signed 32-bit float value */\nconst maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1\n\n/** Bootstring parameters */\nconst base = 36;\nconst tMin = 1;\nconst tMax = 26;\nconst skew = 38;\nconst damp = 700;\nconst initialBias = 72;\nconst initialN = 128; // 0x80\nconst delimiter = '-'; // '\\x2D'\n\n/** Regular expressions */\nconst regexPunycode = /^xn--/;\nconst regexNonASCII = /[^\\0-\\x7E]/; // non-ASCII chars\nconst regexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g; // RFC 3490 separators\n\n/** Error messages */\nconst errors = {\n\t'overflow': 'Overflow: input needs wider integers to process',\n\t'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n\t'invalid-input': 'Invalid input'\n};\n\n/** Convenience shortcuts */\nconst baseMinusTMin = base - tMin;\nconst floor = Math.floor;\nconst stringFromCharCode = String.fromCharCode;\n\n/*--------------------------------------------------------------------------*/\n\n/**\n * A generic error utility function.\n * @private\n * @param {String} type The error type.\n * @returns {Error} Throws a `RangeError` with the applicable error message.\n */\nfunction error(type) {\n\tthrow new RangeError(errors[type]);\n}\n\n/**\n * A generic `Array#map` utility function.\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} callback The function that gets called for every array\n * item.\n * @returns {Array} A new array of values returned by the callback function.\n */\nfunction map(array, fn) {\n\tconst result = [];\n\tlet length = array.length;\n\twhile (length--) {\n\t\tresult[length] = fn(array[length]);\n\t}\n\treturn result;\n}\n\n/**\n * A simple `Array#map`-like wrapper to work with domain name strings or email\n * addresses.\n * @private\n * @param {String} domain The domain name or email address.\n * @param {Function} callback The function that gets called for every\n * character.\n * @returns {Array} A new string of characters returned by the callback\n * function.\n */\nfunction mapDomain(string, fn) {\n\tconst parts = string.split('@');\n\tlet result = '';\n\tif (parts.length > 1) {\n\t\t// In email addresses, only the domain name should be punycoded. Leave\n\t\t// the local part (i.e. everything up to `@`) intact.\n\t\tresult = parts[0] + '@';\n\t\tstring = parts[1];\n\t}\n\t// Avoid `split(regex)` for IE8 compatibility. See #17.\n\tstring = string.replace(regexSeparators, '\\x2E');\n\tconst labels = string.split('.');\n\tconst encoded = map(labels, fn).join('.');\n\treturn result + encoded;\n}\n\n/**\n * Creates an array containing the numeric code points of each Unicode\n * character in the string. While JavaScript uses UCS-2 internally,\n * this function will convert a pair of surrogate halves (each of which\n * UCS-2 exposes as separate characters) into a single code point,\n * matching UTF-16.\n * @see `punycode.ucs2.encode`\n * @see \n * @memberOf punycode.ucs2\n * @name decode\n * @param {String} string The Unicode input string (UCS-2).\n * @returns {Array} The new array of code points.\n */\nfunction ucs2decode(string) {\n\tconst output = [];\n\tlet counter = 0;\n\tconst length = string.length;\n\twhile (counter < length) {\n\t\tconst value = string.charCodeAt(counter++);\n\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t// It's a high surrogate, and there is a next character.\n\t\t\tconst extra = string.charCodeAt(counter++);\n\t\t\tif ((extra & 0xFC00) == 0xDC00) { // Low surrogate.\n\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t} else {\n\t\t\t\t// It's an unmatched surrogate; only append this code unit, in case the\n\t\t\t\t// next code unit is the high surrogate of a surrogate pair.\n\t\t\t\toutput.push(value);\n\t\t\t\tcounter--;\n\t\t\t}\n\t\t} else {\n\t\t\toutput.push(value);\n\t\t}\n\t}\n\treturn output;\n}\n\n/**\n * Creates a string based on an array of numeric code points.\n * @see `punycode.ucs2.decode`\n * @memberOf punycode.ucs2\n * @name encode\n * @param {Array} codePoints The array of numeric code points.\n * @returns {String} The new Unicode string (UCS-2).\n */\nconst ucs2encode = array => String.fromCodePoint(...array);\n\n/**\n * Converts a basic code point into a digit/integer.\n * @see `digitToBasic()`\n * @private\n * @param {Number} codePoint The basic numeric code point value.\n * @returns {Number} The numeric value of a basic code point (for use in\n * representing integers) in the range `0` to `base - 1`, or `base` if\n * the code point does not represent a value.\n */\nconst basicToDigit = function(codePoint) {\n\tif (codePoint - 0x30 < 0x0A) {\n\t\treturn codePoint - 0x16;\n\t}\n\tif (codePoint - 0x41 < 0x1A) {\n\t\treturn codePoint - 0x41;\n\t}\n\tif (codePoint - 0x61 < 0x1A) {\n\t\treturn codePoint - 0x61;\n\t}\n\treturn base;\n};\n\n/**\n * Converts a digit/integer into a basic code point.\n * @see `basicToDigit()`\n * @private\n * @param {Number} digit The numeric value of a basic code point.\n * @returns {Number} The basic code point whose value (when used for\n * representing integers) is `digit`, which needs to be in the range\n * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n * used; else, the lowercase form is used. The behavior is undefined\n * if `flag` is non-zero and `digit` has no uppercase form.\n */\nconst digitToBasic = function(digit, flag) {\n\t// 0..25 map to ASCII a..z or A..Z\n\t// 26..35 map to ASCII 0..9\n\treturn digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n};\n\n/**\n * Bias adaptation function as per section 3.4 of RFC 3492.\n * https://tools.ietf.org/html/rfc3492#section-3.4\n * @private\n */\nconst adapt = function(delta, numPoints, firstTime) {\n\tlet k = 0;\n\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\tdelta += floor(delta / numPoints);\n\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\tdelta = floor(delta / baseMinusTMin);\n\t}\n\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n};\n\n/**\n * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n * symbols.\n * @memberOf punycode\n * @param {String} input The Punycode string of ASCII-only symbols.\n * @returns {String} The resulting string of Unicode symbols.\n */\nconst decode = function(input) {\n\t// Don't use UCS-2.\n\tconst output = [];\n\tconst inputLength = input.length;\n\tlet i = 0;\n\tlet n = initialN;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points: let `basic` be the number of input code\n\t// points before the last delimiter, or `0` if there is none, then copy\n\t// the first basic code points to the output.\n\n\tlet basic = input.lastIndexOf(delimiter);\n\tif (basic < 0) {\n\t\tbasic = 0;\n\t}\n\n\tfor (let j = 0; j < basic; ++j) {\n\t\t// if it's not a basic code point\n\t\tif (input.charCodeAt(j) >= 0x80) {\n\t\t\terror('not-basic');\n\t\t}\n\t\toutput.push(input.charCodeAt(j));\n\t}\n\n\t// Main decoding loop: start just after the last delimiter if any basic code\n\t// points were copied; start at the beginning otherwise.\n\n\tfor (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {\n\n\t\t// `index` is the index of the next character to be consumed.\n\t\t// Decode a generalized variable-length integer into `delta`,\n\t\t// which gets added to `i`. The overflow checking is easier\n\t\t// if we increase `i` as we go, then subtract off its starting\n\t\t// value at the end to obtain `delta`.\n\t\tlet oldi = i;\n\t\tfor (let w = 1, k = base; /* no condition */; k += base) {\n\n\t\t\tif (index >= inputLength) {\n\t\t\t\terror('invalid-input');\n\t\t\t}\n\n\t\t\tconst digit = basicToDigit(input.charCodeAt(index++));\n\n\t\t\tif (digit >= base || digit > floor((maxInt - i) / w)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\ti += digit * w;\n\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n\t\t\tif (digit < t) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst baseMinusT = base - t;\n\t\t\tif (w > floor(maxInt / baseMinusT)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tw *= baseMinusT;\n\n\t\t}\n\n\t\tconst out = output.length + 1;\n\t\tbias = adapt(i - oldi, out, oldi == 0);\n\n\t\t// `i` was supposed to wrap around from `out` to `0`,\n\t\t// incrementing `n` each time, so we'll fix that now:\n\t\tif (floor(i / out) > maxInt - n) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tn += floor(i / out);\n\t\ti %= out;\n\n\t\t// Insert `n` at position `i` of the output.\n\t\toutput.splice(i++, 0, n);\n\n\t}\n\n\treturn String.fromCodePoint(...output);\n};\n\n/**\n * Converts a string of Unicode symbols (e.g. a domain name label) to a\n * Punycode string of ASCII-only symbols.\n * @memberOf punycode\n * @param {String} input The string of Unicode symbols.\n * @returns {String} The resulting Punycode string of ASCII-only symbols.\n */\nconst encode = function(input) {\n\tconst output = [];\n\n\t// Convert the input in UCS-2 to an array of Unicode code points.\n\tinput = ucs2decode(input);\n\n\t// Cache the length.\n\tlet inputLength = input.length;\n\n\t// Initialize the state.\n\tlet n = initialN;\n\tlet delta = 0;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points.\n\tfor (const currentValue of input) {\n\t\tif (currentValue < 0x80) {\n\t\t\toutput.push(stringFromCharCode(currentValue));\n\t\t}\n\t}\n\n\tlet basicLength = output.length;\n\tlet handledCPCount = basicLength;\n\n\t// `handledCPCount` is the number of code points that have been handled;\n\t// `basicLength` is the number of basic code points.\n\n\t// Finish the basic string with a delimiter unless it's empty.\n\tif (basicLength) {\n\t\toutput.push(delimiter);\n\t}\n\n\t// Main encoding loop:\n\twhile (handledCPCount < inputLength) {\n\n\t\t// All non-basic code points < n have been handled already. Find the next\n\t\t// larger one:\n\t\tlet m = maxInt;\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue >= n && currentValue < m) {\n\t\t\t\tm = currentValue;\n\t\t\t}\n\t\t}\n\n\t\t// Increase `delta` enough to advance the decoder's state to ,\n\t\t// but guard against overflow.\n\t\tconst handledCPCountPlusOne = handledCPCount + 1;\n\t\tif (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tdelta += (m - n) * handledCPCountPlusOne;\n\t\tn = m;\n\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue < n && ++delta > maxInt) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\t\t\tif (currentValue == n) {\n\t\t\t\t// Represent delta as a generalized variable-length integer.\n\t\t\t\tlet q = delta;\n\t\t\t\tfor (let k = base; /* no condition */; k += base) {\n\t\t\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\t\t\t\t\tif (q < t) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst qMinusT = q - t;\n\t\t\t\t\tconst baseMinusT = base - t;\n\t\t\t\t\toutput.push(\n\t\t\t\t\t\tstringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n\t\t\t\t\t);\n\t\t\t\t\tq = floor(qMinusT / baseMinusT);\n\t\t\t\t}\n\n\t\t\t\toutput.push(stringFromCharCode(digitToBasic(q, 0)));\n\t\t\t\tbias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n\t\t\t\tdelta = 0;\n\t\t\t\t++handledCPCount;\n\t\t\t}\n\t\t}\n\n\t\t++delta;\n\t\t++n;\n\n\t}\n\treturn output.join('');\n};\n\n/**\n * Converts a Punycode string representing a domain name or an email address\n * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n * it doesn't matter if you call it on a string that has already been\n * converted to Unicode.\n * @memberOf punycode\n * @param {String} input The Punycoded domain name or email address to\n * convert to Unicode.\n * @returns {String} The Unicode representation of the given Punycode\n * string.\n */\nconst toUnicode = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexPunycode.test(string)\n\t\t\t? decode(string.slice(4).toLowerCase())\n\t\t\t: string;\n\t});\n};\n\n/**\n * Converts a Unicode string representing a domain name or an email address to\n * Punycode. Only the non-ASCII parts of the domain name will be converted,\n * i.e. it doesn't matter if you call it with a domain that's already in\n * ASCII.\n * @memberOf punycode\n * @param {String} input The domain name or email address to convert, as a\n * Unicode string.\n * @returns {String} The Punycode representation of the given domain name or\n * email address.\n */\nconst toASCII = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexNonASCII.test(string)\n\t\t\t? 'xn--' + encode(string)\n\t\t\t: string;\n\t});\n};\n\n/*--------------------------------------------------------------------------*/\n\n/** Define the public API */\nconst punycode = {\n\t/**\n\t * A string representing the current Punycode.js version number.\n\t * @memberOf punycode\n\t * @type String\n\t */\n\t'version': '2.1.0',\n\t/**\n\t * An object of methods to convert from JavaScript's internal character\n\t * representation (UCS-2) to Unicode code points, and back.\n\t * @see \n\t * @memberOf punycode\n\t * @type Object\n\t */\n\t'ucs2': {\n\t\t'decode': ucs2decode,\n\t\t'encode': ucs2encode\n\t},\n\t'decode': decode,\n\t'encode': encode,\n\t'toASCII': toASCII,\n\t'toUnicode': toUnicode\n};\n\nexport default punycode;\n","import { URIRegExps } from \"./uri\";\nimport { buildExps } from \"./regexps-uri\";\n\nexport default buildExps(true);\n","import { URIRegExps } from \"./uri\";\nimport { merge, subexp } from \"./util\";\n\nexport function buildExps(isIRI:boolean):URIRegExps {\n\tconst\n\t\tALPHA$$ = \"[A-Za-z]\",\n\t\tCR$ = \"[\\\\x0D]\",\n\t\tDIGIT$$ = \"[0-9]\",\n\t\tDQUOTE$$ = \"[\\\\x22]\",\n\t\tHEXDIG$$ = merge(DIGIT$$, \"[A-Fa-f]\"), //case-insensitive\n\t\tLF$$ = \"[\\\\x0A]\",\n\t\tSP$$ = \"[\\\\x20]\",\n\t\tPCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)), //expanded\n\t\tGEN_DELIMS$$ = \"[\\\\:\\\\/\\\\?\\\\#\\\\[\\\\]\\\\@]\",\n\t\tSUB_DELIMS$$ = \"[\\\\!\\\\$\\\\&\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\=]\",\n\t\tRESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),\n\t\tUCSCHAR$$ = isIRI ? \"[\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF]\" : \"[]\", //subset, excludes bidi control characters\n\t\tIPRIVATE$$ = isIRI ? \"[\\\\uE000-\\\\uF8FF]\" : \"[]\", //subset\n\t\tUNRESERVED$$ = merge(ALPHA$$, DIGIT$$, \"[\\\\-\\\\.\\\\_\\\\~]\", UCSCHAR$$),\n\t\tSCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\") + \"*\"),\n\t\tUSERINFO$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\")) + \"*\"),\n\t\tDEC_OCTET$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"[1-9]\" + DIGIT$$) + \"|\" + DIGIT$$),\n\t\tDEC_OCTET_RELAXED$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"0?[1-9]\" + DIGIT$$) + \"|0?0?\" + DIGIT$$), //relaxed parsing rules\n\t\tIPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$),\n\t\tH16$ = subexp(HEXDIG$$ + \"{1,4}\"),\n\t\tLS32$ = subexp(subexp(H16$ + \"\\\\:\" + H16$) + \"|\" + IPV4ADDRESS$),\n\t\tIPV6ADDRESS1$ = subexp( subexp(H16$ + \"\\\\:\") + \"{6}\" + LS32$), // 6( h16 \":\" ) ls32\n\t\tIPV6ADDRESS2$ = subexp( \"\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{5}\" + LS32$), // \"::\" 5( h16 \":\" ) ls32\n\t\tIPV6ADDRESS3$ = subexp(subexp( H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{4}\" + LS32$), //[ h16 ] \"::\" 4( h16 \":\" ) ls32\n\t\tIPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,1}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{3}\" + LS32$), //[ *1( h16 \":\" ) h16 ] \"::\" 3( h16 \":\" ) ls32\n\t\tIPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,2}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{2}\" + LS32$), //[ *2( h16 \":\" ) h16 ] \"::\" 2( h16 \":\" ) ls32\n\t\tIPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,3}\" + H16$) + \"?\\\\:\\\\:\" + H16$ + \"\\\\:\" + LS32$), //[ *3( h16 \":\" ) h16 ] \"::\" h16 \":\" ls32\n\t\tIPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,4}\" + H16$) + \"?\\\\:\\\\:\" + LS32$), //[ *4( h16 \":\" ) h16 ] \"::\" ls32\n\t\tIPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,5}\" + H16$) + \"?\\\\:\\\\:\" + H16$ ), //[ *5( h16 \":\" ) h16 ] \"::\" h16\n\t\tIPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,6}\" + H16$) + \"?\\\\:\\\\:\" ), //[ *6( h16 \":\" ) h16 ] \"::\"\n\t\tIPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join(\"|\")),\n\t\tZONEID$ = subexp(subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$) + \"+\"), //RFC 6874\n\t\tIPV6ADDRZ$ = subexp(IPV6ADDRESS$ + \"\\\\%25\" + ZONEID$), //RFC 6874\n\t\tIPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + ZONEID$), //RFC 6874, with relaxed parsing rules\n\t\tIPVFUTURE$ = subexp(\"[vV]\" + HEXDIG$$ + \"+\\\\.\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\") + \"+\"),\n\t\tIP_LITERAL$ = subexp(\"\\\\[\" + subexp(IPV6ADDRZ_RELAXED$ + \"|\" + IPV6ADDRESS$ + \"|\" + IPVFUTURE$) + \"\\\\]\"), //RFC 6874\n\t\tREG_NAME$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$)) + \"*\"),\n\t\tHOST$ = subexp(IP_LITERAL$ + \"|\" + IPV4ADDRESS$ + \"(?!\" + REG_NAME$ + \")\" + \"|\" + REG_NAME$),\n\t\tPORT$ = subexp(DIGIT$$ + \"*\"),\n\t\tAUTHORITY$ = subexp(subexp(USERINFO$ + \"@\") + \"?\" + HOST$ + subexp(\"\\\\:\" + PORT$) + \"?\"),\n\t\tPCHAR$ = subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@]\")),\n\t\tSEGMENT$ = subexp(PCHAR$ + \"*\"),\n\t\tSEGMENT_NZ$ = subexp(PCHAR$ + \"+\"),\n\t\tSEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\@]\")) + \"+\"),\n\t\tPATH_ABEMPTY$ = subexp(subexp(\"\\\\/\" + SEGMENT$) + \"*\"),\n\t\tPATH_ABSOLUTE$ = subexp(\"\\\\/\" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + \"?\"), //simplified\n\t\tPATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_EMPTY$ = \"(?!\" + PCHAR$ + \")\",\n\t\tPATH$ = subexp(PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tQUERY$ = subexp(subexp(PCHAR$ + \"|\" + merge(\"[\\\\/\\\\?]\", IPRIVATE$$)) + \"*\"),\n\t\tFRAGMENT$ = subexp(subexp(PCHAR$ + \"|[\\\\/\\\\?]\") + \"*\"),\n\t\tHIER_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tURI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tRELATIVE_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$),\n\t\tRELATIVE$ = subexp(RELATIVE_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tURI_REFERENCE$ = subexp(URI$ + \"|\" + RELATIVE$),\n\t\tABSOLUTE_URI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\"),\n\n\t\tGENERIC_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tRELATIVE_REF$ = \"^(){0}\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tABSOLUTE_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?$\",\n\t\tSAMEDOC_REF$ = \"^\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tAUTHORITY_REF$ = \"^\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?$\"\n\t;\n\n\treturn {\n\t\tNOT_SCHEME : new RegExp(merge(\"[^]\", ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\"), \"g\"),\n\t\tNOT_USERINFO : new RegExp(merge(\"[^\\\\%\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_HOST : new RegExp(merge(\"[^\\\\%\\\\[\\\\]\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH : new RegExp(merge(\"[^\\\\%\\\\/\\\\:\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH_NOSCHEME : new RegExp(merge(\"[^\\\\%\\\\/\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_QUERY : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\", IPRIVATE$$), \"g\"),\n\t\tNOT_FRAGMENT : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\"), \"g\"),\n\t\tESCAPE : new RegExp(merge(\"[^]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tUNRESERVED : new RegExp(UNRESERVED$$, \"g\"),\n\t\tOTHER_CHARS : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, RESERVED$$), \"g\"),\n\t\tPCT_ENCODED : new RegExp(PCT_ENCODED$, \"g\"),\n\t\tIPV4ADDRESS : new RegExp(\"^(\" + IPV4ADDRESS$ + \")$\"),\n\t\tIPV6ADDRESS : new RegExp(\"^\\\\[?(\" + IPV6ADDRESS$ + \")\" + subexp(subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + \"(\" + ZONEID$ + \")\") + \"?\\\\]?$\") //RFC 6874, with relaxed parsing rules\n\t};\n}\n\nexport default buildExps(false);\n","export function merge(...sets:Array):string {\n\tif (sets.length > 1) {\n\t\tsets[0] = sets[0].slice(0, -1);\n\t\tconst xl = sets.length - 1;\n\t\tfor (let x = 1; x < xl; ++x) {\n\t\t\tsets[x] = sets[x].slice(1, -1);\n\t\t}\n\t\tsets[xl] = sets[xl].slice(1);\n\t\treturn sets.join('');\n\t} else {\n\t\treturn sets[0];\n\t}\n}\n\nexport function subexp(str:string):string {\n\treturn \"(?:\" + str + \")\";\n}\n\nexport function typeOf(o:any):string {\n\treturn o === undefined ? \"undefined\" : (o === null ? \"null\" : Object.prototype.toString.call(o).split(\" \").pop().split(\"]\").shift().toLowerCase());\n}\n\nexport function toUpperCase(str:string):string {\n\treturn str.toUpperCase();\n}\n\nexport function toArray(obj:any):Array {\n\treturn obj !== undefined && obj !== null ? (obj instanceof Array ? obj : (typeof obj.length !== \"number\" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj))) : [];\n}\n\n\nexport function assign(target: object, source: any): any {\n\tconst obj = target as any;\n\tif (source) {\n\t\tfor (const key in source) {\n\t\t\tobj[key] = source[key];\n\t\t}\n\t}\n\treturn obj;\n}"],"names":["SCHEMES","uuid","scheme","urn","mailto","wss","ws","https","http","urnComponents","nss","uuidComponents","toLowerCase","options","error","tolerant","match","UUID","undefined","handler","uriComponents","path","nid","schemeHandler","serialize","urnScheme","parse","matches","components","URN_PARSE","query","fields","join","length","push","name","replace","PCT_ENCODED","decodeUnreserved","toUpperCase","NOT_HFNAME","pctEncChar","headers","NOT_HFVALUE","O","mailtoComponents","body","subject","to","x","localPart","domain","iri","e","punycode","toASCII","unescapeComponent","toUnicode","toAddr","slice","atIdx","NOT_LOCAL_PART","lastIndexOf","String","xl","toArray","addr","unicodeSupport","split","unknownHeaders","hfield","toAddrs","hfields","decStr","UNRESERVED","str","pctDecChars","RegExp","merge","UNRESERVED$$","SOME_DELIMS$$","ATEXT$$","VCHAR$$","PCT_ENCODED$","QTEXT$$","subexp","HEXDIG$$","isIRI","domainHost","wsComponents","fragment","resourceName","secure","port","isSecure","host","toString","URI_PROTOCOL","IRI_PROTOCOL","ESCAPE","escapeComponent","uriA","uriB","typeOf","equal","uri","normalize","resolveComponents","baseURI","schemelessOptions","relativeURI","assign","resolve","target","relative","base","userinfo","removeDotSegments","charAt","skipNormalization","uriTokens","s","authority","absolutePath","reference","_recomposeAuthority","protocol","IPV6ADDRESS","test","output","Error","input","im","RDS5","pop","RDS3","RDS2","RDS1","$1","$2","_normalizeIPv6","_normalizeIPv4","_","uriString","isNaN","indexOf","parseInt","NO_MATCH_IS_UNDEFINED","URI_PARSE","newHost","zone","newFirst","newLast","longestZeroFields","index","b","a","allZeroFields","sort","acc","lastLongest","field","reduce","fieldCount","isLastFieldIPv4Address","firstFields","lastFields","lastFieldsStart","Array","IPV4ADDRESS","last","map","_stripLeadingZeros","first","address","reverse","NOT_FRAGMENT","NOT_QUERY","NOT_PATH","NOT_PATH_NOSCHEME","NOT_HOST","NOT_USERINFO","NOT_SCHEME","_normalizeComponentEncoding","newStr","substr","i","fromCharCode","c","c2","c3","il","chr","charCodeAt","encode","decode","ucs2encode","ucs2decode","regexNonASCII","string","mapDomain","regexPunycode","n","delta","handledCPCount","adapt","handledCPCountPlusOne","basicLength","stringFromCharCode","digitToBasic","q","floor","qMinusT","baseMinusT","t","k","bias","tMin","tMax","currentValue","maxInt","m","inputLength","delimiter","initialBias","initialN","fromCodePoint","splice","out","oldi","w","digit","basicToDigit","basic","j","baseMinusTMin","skew","numPoints","firstTime","damp","flag","codePoint","array","value","extra","counter","result","encoded","labels","fn","regexSeparators","parts","RangeError","errors","type","Math","buildExps","IPV6ADDRESS$","ZONEID$","IPV4ADDRESS$","RESERVED$$","SUB_DELIMS$$","IPRIVATE$$","ALPHA$$","DIGIT$$","AUTHORITY_REF$","USERINFO$","HOST$","PORT$","SAMEDOC_REF$","FRAGMENT$","ABSOLUTE_REF$","SCHEME$","PATH_ABEMPTY$","PATH_ABSOLUTE$","PATH_ROOTLESS$","PATH_EMPTY$","QUERY$","RELATIVE_REF$","PATH_NOSCHEME$","GENERIC_REF$","ABSOLUTE_URI$","HIER_PART$","URI_REFERENCE$","URI$","RELATIVE$","RELATIVE_PART$","AUTHORITY$","PCHAR$","PATH$","SEGMENT_NZ$","SEGMENT_NZ_NC$","SEGMENT$","IP_LITERAL$","REG_NAME$","IPV6ADDRZ_RELAXED$","IPVFUTURE$","IPV6ADDRESS1$","IPV6ADDRESS2$","IPV6ADDRESS3$","IPV6ADDRESS4$","IPV6ADDRESS5$","IPV6ADDRESS6$","IPV6ADDRESS7$","IPV6ADDRESS8$","IPV6ADDRESS9$","H16$","LS32$","DEC_OCTET_RELAXED$","DEC_OCTET$","UCSCHAR$$","GEN_DELIMS$$","SP$$","DQUOTE$$","CR$","obj","key","source","setInterval","call","prototype","o","Object","shift","sets"],"mappings":";;;;;;;AYAA,SAAA8E,KAAA,GAAA;sCAAyBsP,IAAzB;YAAA;;;QACKA,KAAKnS,MAAL,GAAc,CAAlB,EAAqB;aACf,CAAL,IAAUmS,KAAK,CAAL,EAAQzQ,KAAR,CAAc,CAAd,EAAiB,CAAC,CAAlB,CAAV;YACMK,KAAKoQ,KAAKnS,MAAL,GAAc,CAAzB;aACK,IAAIgB,IAAI,CAAb,EAAgBA,IAAIe,EAApB,EAAwB,EAAEf,CAA1B,EAA6B;iBACvBA,CAAL,IAAUmR,KAAKnR,CAAL,EAAQU,KAAR,CAAc,CAAd,EAAiB,CAAC,CAAlB,CAAV;;aAEIK,EAAL,IAAWoQ,KAAKpQ,EAAL,EAASL,KAAT,CAAe,CAAf,CAAX;eACOyQ,KAAKpS,IAAL,CAAU,EAAV,CAAP;KAPD,MAQO;eACCoS,KAAK,CAAL,CAAP;;;AAIF,AAAA,SAAA/O,MAAA,CAAuBV,GAAvB,EAAA;WACQ,QAAQA,GAAR,GAAc,GAArB;;AAGD,AAAA,SAAA4B,MAAA,CAAuB0N,CAAvB,EAAA;WACQA,MAAM/S,SAAN,GAAkB,WAAlB,GAAiC+S,MAAM,IAAN,GAAa,MAAb,GAAsBC,OAAOF,SAAP,CAAiBhO,QAAjB,CAA0B+N,IAA1B,CAA+BE,CAA/B,EAAkC7P,KAAlC,CAAwC,GAAxC,EAA6CkE,GAA7C,GAAmDlE,KAAnD,CAAyD,GAAzD,EAA8D+P,KAA9D,GAAsEvT,WAAtE,EAA9D;;AAGD,AAAA,SAAA2B,WAAA,CAA4BoC,GAA5B,EAAA;WACQA,IAAIpC,WAAJ,EAAP;;AAGD,AAAA,SAAA0B,OAAA,CAAwB0P,GAAxB,EAAA;WACQA,QAAQzS,SAAR,IAAqByS,QAAQ,IAA7B,GAAqCA,eAAenJ,KAAf,GAAuBmJ,GAAvB,GAA8B,OAAOA,IAAI1R,MAAX,KAAsB,QAAtB,IAAkC0R,IAAIvP,KAAtC,IAA+CuP,IAAIG,WAAnD,IAAkEH,IAAII,IAAtE,GAA6E,CAACJ,GAAD,CAA7E,GAAqFnJ,MAAMwJ,SAAN,CAAgBrQ,KAAhB,CAAsBoQ,IAAtB,CAA2BJ,GAA3B,CAAxJ,GAA4L,EAAnM;;AAID,AAAA,SAAA5M,MAAA,CAAuBE,MAAvB,EAAuC4M,MAAvC,EAAA;QACOF,MAAM1M,MAAZ;QACI4M,MAAJ,EAAY;aACN,IAAMD,GAAX,IAAkBC,MAAlB,EAA0B;gBACrBD,GAAJ,IAAWC,OAAOD,GAAP,CAAX;;;WAGKD,GAAP;;;ADnCD,SAAA3D,SAAA,CAA0BzK,KAA1B,EAAA;QAEEgL,UAAU,UADX;QAECmD,MAAM,SAFP;QAGClD,UAAU,OAHX;QAICiD,WAAW,SAJZ;QAKCnO,WAAWR,MAAM0L,OAAN,EAAe,UAAf,CALZ;;WAMQ,SANR;QAOCgD,OAAO,SAPR;QAQCrO,eAAeE,OAAOA,OAAO,YAAYC,QAAZ,GAAuB,GAAvB,GAA6BA,QAA7B,GAAwCA,QAAxC,GAAmD,GAAnD,GAAyDA,QAAzD,GAAoEA,QAA3E,IAAuF,GAAvF,GAA6FD,OAAO,gBAAgBC,QAAhB,GAA2B,GAA3B,GAAiCA,QAAjC,GAA4CA,QAAnD,CAA7F,GAA4J,GAA5J,GAAkKD,OAAO,MAAMC,QAAN,GAAiBA,QAAxB,CAAzK,CARhB;;mBASgB,yBAThB;QAUC+K,eAAe,qCAVhB;QAWCD,aAAatL,MAAMyO,YAAN,EAAoBlD,YAApB,CAXd;QAYCiD,YAAY/N,QAAQ,6EAAR,GAAwF,IAZrG;;iBAacA,QAAQ,mBAAR,GAA8B,IAb5C;;mBAcgBT,MAAMyL,OAAN,EAAeC,OAAf,EAAwB,gBAAxB,EAA0C8C,SAA1C,CAdhB;QAeCtC,UAAU3L,OAAOkL,UAAUzL,MAAMyL,OAAN,EAAeC,OAAf,EAAwB,aAAxB,CAAV,GAAmD,GAA1D,CAfX;QAgBCE,YAAYrL,OAAOA,OAAOF,eAAe,GAAf,GAAqBL,MAAMC,YAAN,EAAoBsL,YAApB,EAAkC,OAAlC,CAA5B,IAA0E,GAAjF,CAhBb;QAiBCgD,aAAahO,OAAOA,OAAO,SAAP,IAAoB,GAApB,GAA0BA,OAAO,WAAWmL,OAAlB,CAA1B,GAAuD,GAAvD,GAA6DnL,OAAO,MAAMmL,OAAN,GAAgBA,OAAvB,CAA7D,GAA+F,GAA/F,GAAqGnL,OAAO,UAAUmL,OAAjB,CAArG,GAAiI,GAAjI,GAAuIA,OAA9I,CAjBd;QAkBC4C,qBAAqB/N,OAAOA,OAAO,SAAP,IAAoB,GAApB,GAA0BA,OAAO,WAAWmL,OAAlB,CAA1B,GAAuD,GAAvD,GAA6DnL,OAAO,MAAMmL,OAAN,GAAgBA,OAAvB,CAA7D,GAA+F,GAA/F,GAAqGnL,OAAO,YAAYmL,OAAnB,CAArG,GAAmI,OAAnI,GAA6IA,OAApJ,CAlBtB;;mBAmBgBnL,OAAO+N,qBAAqB,KAArB,GAA6BA,kBAA7B,GAAkD,KAAlD,GAA0DA,kBAA1D,GAA+E,KAA/E,GAAuFA,kBAA9F,CAnBhB;QAoBCF,OAAO7N,OAAOC,WAAW,OAAlB,CApBR;QAqBC6N,QAAQ9N,OAAOA,OAAO6N,OAAO,KAAP,GAAeA,IAAtB,IAA8B,GAA9B,GAAoC/C,YAA3C,CArBT;QAsBCsC,gBAAgBpN,OAAmEA,OAAO6N,OAAO,KAAd,IAAuB,KAAvB,GAA+BC,KAAlG,CAtBjB;;oBAuBiB9N,OAAwD,WAAWA,OAAO6N,OAAO,KAAd,CAAX,GAAkC,KAAlC,GAA0CC,KAAlG,CAvBjB;;oBAwBiB9N,OAAOA,OAAwC6N,IAAxC,IAAgD,SAAhD,GAA4D7N,OAAO6N,OAAO,KAAd,CAA5D,GAAmF,KAAnF,GAA2FC,KAAlG,CAxBjB;;oBAyBiB9N,OAAOA,OAAOA,OAAO6N,OAAO,KAAd,IAAuB,OAAvB,GAAiCA,IAAxC,IAAgD,SAAhD,GAA4D7N,OAAO6N,OAAO,KAAd,CAA5D,GAAmF,KAAnF,GAA2FC,KAAlG,CAzBjB;;oBA0BiB9N,OAAOA,OAAOA,OAAO6N,OAAO,KAAd,IAAuB,OAAvB,GAAiCA,IAAxC,IAAgD,SAAhD,GAA4D7N,OAAO6N,OAAO,KAAd,CAA5D,GAAmF,KAAnF,GAA2FC,KAAlG,CA1BjB;;oBA2BiB9N,OAAOA,OAAOA,OAAO6N,OAAO,KAAd,IAAuB,OAAvB,GAAiCA,IAAxC,IAAgD,SAAhD,GAAmEA,IAAnE,GAA0E,KAA1E,GAA2FC,KAAlG,CA3BjB;;oBA4BiB9N,OAAOA,OAAOA,OAAO6N,OAAO,KAAd,IAAuB,OAAvB,GAAiCA,IAAxC,IAAgD,SAAhD,GAA2FC,KAAlG,CA5BjB;;oBA6BiB9N,OAAOA,OAAOA,OAAO6N,OAAO,KAAd,IAAuB,OAAvB,GAAiCA,IAAxC,IAAgD,SAAhD,GAA2FA,IAAlG,CA7BjB;;oBA8BiB7N,OAAOA,OAAOA,OAAO6N,OAAO,KAAd,IAAuB,OAAvB,GAAiCA,IAAxC,IAAgD,SAAvD,CA9BjB;;mBA+BgB7N,OAAO,CAACoN,aAAD,EAAgBC,aAAhB,EAA+BC,aAA/B,EAA8CC,aAA9C,EAA6DC,aAA7D,EAA4EC,aAA5E,EAA2FC,aAA3F,EAA0GC,aAA1G,EAAyHC,aAAzH,EAAwIjR,IAAxI,CAA6I,GAA7I,CAAP,CA/BhB;QAgCCkO,UAAU7K,OAAOA,OAAON,eAAe,GAAf,GAAqBI,YAA5B,IAA4C,GAAnD,CAhCX;;iBAiCcE,OAAO4K,eAAe,OAAf,GAAyBC,OAAhC,CAjCd;;yBAkCsB7K,OAAO4K,eAAe5K,OAAO,iBAAiBC,QAAjB,GAA4B,MAAnC,CAAf,GAA4D4K,OAAnE,CAlCtB;;iBAmCc7K,OAAO,SAASC,QAAT,GAAoB,MAApB,GAA6BR,MAAMC,YAAN,EAAoBsL,YAApB,EAAkC,OAAlC,CAA7B,GAA0E,GAAjF,CAnCd;QAoCCgC,cAAchN,OAAO,QAAQA,OAAOkN,qBAAqB,GAArB,GAA2BtC,YAA3B,GAA0C,GAA1C,GAAgDuC,UAAvD,CAAR,GAA6E,KAApF,CApCf;;gBAqCanN,OAAOA,OAAOF,eAAe,GAAf,GAAqBL,MAAMC,YAAN,EAAoBsL,YAApB,CAA5B,IAAiE,GAAxE,CArCb;QAsCCM,QAAQtL,OAAOgN,cAAc,GAAd,GAAoBlC,YAApB,GAAmC,KAAnC,GAA2CmC,SAA3C,GAAuD,GAAvD,GAA6D,GAA7D,GAAmEA,SAA1E,CAtCT;QAuCC1B,QAAQvL,OAAOmL,UAAU,GAAjB,CAvCT;QAwCCuB,aAAa1M,OAAOA,OAAOqL,YAAY,GAAnB,IAA0B,GAA1B,GAAgCC,KAAhC,GAAwCtL,OAAO,QAAQuL,KAAf,CAAxC,GAAgE,GAAvE,CAxCd;QAyCCoB,SAAS3M,OAAOF,eAAe,GAAf,GAAqBL,MAAMC,YAAN,EAAoBsL,YAApB,EAAkC,UAAlC,CAA5B,CAzCV;QA0CC+B,WAAW/M,OAAO2M,SAAS,GAAhB,CA1CZ;QA2CCE,cAAc7M,OAAO2M,SAAS,GAAhB,CA3Cf;QA4CCG,iBAAiB9M,OAAOA,OAAOF,eAAe,GAAf,GAAqBL,MAAMC,YAAN,EAAoBsL,YAApB,EAAkC,OAAlC,CAA5B,IAA0E,GAAjF,CA5ClB;QA6CCY,gBAAgB5L,OAAOA,OAAO,QAAQ+M,QAAf,IAA2B,GAAlC,CA7CjB;QA8CClB,iBAAiB7L,OAAO,QAAQA,OAAO6M,cAAcjB,aAArB,CAAR,GAA8C,GAArD,CA9ClB;;qBA+CkB5L,OAAO8M,iBAAiBlB,aAAxB,CA/ClB;;qBAgDkB5L,OAAO6M,cAAcjB,aAArB,CAhDlB;;kBAiDe,QAAQe,MAAR,GAAiB,GAjDhC;QAkDCC,QAAQ5M,OAAO4L,gBAAgB,GAAhB,GAAsBC,cAAtB,GAAuC,GAAvC,GAA6CK,cAA7C,GAA8D,GAA9D,GAAoEJ,cAApE,GAAqF,GAArF,GAA2FC,WAAlG,CAlDT;QAmDCC,SAAShM,OAAOA,OAAO2M,SAAS,GAAT,GAAelN,MAAM,UAAN,EAAkBwL,UAAlB,CAAtB,IAAuD,GAA9D,CAnDV;QAoDCQ,YAAYzL,OAAOA,OAAO2M,SAAS,WAAhB,IAA+B,GAAtC,CApDb;QAqDCN,aAAarM,OAAOA,OAAO,WAAW0M,UAAX,GAAwBd,aAA/B,IAAgD,GAAhD,GAAsDC,cAAtD,GAAuE,GAAvE,GAA6EC,cAA7E,GAA8F,GAA9F,GAAoGC,WAA3G,CArDd;QAsDCQ,OAAOvM,OAAO2L,UAAU,KAAV,GAAkBU,UAAlB,GAA+BrM,OAAO,QAAQgM,MAAf,CAA/B,GAAwD,GAAxD,GAA8DhM,OAAO,QAAQyL,SAAf,CAA9D,GAA0F,GAAjG,CAtDR;QAuDCgB,iBAAiBzM,OAAOA,OAAO,WAAW0M,UAAX,GAAwBd,aAA/B,IAAgD,GAAhD,GAAsDC,cAAtD,GAAuE,GAAvE,GAA6EK,cAA7E,GAA8F,GAA9F,GAAoGH,WAA3G,CAvDlB;QAwDCS,YAAYxM,OAAOyM,iBAAiBzM,OAAO,QAAQgM,MAAf,CAAjB,GAA0C,GAA1C,GAAgDhM,OAAO,QAAQyL,SAAf,CAAhD,GAA4E,GAAnF,CAxDb;QAyDCa,iBAAiBtM,OAAOuM,OAAO,GAAP,GAAaC,SAApB,CAzDlB;QA0DCJ,gBAAgBpM,OAAO2L,UAAU,KAAV,GAAkBU,UAAlB,GAA+BrM,OAAO,QAAQgM,MAAf,CAA/B,GAAwD,GAA/D,CA1DjB;QA4DCG,eAAe,OAAOR,OAAP,GAAiB,MAAjB,GAA0B3L,OAAOA,OAAO,YAAYA,OAAO,MAAMqL,SAAN,GAAkB,IAAzB,CAAZ,GAA6C,IAA7C,GAAoDC,KAApD,GAA4D,GAA5D,GAAkEtL,OAAO,SAASuL,KAAT,GAAiB,GAAxB,CAAlE,GAAiG,IAAxG,IAAgH,IAAhH,GAAuHK,aAAvH,GAAuI,GAAvI,GAA6IC,cAA7I,GAA8J,GAA9J,GAAoKC,cAApK,GAAqL,GAArL,GAA2LC,WAA3L,GAAyM,GAAhN,CAA1B,GAAiP/L,OAAO,SAASgM,MAAT,GAAkB,GAAzB,CAAjP,GAAiR,GAAjR,GAAuRhM,OAAO,SAASyL,SAAT,GAAqB,GAA5B,CAAvR,GAA0T,IA5D1U;QA6DCQ,gBAAgB,WAAWjM,OAAOA,OAAO,YAAYA,OAAO,MAAMqL,SAAN,GAAkB,IAAzB,CAAZ,GAA6C,IAA7C,GAAoDC,KAApD,GAA4D,GAA5D,GAAkEtL,OAAO,SAASuL,KAAT,GAAiB,GAAxB,CAAlE,GAAiG,IAAxG,IAAgH,IAAhH,GAAuHK,aAAvH,GAAuI,GAAvI,GAA6IC,cAA7I,GAA8J,GAA9J,GAAoKK,cAApK,GAAqL,GAArL,GAA2LH,WAA3L,GAAyM,GAAhN,CAAX,GAAkO/L,OAAO,SAASgM,MAAT,GAAkB,GAAzB,CAAlO,GAAkQ,GAAlQ,GAAwQhM,OAAO,SAASyL,SAAT,GAAqB,GAA5B,CAAxQ,GAA2S,IA7D5T;QA8DCC,gBAAgB,OAAOC,OAAP,GAAiB,MAAjB,GAA0B3L,OAAOA,OAAO,YAAYA,OAAO,MAAMqL,SAAN,GAAkB,IAAzB,CAAZ,GAA6C,IAA7C,GAAoDC,KAApD,GAA4D,GAA5D,GAAkEtL,OAAO,SAASuL,KAAT,GAAiB,GAAxB,CAAlE,GAAiG,IAAxG,IAAgH,IAAhH,GAAuHK,aAAvH,GAAuI,GAAvI,GAA6IC,cAA7I,GAA8J,GAA9J,GAAoKC,cAApK,GAAqL,GAArL,GAA2LC,WAA3L,GAAyM,GAAhN,CAA1B,GAAiP/L,OAAO,SAASgM,MAAT,GAAkB,GAAzB,CAAjP,GAAiR,IA9DlS;QA+DCR,eAAe,MAAMxL,OAAO,SAASyL,SAAT,GAAqB,GAA5B,CAAN,GAAyC,IA/DzD;QAgECL,iBAAiB,MAAMpL,OAAO,MAAMqL,SAAN,GAAkB,IAAzB,CAAN,GAAuC,IAAvC,GAA8CC,KAA9C,GAAsD,GAAtD,GAA4DtL,OAAO,SAASuL,KAAT,GAAiB,GAAxB,CAA5D,GAA2F,IAhE7G;WAmEO;oBACO,IAAI/L,MAAJ,CAAWC,MAAM,KAAN,EAAayL,OAAb,EAAsBC,OAAtB,EAA+B,aAA/B,CAAX,EAA0D,GAA1D,CADP;sBAES,IAAI3L,MAAJ,CAAWC,MAAM,WAAN,EAAmBC,YAAnB,EAAiCsL,YAAjC,CAAX,EAA2D,GAA3D,CAFT;kBAGK,IAAIxL,MAAJ,CAAWC,MAAM,iBAAN,EAAyBC,YAAzB,EAAuCsL,YAAvC,CAAX,EAAiE,GAAjE,CAHL;kBAIK,IAAIxL,MAAJ,CAAWC,MAAM,iBAAN,EAAyBC,YAAzB,EAAuCsL,YAAvC,CAAX,EAAiE,GAAjE,CAJL;2BAKc,IAAIxL,MAAJ,CAAWC,MAAM,cAAN,EAAsBC,YAAtB,EAAoCsL,YAApC,CAAX,EAA8D,GAA9D,CALd;mBAMM,IAAIxL,MAAJ,CAAWC,MAAM,QAAN,EAAgBC,YAAhB,EAA8BsL,YAA9B,EAA4C,gBAA5C,EAA8DC,UAA9D,CAAX,EAAsF,GAAtF,CANN;sBAOS,IAAIzL,MAAJ,CAAWC,MAAM,QAAN,EAAgBC,YAAhB,EAA8BsL,YAA9B,EAA4C,gBAA5C,CAAX,EAA0E,GAA1E,CAPT;gBAQG,IAAIxL,MAAJ,CAAWC,MAAM,KAAN,EAAaC,YAAb,EAA2BsL,YAA3B,CAAX,EAAqD,GAArD,CARH;oBASO,IAAIxL,MAAJ,CAAWE,YAAX,EAAyB,GAAzB,CATP;qBAUQ,IAAIF,MAAJ,CAAWC,MAAM,QAAN,EAAgBC,YAAhB,EAA8BqL,UAA9B,CAAX,EAAsD,GAAtD,CAVR;qBAWQ,IAAIvL,MAAJ,CAAWM,YAAX,EAAyB,GAAzB,CAXR;qBAYQ,IAAIN,MAAJ,CAAW,OAAOsL,YAAP,GAAsB,IAAjC,CAZR;qBAaQ,IAAItL,MAAJ,CAAW,WAAWoL,YAAX,GAA0B,GAA1B,GAAgC5K,OAAOA,OAAO,iBAAiBC,QAAjB,GAA4B,MAAnC,IAA6C,GAA7C,GAAmD4K,OAAnD,GAA6D,GAApE,CAAhC,GAA2G,QAAtH,CAbR;KAAP;;AAiBD,mBAAeF,UAAU,KAAV,CAAf;;ADrFA,mBAAeA,UAAU,IAAV,CAAf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ADDA;;AACA,IAAMpC,SAAS,UAAf;;;AAGA,IAAMzG,OAAO,EAAb;AACA,IAAMsG,OAAO,CAAb;AACA,IAAMC,OAAO,EAAb;AACA,IAAMkB,OAAO,EAAb;AACA,IAAMG,OAAO,GAAb;AACA,IAAMf,cAAc,EAApB;AACA,IAAMC,WAAW,GAAjB;AACA,IAAMF,YAAY,GAAlB;;;AAGA,IAAMtB,gBAAgB,OAAtB;AACA,IAAMH,gBAAgB,YAAtB;AACA,IAAMoD,kBAAkB,2BAAxB;;;AAGA,IAAMG,SAAS;aACF,iDADE;cAED,gDAFC;kBAGG;CAHlB;;;AAOA,IAAMlB,gBAAgBxH,OAAOsG,IAA7B;AACA,IAAMN,QAAQ4C,KAAK5C,KAAnB;AACA,IAAMH,qBAAqBjJ,OAAO4H,YAAlC;;;;;;;;;;AAUA,SAAS7K,OAAT,CAAegP,IAAf,EAAqB;OACd,IAAIF,UAAJ,CAAeC,OAAOC,IAAP,CAAf,CAAN;;;;;;;;;;;AAWD,SAASnF,GAAT,CAAauE,KAAb,EAAoBO,EAApB,EAAwB;KACjBH,SAAS,EAAf;KACIrN,SAASiN,MAAMjN,MAAnB;QACOA,QAAP,EAAiB;SACTA,MAAP,IAAiBwN,GAAGP,MAAMjN,MAAN,CAAH,CAAjB;;QAEMqN,MAAP;;;;;;;;;;;;;AAaD,SAAS9C,SAAT,CAAmBD,MAAnB,EAA2BkD,EAA3B,EAA+B;KACxBE,QAAQpD,OAAOnI,KAAP,CAAa,GAAb,CAAd;KACIkL,SAAS,EAAb;KACIK,MAAM1N,MAAN,GAAe,CAAnB,EAAsB;;;WAGZ0N,MAAM,CAAN,IAAW,GAApB;WACSA,MAAM,CAAN,CAAT;;;UAGQpD,OAAOnK,OAAP,CAAesN,eAAf,EAAgC,MAAhC,CAAT;KACMF,SAASjD,OAAOnI,KAAP,CAAa,GAAb,CAAf;KACMmL,UAAU5E,IAAI6E,MAAJ,EAAYC,EAAZ,EAAgBzN,IAAhB,CAAqB,GAArB,CAAhB;QACOsN,SAASC,OAAhB;;;;;;;;;;;;;;;;AAgBD,SAASlD,UAAT,CAAoBE,MAApB,EAA4B;KACrBtE,SAAS,EAAf;KACIoH,UAAU,CAAd;KACMpN,SAASsK,OAAOtK,MAAtB;QACOoN,UAAUpN,MAAjB,EAAyB;MAClBkN,QAAQ5C,OAAON,UAAP,CAAkBoD,SAAlB,CAAd;MACIF,SAAS,MAAT,IAAmBA,SAAS,MAA5B,IAAsCE,UAAUpN,MAApD,EAA4D;;OAErDmN,QAAQ7C,OAAON,UAAP,CAAkBoD,SAAlB,CAAd;OACI,CAACD,QAAQ,MAAT,KAAoB,MAAxB,EAAgC;;WACxBlN,IAAP,CAAY,CAAC,CAACiN,QAAQ,KAAT,KAAmB,EAApB,KAA2BC,QAAQ,KAAnC,IAA4C,OAAxD;IADD,MAEO;;;WAGClN,IAAP,CAAYiN,KAAZ;;;GARF,MAWO;UACCjN,IAAP,CAAYiN,KAAZ;;;QAGKlH,MAAP;;;;;;;;;;;AAWD,IAAMmE,aAAa,SAAbA,UAAa;QAASrI,OAAOmK,aAAP,iCAAwBgB,KAAxB,EAAT;CAAnB;;;;;;;;;;;AAWA,IAAMV,eAAe,SAAfA,YAAe,CAASS,SAAT,EAAoB;KACpCA,YAAY,IAAZ,GAAmB,IAAvB,EAA6B;SACrBA,YAAY,IAAnB;;KAEGA,YAAY,IAAZ,GAAmB,IAAvB,EAA6B;SACrBA,YAAY,IAAnB;;KAEGA,YAAY,IAAZ,GAAmB,IAAvB,EAA6B;SACrBA,YAAY,IAAnB;;QAEM9H,IAAP;CAVD;;;;;;;;;;;;;AAwBA,IAAM8F,eAAe,SAAfA,YAAe,CAASsB,KAAT,EAAgBS,IAAhB,EAAsB;;;QAGnCT,QAAQ,EAAR,GAAa,MAAMA,QAAQ,EAAd,CAAb,IAAkC,CAACS,QAAQ,CAAT,KAAe,CAAjD,CAAP;CAHD;;;;;;;AAWA,IAAMnC,QAAQ,SAARA,KAAQ,CAASF,KAAT,EAAgBkC,SAAhB,EAA2BC,SAA3B,EAAsC;KAC/CvB,IAAI,CAAR;SACQuB,YAAY3B,MAAMR,QAAQoC,IAAd,CAAZ,GAAkCpC,SAAS,CAAnD;UACSQ,MAAMR,QAAQkC,SAAd,CAAT;+BAC8BlC,QAAQgC,gBAAgBjB,IAAhB,IAAwB,CAA9D,EAAiEH,KAAKpG,IAAtE,EAA4E;UACnEgG,MAAMR,QAAQgC,aAAd,CAAR;;QAEMxB,MAAMI,IAAI,CAACoB,gBAAgB,CAAjB,IAAsBhC,KAAtB,IAA+BA,QAAQiC,IAAvC,CAAV,CAAP;CAPD;;;;;;;;;AAiBA,IAAMzC,SAAS,SAATA,MAAS,CAAShE,KAAT,EAAgB;;KAExBF,SAAS,EAAf;KACM6F,cAAc3F,MAAMlG,MAA1B;KACIyJ,IAAI,CAAR;KACIgB,IAAIuB,QAAR;KACIT,OAAOQ,WAAX;;;;;;KAMIS,QAAQtG,MAAMrE,WAAN,CAAkBiK,SAAlB,CAAZ;KACIU,QAAQ,CAAZ,EAAe;UACN,CAAR;;;MAGI,IAAIC,IAAI,CAAb,EAAgBA,IAAID,KAApB,EAA2B,EAAEC,CAA7B,EAAgC;;MAE3BvG,MAAM8D,UAAN,CAAiByC,CAAjB,KAAuB,IAA3B,EAAiC;WAC1B,WAAN;;SAEMxM,IAAP,CAAYiG,MAAM8D,UAAN,CAAiByC,CAAjB,CAAZ;;;;;;MAMI,IAAIhF,QAAQ+E,QAAQ,CAAR,GAAYA,QAAQ,CAApB,GAAwB,CAAzC,EAA4C/E,QAAQoE,WAApD,4BAA4F;;;;;;;MAOvFO,OAAO3C,CAAX;OACK,IAAI4C,IAAI,CAAR,EAAWf,IAAIpG,IAApB,qBAA8CoG,KAAKpG,IAAnD,EAAyD;;OAEpDuC,SAASoE,WAAb,EAA0B;YACnB,eAAN;;;OAGKS,QAAQC,aAAarG,MAAM8D,UAAN,CAAiBvC,OAAjB,CAAb,CAAd;;OAEI6E,SAASpH,IAAT,IAAiBoH,QAAQpB,MAAM,CAACS,SAASlC,CAAV,IAAe4C,CAArB,CAA7B,EAAsD;YAC/C,UAAN;;;QAGIC,QAAQD,CAAb;OACMhB,IAAIC,KAAKC,IAAL,GAAYC,IAAZ,GAAoBF,KAAKC,OAAOE,IAAZ,GAAmBA,IAAnB,GAA0BH,IAAIC,IAA5D;;OAEIe,QAAQjB,CAAZ,EAAe;;;;OAITD,aAAalG,OAAOmG,CAA1B;OACIgB,IAAInB,MAAMS,SAASP,UAAf,CAAR,EAAoC;YAC7B,UAAN;;;QAGIA,UAAL;;;MAIKe,MAAMnG,OAAOhG,MAAP,GAAgB,CAA5B;SACO4K,MAAMnB,IAAI2C,IAAV,EAAgBD,GAAhB,EAAqBC,QAAQ,CAA7B,CAAP;;;;MAIIlB,MAAMzB,IAAI0C,GAAV,IAAiBR,SAASlB,CAA9B,EAAiC;WAC1B,UAAN;;;OAGIS,MAAMzB,IAAI0C,GAAV,CAAL;OACKA,GAAL;;;SAGOD,MAAP,CAAczC,GAAd,EAAmB,CAAnB,EAAsBgB,CAAtB;;;QAIM3I,OAAOmK,aAAP,eAAwBjG,MAAxB,CAAP;CAjFD;;;;;;;;;AA2FA,IAAMiE,SAAS,SAATA,MAAS,CAAS/D,KAAT,EAAgB;KACxBF,SAAS,EAAf;;;SAGQoE,WAAWlE,KAAX,CAAR;;;KAGI2F,cAAc3F,MAAMlG,MAAxB;;;KAGIyK,IAAIuB,QAAR;KACItB,QAAQ,CAAZ;KACIa,OAAOQ,WAAX;;;;;;;;uBAG2B7F,KAA3B,8HAAkC;OAAvBwF,cAAuB;;OAC7BA,iBAAe,IAAnB,EAAyB;WACjBzL,IAAP,CAAY8K,mBAAmBW,cAAnB,CAAZ;;;;;;;;;;;;;;;;;;KAIEZ,cAAc9E,OAAOhG,MAAzB;KACI2K,iBAAiBG,WAArB;;;;;;KAMIA,WAAJ,EAAiB;SACT7K,IAAP,CAAY6L,SAAZ;;;;QAIMnB,iBAAiBkB,WAAxB,EAAqC;;;;MAIhCD,IAAID,MAAR;;;;;;yBAC2BzF,KAA3B,mIAAkC;QAAvBwF,YAAuB;;QAC7BA,gBAAgBjB,CAAhB,IAAqBiB,eAAeE,CAAxC,EAA2C;SACtCF,YAAJ;;;;;;;;;;;;;;;;;;;;;MAMIb,wBAAwBF,iBAAiB,CAA/C;MACIiB,IAAInB,CAAJ,GAAQS,MAAM,CAACS,SAASjB,KAAV,IAAmBG,qBAAzB,CAAZ,EAA6D;WACtD,UAAN;;;WAGQ,CAACe,IAAInB,CAAL,IAAUI,qBAAnB;MACIe,CAAJ;;;;;;;yBAE2B1F,KAA3B,mIAAkC;QAAvBwF,aAAuB;;QAC7BA,gBAAejB,CAAf,IAAoB,EAAEC,KAAF,GAAUiB,MAAlC,EAA0C;aACnC,UAAN;;QAEGD,iBAAgBjB,CAApB,EAAuB;;SAElBQ,IAAIP,KAAR;UACK,IAAIY,IAAIpG,IAAb,qBAAuCoG,KAAKpG,IAA5C,EAAkD;UAC3CmG,IAAIC,KAAKC,IAAL,GAAYC,IAAZ,GAAoBF,KAAKC,OAAOE,IAAZ,GAAmBA,IAAnB,GAA0BH,IAAIC,IAA5D;UACIN,IAAII,CAAR,EAAW;;;UAGLF,UAAUF,IAAII,CAApB;UACMD,aAAalG,OAAOmG,CAA1B;aACOpL,IAAP,CACC8K,mBAAmBC,aAAaK,IAAIF,UAAUC,UAA3B,EAAuC,CAAvC,CAAnB,CADD;UAGIF,MAAMC,UAAUC,UAAhB,CAAJ;;;YAGMnL,IAAP,CAAY8K,mBAAmBC,aAAaC,CAAb,EAAgB,CAAhB,CAAnB,CAAZ;YACOL,MAAMF,KAAN,EAAaG,qBAAb,EAAoCF,kBAAkBG,WAAtD,CAAP;aACQ,CAAR;OACEH,cAAF;;;;;;;;;;;;;;;;;;IAIAD,KAAF;IACED,CAAF;;QAGMzE,OAAOjG,IAAP,CAAY,EAAZ,CAAP;CArFD;;;;;;;;;;;;;AAmGA,IAAMyB,YAAY,SAAZA,SAAY,CAAS0E,KAAT,EAAgB;QAC1BqE,UAAUrE,KAAV,EAAiB,UAASoE,MAAT,EAAiB;SACjCE,cAAczE,IAAd,CAAmBuE,MAAnB,IACJJ,OAAOI,OAAO5I,KAAP,CAAa,CAAb,EAAgB/C,WAAhB,EAAP,CADI,GAEJ2L,MAFH;EADM,CAAP;CADD;;;;;;;;;;;;;AAmBA,IAAMhJ,UAAU,SAAVA,OAAU,CAAS4E,KAAT,EAAgB;QACxBqE,UAAUrE,KAAV,EAAiB,UAASoE,MAAT,EAAiB;SACjCD,cAActE,IAAd,CAAmBuE,MAAnB,IACJ,SAASL,OAAOK,MAAP,CADL,GAEJA,MAFH;EADM,CAAP;CADD;;;;;AAWA,IAAMjJ,WAAW;;;;;;YAML,OANK;;;;;;;;SAcR;YACG+I,UADH;YAEGD;EAhBK;WAkBND,MAlBM;WAmBND,MAnBM;YAoBL3I,OApBK;cAqBHE;CArBd,CAwBA;;ADvbA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,AACA,AACA,AACA,AAiDA,AAAO,IAAMzD,UAA6C,EAAnD;AAEP,AAAA,SAAAyC,UAAA,CAA2BuJ,GAA3B,EAAA;QACOJ,IAAII,IAAIC,UAAJ,CAAe,CAAf,CAAV;QACI5I,UAAJ;QAEIuI,IAAI,EAAR,EAAYvI,IAAI,OAAOuI,EAAE5F,QAAF,CAAW,EAAX,EAAezD,WAAf,EAAX,CAAZ,KACK,IAAIqJ,IAAI,GAAR,EAAavI,IAAI,MAAMuI,EAAE5F,QAAF,CAAW,EAAX,EAAezD,WAAf,EAAV,CAAb,KACA,IAAIqJ,IAAI,IAAR,EAAcvI,IAAI,MAAM,CAAEuI,KAAK,CAAN,GAAW,GAAZ,EAAiB5F,QAAjB,CAA0B,EAA1B,EAA8BzD,WAA9B,EAAN,GAAoD,GAApD,GAA0D,CAAEqJ,IAAI,EAAL,GAAW,GAAZ,EAAiB5F,QAAjB,CAA0B,EAA1B,EAA8BzD,WAA9B,EAA9D,CAAd,KACAc,IAAI,MAAM,CAAEuI,KAAK,EAAN,GAAY,GAAb,EAAkB5F,QAAlB,CAA2B,EAA3B,EAA+BzD,WAA/B,EAAN,GAAqD,GAArD,GAA2D,CAAGqJ,KAAK,CAAN,GAAW,EAAZ,GAAkB,GAAnB,EAAwB5F,QAAxB,CAAiC,EAAjC,EAAqCzD,WAArC,EAA3D,GAAgH,GAAhH,GAAsH,CAAEqJ,IAAI,EAAL,GAAW,GAAZ,EAAiB5F,QAAjB,CAA0B,EAA1B,EAA8BzD,WAA9B,EAA1H;WAEEc,CAAP;;AAGD,AAAA,SAAAuB,WAAA,CAA4BD,GAA5B,EAAA;QACK6G,SAAS,EAAb;QACIE,IAAI,CAAR;QACMK,KAAKpH,IAAI1C,MAAf;WAEOyJ,IAAIK,EAAX,EAAe;YACRH,IAAI1C,SAASvE,IAAI8G,MAAJ,CAAWC,IAAI,CAAf,EAAkB,CAAlB,CAAT,EAA+B,EAA/B,CAAV;YAEIE,IAAI,GAAR,EAAa;sBACF7H,OAAO4H,YAAP,CAAoBC,CAApB,CAAV;iBACK,CAAL;SAFD,MAIK,IAAIA,KAAK,GAAL,IAAYA,IAAI,GAApB,EAAyB;gBACxBG,KAAKL,CAAN,IAAY,CAAhB,EAAmB;oBACZG,KAAK3C,SAASvE,IAAI8G,MAAJ,CAAWC,IAAI,CAAf,EAAkB,CAAlB,CAAT,EAA+B,EAA/B,CAAX;0BACU3H,OAAO4H,YAAP,CAAqB,CAACC,IAAI,EAAL,KAAY,CAAb,GAAmBC,KAAK,EAA5C,CAAV;aAFD,MAGO;0BACIlH,IAAI8G,MAAJ,CAAWC,CAAX,EAAc,CAAd,CAAV;;iBAEI,CAAL;SAPI,MASA,IAAIE,KAAK,GAAT,EAAc;gBACbG,KAAKL,CAAN,IAAY,CAAhB,EAAmB;oBACZG,KAAK3C,SAASvE,IAAI8G,MAAJ,CAAWC,IAAI,CAAf,EAAkB,CAAlB,CAAT,EAA+B,EAA/B,CAAX;oBACMI,KAAK5C,SAASvE,IAAI8G,MAAJ,CAAWC,IAAI,CAAf,EAAkB,CAAlB,CAAT,EAA+B,EAA/B,CAAX;0BACU3H,OAAO4H,YAAP,CAAqB,CAACC,IAAI,EAAL,KAAY,EAAb,GAAoB,CAACC,KAAK,EAAN,KAAa,CAAjC,GAAuCC,KAAK,EAAhE,CAAV;aAHD,MAIO;0BACInH,IAAI8G,MAAJ,CAAWC,CAAX,EAAc,CAAd,CAAV;;iBAEI,CAAL;SARI,MAUA;sBACM/G,IAAI8G,MAAJ,CAAWC,CAAX,EAAc,CAAd,CAAV;iBACK,CAAL;;;WAIKF,MAAP;;AAGD,SAAAD,2BAAA,CAAqC3J,UAArC,EAA+DkG,QAA/D,EAAA;aACAxF,gBAAC,CAA0BqC,GAA1B,EAAD;YACQF,SAASG,YAAYD,GAAZ,CAAf;eACQ,CAACF,OAAOzD,KAAP,CAAa8G,SAASpD,UAAtB,CAAD,GAAqCC,GAArC,GAA2CF,MAAnD;;QAGG7C,WAAW1B,MAAf,EAAuB0B,WAAW1B,MAAX,GAAoB6D,OAAOnC,WAAW1B,MAAlB,EAA0BkC,OAA1B,CAAkC0F,SAASzF,WAA3C,EAAwDC,gBAAxD,EAA0E1B,WAA1E,GAAwFwB,OAAxF,CAAgG0F,SAASwD,UAAzG,EAAqH,EAArH,CAApB;QACnB1J,WAAWwF,QAAX,KAAwBlG,SAA5B,EAAuCU,WAAWwF,QAAX,GAAsBrD,OAAOnC,WAAWwF,QAAlB,EAA4BhF,OAA5B,CAAoC0F,SAASzF,WAA7C,EAA0DC,gBAA1D,EAA4EF,OAA5E,CAAoF0F,SAASuD,YAA7F,EAA2G5I,UAA3G,EAAuHL,OAAvH,CAA+H0F,SAASzF,WAAxI,EAAqJE,WAArJ,CAAtB;QACnCX,WAAWmE,IAAX,KAAoB7E,SAAxB,EAAmCU,WAAWmE,IAAX,GAAkBhC,OAAOnC,WAAWmE,IAAlB,EAAwB3D,OAAxB,CAAgC0F,SAASzF,WAAzC,EAAsDC,gBAAtD,EAAwE1B,WAAxE,GAAsFwB,OAAtF,CAA8F0F,SAASsD,QAAvG,EAAiH3I,UAAjH,EAA6HL,OAA7H,CAAqI0F,SAASzF,WAA9I,EAA2JE,WAA3J,CAAlB;QAC/BX,WAAWP,IAAX,KAAoBH,SAAxB,EAAmCU,WAAWP,IAAX,GAAkB0C,OAAOnC,WAAWP,IAAlB,EAAwBe,OAAxB,CAAgC0F,SAASzF,WAAzC,EAAsDC,gBAAtD,EAAwEF,OAAxE,CAAiFR,WAAW1B,MAAX,GAAoB4H,SAASoD,QAA7B,GAAwCpD,SAASqD,iBAAlI,EAAsJ1I,UAAtJ,EAAkKL,OAAlK,CAA0K0F,SAASzF,WAAnL,EAAgME,WAAhM,CAAlB;QAC/BX,WAAWE,KAAX,KAAqBZ,SAAzB,EAAoCU,WAAWE,KAAX,GAAmBiC,OAAOnC,WAAWE,KAAlB,EAAyBM,OAAzB,CAAiC0F,SAASzF,WAA1C,EAAuDC,gBAAvD,EAAyEF,OAAzE,CAAiF0F,SAASmD,SAA1F,EAAqGxI,UAArG,EAAiHL,OAAjH,CAAyH0F,SAASzF,WAAlI,EAA+IE,WAA/I,CAAnB;QAChCX,WAAW8D,QAAX,KAAwBxE,SAA5B,EAAuCU,WAAW8D,QAAX,GAAsB3B,OAAOnC,WAAW8D,QAAlB,EAA4BtD,OAA5B,CAAoC0F,SAASzF,WAA7C,EAA0DC,gBAA1D,EAA4EF,OAA5E,CAAoF0F,SAASkD,YAA7F,EAA2GvI,UAA3G,EAAuHL,OAAvH,CAA+H0F,SAASzF,WAAxI,EAAqJE,WAArJ,CAAtB;WAEhCX,UAAP;;AACA;AAED,SAAAgJ,kBAAA,CAA4BjG,GAA5B,EAAA;WACQA,IAAIvC,OAAJ,CAAY,SAAZ,EAAuB,IAAvB,KAAgC,GAAvC;;AAGD,SAAAyG,cAAA,CAAwB9C,IAAxB,EAAqC+B,QAArC,EAAA;QACOnG,UAAUoE,KAAK/E,KAAL,CAAW8G,SAAS2C,WAApB,KAAoC,EAApD;;iCACoB9I,OAFrB;QAEUmJ,OAFV;;QAIKA,OAAJ,EAAa;eACLA,QAAQ1G,KAAR,CAAc,GAAd,EAAmBuG,GAAnB,CAAuBC,kBAAvB,EAA2C5I,IAA3C,CAAgD,GAAhD,CAAP;KADD,MAEO;eACC+D,IAAP;;;AAIF,SAAA6C,cAAA,CAAwB7C,IAAxB,EAAqC+B,QAArC,EAAA;QACOnG,UAAUoE,KAAK/E,KAAL,CAAW8G,SAASC,WAApB,KAAoC,EAApD;;kCAC0BpG,OAF3B;QAEUmJ,OAFV;QAEmBxB,IAFnB;;QAIKwB,OAAJ,EAAa;oCACUA,QAAQlK,WAAR,GAAsBwD,KAAtB,CAA4B,IAA5B,EAAkC2G,OAAlC,EADV;;YACLL,IADK;YACCG,KADD;;YAENR,cAAcQ,QAAQA,MAAMzG,KAAN,CAAY,GAAZ,EAAiBuG,GAAjB,CAAqBC,kBAArB,CAAR,GAAmD,EAAvE;YACMN,aAAaI,KAAKtG,KAAL,CAAW,GAAX,EAAgBuG,GAAhB,CAAoBC,kBAApB,CAAnB;YACMR,yBAAyBtC,SAAS2C,WAAT,CAAqBzC,IAArB,CAA0BsC,WAAWA,WAAWrI,MAAX,GAAoB,CAA/B,CAA1B,CAA/B;YACMkI,aAAaC,yBAAyB,CAAzB,GAA6B,CAAhD;YACMG,kBAAkBD,WAAWrI,MAAX,GAAoBkI,UAA5C;YACMpI,SAASyI,MAAcL,UAAd,CAAf;aAEK,IAAIlH,IAAI,CAAb,EAAgBA,IAAIkH,UAApB,EAAgC,EAAElH,CAAlC,EAAqC;mBAC7BA,CAAP,IAAYoH,YAAYpH,CAAZ,KAAkBqH,WAAWC,kBAAkBtH,CAA7B,CAAlB,IAAqD,EAAjE;;YAGGmH,sBAAJ,EAA4B;mBACpBD,aAAa,CAApB,IAAyBtB,eAAe9G,OAAOoI,aAAa,CAApB,CAAf,EAAuCrC,QAAvC,CAAzB;;YAGK+B,gBAAgB9H,OAAOmI,MAAP,CAAmD,UAACH,GAAD,EAAME,KAAN,EAAaP,KAAb,EAA3E;gBACO,CAACO,KAAD,IAAUA,UAAU,GAAxB,EAA6B;oBACtBD,cAAcD,IAAIA,IAAI9H,MAAJ,GAAa,CAAjB,CAApB;oBACI+H,eAAeA,YAAYN,KAAZ,GAAoBM,YAAY/H,MAAhC,KAA2CyH,KAA9D,EAAqE;gCACxDzH,MAAZ;iBADD,MAEO;wBACFC,IAAJ,CAAS,EAAEwH,YAAF,EAASzH,QAAS,CAAlB,EAAT;;;mBAGK8H,GAAP;SATqB,EAUnB,EAVmB,CAAtB;YAYMN,oBAAoBI,cAAcC,IAAd,CAAmB,UAACF,CAAD,EAAID,CAAJ;mBAAUA,EAAE1H,MAAF,GAAW2H,EAAE3H,MAAvB;SAAnB,EAAkD,CAAlD,CAA1B;YAEIoH,gBAAJ;YACII,qBAAqBA,kBAAkBxH,MAAlB,GAA2B,CAApD,EAAuD;gBAChDsH,WAAWxH,OAAO4B,KAAP,CAAa,CAAb,EAAgB8F,kBAAkBC,KAAlC,CAAjB;gBACMF,UAAUzH,OAAO4B,KAAP,CAAa8F,kBAAkBC,KAAlB,GAA0BD,kBAAkBxH,MAAzD,CAAhB;sBACUsH,SAASvH,IAAT,CAAc,GAAd,IAAqB,IAArB,GAA4BwH,QAAQxH,IAAR,CAAa,GAAb,CAAtC;SAHD,MAIO;sBACID,OAAOC,IAAP,CAAY,GAAZ,CAAV;;YAGGsH,IAAJ,EAAU;uBACE,MAAMA,IAAjB;;eAGMD,OAAP;KA5CD,MA6CO;eACCtD,IAAP;;;AAIF,IAAMqD,YAAY,iIAAlB;AACA,IAAMD,wBAA4C,EAAD,CAAKnI,KAAL,CAAW,OAAX,EAAqB,CAArB,MAA4BE,SAA7E;AAEA,AAAA,SAAAQ,KAAA,CAAsBqH,SAAtB,EAAA;QAAwClI,OAAxC,uEAA6D,EAA7D;;QACOe,aAA2B,EAAjC;QACMkG,WAAYjH,QAAQuC,GAAR,KAAgB,KAAhB,GAAwB8C,YAAxB,GAAuCD,YAAzD;QAEIpF,QAAQ+G,SAAR,KAAsB,QAA1B,EAAoCmB,YAAY,CAAClI,QAAQX,MAAR,GAAiBW,QAAQX,MAAR,GAAiB,GAAlC,GAAwC,EAAzC,IAA+C,IAA/C,GAAsD6I,SAAlE;QAE9BpH,UAAUoH,UAAU/H,KAAV,CAAgBoI,SAAhB,CAAhB;QAEIzH,OAAJ,EAAa;YACRwH,qBAAJ,EAA2B;;uBAEfjJ,MAAX,GAAoByB,QAAQ,CAAR,CAApB;uBACWyF,QAAX,GAAsBzF,QAAQ,CAAR,CAAtB;uBACWoE,IAAX,GAAkBpE,QAAQ,CAAR,CAAlB;uBACWkE,IAAX,GAAkBqD,SAASvH,QAAQ,CAAR,CAAT,EAAqB,EAArB,CAAlB;uBACWN,IAAX,GAAkBM,QAAQ,CAAR,KAAc,EAAhC;uBACWG,KAAX,GAAmBH,QAAQ,CAAR,CAAnB;uBACW+D,QAAX,GAAsB/D,QAAQ,CAAR,CAAtB;;gBAGIqH,MAAMpH,WAAWiE,IAAjB,CAAJ,EAA4B;2BAChBA,IAAX,GAAkBlE,QAAQ,CAAR,CAAlB;;SAZF,MAcO;;;uBAEKzB,MAAX,GAAoByB,QAAQ,CAAR,KAAcT,SAAlC;uBACWkG,QAAX,GAAuB2B,UAAUE,OAAV,CAAkB,GAAlB,MAA2B,CAAC,CAA5B,GAAgCtH,QAAQ,CAAR,CAAhC,GAA6CT,SAApE;uBACW6E,IAAX,GAAmBgD,UAAUE,OAAV,CAAkB,IAAlB,MAA4B,CAAC,CAA7B,GAAiCtH,QAAQ,CAAR,CAAjC,GAA8CT,SAAjE;uBACW2E,IAAX,GAAkBqD,SAASvH,QAAQ,CAAR,CAAT,EAAqB,EAArB,CAAlB;uBACWN,IAAX,GAAkBM,QAAQ,CAAR,KAAc,EAAhC;uBACWG,KAAX,GAAoBiH,UAAUE,OAAV,CAAkB,GAAlB,MAA2B,CAAC,CAA5B,GAAgCtH,QAAQ,CAAR,CAAhC,GAA6CT,SAAjE;uBACWwE,QAAX,GAAuBqD,UAAUE,OAAV,CAAkB,GAAlB,MAA2B,CAAC,CAA5B,GAAgCtH,QAAQ,CAAR,CAAhC,GAA6CT,SAApE;;gBAGI8H,MAAMpH,WAAWiE,IAAjB,CAAJ,EAA4B;2BAChBA,IAAX,GAAmBkD,UAAU/H,KAAV,CAAgB,+BAAhB,IAAmDW,QAAQ,CAAR,CAAnD,GAAgET,SAAnF;;;YAIEU,WAAWmE,IAAf,EAAqB;;uBAETA,IAAX,GAAkB6C,eAAeC,eAAejH,WAAWmE,IAA1B,EAAgC+B,QAAhC,CAAf,EAA0DA,QAA1D,CAAlB;;;YAIGlG,WAAW1B,MAAX,KAAsBgB,SAAtB,IAAmCU,WAAWwF,QAAX,KAAwBlG,SAA3D,IAAwEU,WAAWmE,IAAX,KAAoB7E,SAA5F,IAAyGU,WAAWiE,IAAX,KAAoB3E,SAA7H,IAA0I,CAACU,WAAWP,IAAtJ,IAA8JO,WAAWE,KAAX,KAAqBZ,SAAvL,EAAkM;uBACtL0G,SAAX,GAAuB,eAAvB;SADD,MAEO,IAAIhG,WAAW1B,MAAX,KAAsBgB,SAA1B,EAAqC;uBAChC0G,SAAX,GAAuB,UAAvB;SADM,MAEA,IAAIhG,WAAW8D,QAAX,KAAwBxE,SAA5B,EAAuC;uBAClC0G,SAAX,GAAuB,UAAvB;SADM,MAEA;uBACKA,SAAX,GAAuB,KAAvB;;;YAIG/G,QAAQ+G,SAAR,IAAqB/G,QAAQ+G,SAAR,KAAsB,QAA3C,IAAuD/G,QAAQ+G,SAAR,KAAsBhG,WAAWgG,SAA5F,EAAuG;uBAC3F9G,KAAX,GAAmBc,WAAWd,KAAX,IAAoB,kBAAkBD,QAAQ+G,SAA1B,GAAsC,aAA7E;;;YAIKrG,gBAAgBvB,QAAQ,CAACa,QAAQX,MAAR,IAAkB0B,WAAW1B,MAA7B,IAAuC,EAAxC,EAA4CU,WAA5C,EAAR,CAAtB;;YAGI,CAACC,QAAQsD,cAAT,KAA4B,CAAC5C,aAAD,IAAkB,CAACA,cAAc4C,cAA7D,CAAJ,EAAkF;;gBAE7EvC,WAAWmE,IAAX,KAAoBlF,QAAQ2E,UAAR,IAAuBjE,iBAAiBA,cAAciE,UAA1E,CAAJ,EAA4F;;oBAEvF;+BACQO,IAAX,GAAkBzC,SAASC,OAAT,CAAiB3B,WAAWmE,IAAX,CAAgB3D,OAAhB,CAAwB0F,SAASzF,WAAjC,EAA8CuC,WAA9C,EAA2DhE,WAA3D,EAAjB,CAAlB;iBADD,CAEE,OAAOyC,CAAP,EAAU;+BACAvC,KAAX,GAAmBc,WAAWd,KAAX,IAAoB,oEAAoEuC,CAA3G;;;;wCAI0BzB,UAA5B,EAAwCqE,YAAxC;SAXD,MAYO;;wCAEsBrE,UAA5B,EAAwCkG,QAAxC;;;YAIGvG,iBAAiBA,cAAcG,KAAnC,EAA0C;0BAC3BA,KAAd,CAAoBE,UAApB,EAAgCf,OAAhC;;KA3EF,MA6EO;mBACKC,KAAX,GAAmBc,WAAWd,KAAX,IAAoB,wBAAvC;;WAGMc,UAAP;;AACA;AAED,SAAAiG,mBAAA,CAA6BjG,UAA7B,EAAuDf,OAAvD,EAAA;QACOiH,WAAYjH,QAAQuC,GAAR,KAAgB,KAAhB,GAAwB8C,YAAxB,GAAuCD,YAAzD;QACMuB,YAA0B,EAAhC;QAEI5F,WAAWwF,QAAX,KAAwBlG,SAA5B,EAAuC;kBAC5BgB,IAAV,CAAeN,WAAWwF,QAA1B;kBACUlF,IAAV,CAAe,GAAf;;QAGGN,WAAWmE,IAAX,KAAoB7E,SAAxB,EAAmC;;kBAExBgB,IAAV,CAAe0G,eAAeC,eAAe9E,OAAOnC,WAAWmE,IAAlB,CAAf,EAAwC+B,QAAxC,CAAf,EAAkEA,QAAlE,EAA4E1F,OAA5E,CAAoF0F,SAASC,WAA7F,EAA0G,UAACe,CAAD,EAAIJ,EAAJ,EAAQC,EAAR;mBAAe,MAAMD,EAAN,IAAYC,KAAK,QAAQA,EAAb,GAAkB,EAA9B,IAAoC,GAAnD;SAA1G,CAAf;;QAGG,OAAO/G,WAAWiE,IAAlB,KAA2B,QAA3B,IAAuC,OAAOjE,WAAWiE,IAAlB,KAA2B,QAAtE,EAAgF;kBACrE3D,IAAV,CAAe,GAAf;kBACUA,IAAV,CAAe6B,OAAOnC,WAAWiE,IAAlB,CAAf;;WAGM2B,UAAUvF,MAAV,GAAmBuF,UAAUxF,IAAV,CAAe,EAAf,CAAnB,GAAwCd,SAA/C;;AACA;AAED,IAAMuH,OAAO,UAAb;AACA,IAAMD,OAAO,aAAb;AACA,IAAMD,OAAO,eAAb;AACA,AACA,IAAMF,OAAO,wBAAb;AAEA,AAAA,SAAAhB,iBAAA,CAAkCc,KAAlC,EAAA;QACOF,SAAuB,EAA7B;WAEOE,MAAMlG,MAAb,EAAqB;YAChBkG,MAAMnH,KAAN,CAAYyH,IAAZ,CAAJ,EAAuB;oBACdN,MAAM/F,OAAN,CAAcqG,IAAd,EAAoB,EAApB,CAAR;SADD,MAEO,IAAIN,MAAMnH,KAAN,CAAYwH,IAAZ,CAAJ,EAAuB;oBACrBL,MAAM/F,OAAN,CAAcoG,IAAd,EAAoB,GAApB,CAAR;SADM,MAEA,IAAIL,MAAMnH,KAAN,CAAYuH,IAAZ,CAAJ,EAAuB;oBACrBJ,MAAM/F,OAAN,CAAcmG,IAAd,EAAoB,GAApB,CAAR;mBACOD,GAAP;SAFM,MAGA,IAAIH,UAAU,GAAV,IAAiBA,UAAU,IAA/B,EAAqC;oBACnC,EAAR;SADM,MAEA;gBACAC,KAAKD,MAAMnH,KAAN,CAAYqH,IAAZ,CAAX;gBACID,EAAJ,EAAQ;oBACDX,IAAIW,GAAG,CAAH,CAAV;wBACQD,MAAMxE,KAAN,CAAY8D,EAAExF,MAAd,CAAR;uBACOC,IAAP,CAAYuF,CAAZ;aAHD,MAIO;sBACA,IAAIS,KAAJ,CAAU,kCAAV,CAAN;;;;WAKID,OAAOjG,IAAP,CAAY,EAAZ,CAAP;;AACA;AAED,AAAA,SAAAR,SAAA,CAA0BI,UAA1B,EAAA;QAAoDf,OAApD,uEAAyE,EAAzE;;QACOiH,WAAYjH,QAAQuC,GAAR,GAAc8C,YAAd,GAA6BD,YAA/C;QACMuB,YAA0B,EAAhC;;QAGMjG,gBAAgBvB,QAAQ,CAACa,QAAQX,MAAR,IAAkB0B,WAAW1B,MAA7B,IAAuC,EAAxC,EAA4CU,WAA5C,EAAR,CAAtB;;QAGIW,iBAAiBA,cAAcC,SAAnC,EAA8CD,cAAcC,SAAd,CAAwBI,UAAxB,EAAoCf,OAApC;QAE1Ce,WAAWmE,IAAf,EAAqB;;YAEhB+B,SAASC,WAAT,CAAqBC,IAArB,CAA0BpG,WAAWmE,IAArC,CAAJ,EAAgD;;;;aAK3C,IAAIlF,QAAQ2E,UAAR,IAAuBjE,iBAAiBA,cAAciE,UAA1D,EAAuE;;oBAEvE;+BACQO,IAAX,GAAmB,CAAClF,QAAQuC,GAAT,GAAeE,SAASC,OAAT,CAAiB3B,WAAWmE,IAAX,CAAgB3D,OAAhB,CAAwB0F,SAASzF,WAAjC,EAA8CuC,WAA9C,EAA2DhE,WAA3D,EAAjB,CAAf,GAA4G0C,SAASG,SAAT,CAAmB7B,WAAWmE,IAA9B,CAA/H;iBADD,CAEE,OAAO1C,CAAP,EAAU;+BACAvC,KAAX,GAAmBc,WAAWd,KAAX,IAAoB,iDAAiD,CAACD,QAAQuC,GAAT,GAAe,OAAf,GAAyB,SAA1E,IAAuF,iBAAvF,GAA2GC,CAAlJ;;;;;gCAMyBzB,UAA5B,EAAwCkG,QAAxC;QAEIjH,QAAQ+G,SAAR,KAAsB,QAAtB,IAAkChG,WAAW1B,MAAjD,EAAyD;kBAC9CgC,IAAV,CAAeN,WAAW1B,MAA1B;kBACUgC,IAAV,CAAe,GAAf;;QAGKwF,YAAYG,oBAAoBjG,UAApB,EAAgCf,OAAhC,CAAlB;QACI6G,cAAcxG,SAAlB,EAA6B;YACxBL,QAAQ+G,SAAR,KAAsB,QAA1B,EAAoC;sBACzB1F,IAAV,CAAe,IAAf;;kBAGSA,IAAV,CAAewF,SAAf;YAEI9F,WAAWP,IAAX,IAAmBO,WAAWP,IAAX,CAAgBiG,MAAhB,CAAuB,CAAvB,MAA8B,GAArD,EAA0D;sBAC/CpF,IAAV,CAAe,GAAf;;;QAIEN,WAAWP,IAAX,KAAoBH,SAAxB,EAAmC;YAC9BuG,IAAI7F,WAAWP,IAAnB;YAEI,CAACR,QAAQ8G,YAAT,KAA0B,CAACpG,aAAD,IAAkB,CAACA,cAAcoG,YAA3D,CAAJ,EAA8E;gBACzEN,kBAAkBI,CAAlB,CAAJ;;YAGGC,cAAcxG,SAAlB,EAA6B;gBACxBuG,EAAErF,OAAF,CAAU,OAAV,EAAmB,MAAnB,CAAJ,CAD4B;;kBAInBF,IAAV,CAAeuF,CAAf;;QAGG7F,WAAWE,KAAX,KAAqBZ,SAAzB,EAAoC;kBACzBgB,IAAV,CAAe,GAAf;kBACUA,IAAV,CAAeN,WAAWE,KAA1B;;QAGGF,WAAW8D,QAAX,KAAwBxE,SAA5B,EAAuC;kBAC5BgB,IAAV,CAAe,GAAf;kBACUA,IAAV,CAAeN,WAAW8D,QAA1B;;WAGM8B,UAAUxF,IAAV,CAAe,EAAf,CAAP,CAxED;;AAyEC;AAED,AAAA,SAAA2E,iBAAA,CAAkCQ,IAAlC,EAAsDD,QAAtD,EAAA;QAA8ErG,OAA9E,uEAAmG,EAAnG;QAAuG0G,iBAAvG;;QACON,SAAuB,EAA7B;QAEI,CAACM,iBAAL,EAAwB;eAChB7F,MAAMF,UAAU2F,IAAV,EAAgBtG,OAAhB,CAAN,EAAgCA,OAAhC,CAAP,CADuB;mBAEZa,MAAMF,UAAU0F,QAAV,EAAoBrG,OAApB,CAAN,EAAoCA,OAApC,CAAX,CAFuB;;cAIdA,WAAW,EAArB;QAEI,CAACA,QAAQE,QAAT,IAAqBmG,SAAShH,MAAlC,EAA0C;eAClCA,MAAP,GAAgBgH,SAAShH,MAAzB;;eAEOkH,QAAP,GAAkBF,SAASE,QAA3B;eACOrB,IAAP,GAAcmB,SAASnB,IAAvB;eACOF,IAAP,GAAcqB,SAASrB,IAAvB;eACOxE,IAAP,GAAcgG,kBAAkBH,SAAS7F,IAAT,IAAiB,EAAnC,CAAd;eACOS,KAAP,GAAeoF,SAASpF,KAAxB;KAPD,MAQO;YACFoF,SAASE,QAAT,KAAsBlG,SAAtB,IAAmCgG,SAASnB,IAAT,KAAkB7E,SAArD,IAAkEgG,SAASrB,IAAT,KAAkB3E,SAAxF,EAAmG;;mBAE3FkG,QAAP,GAAkBF,SAASE,QAA3B;mBACOrB,IAAP,GAAcmB,SAASnB,IAAvB;mBACOF,IAAP,GAAcqB,SAASrB,IAAvB;mBACOxE,IAAP,GAAcgG,kBAAkBH,SAAS7F,IAAT,IAAiB,EAAnC,CAAd;mBACOS,KAAP,GAAeoF,SAASpF,KAAxB;SAND,MAOO;gBACF,CAACoF,SAAS7F,IAAd,EAAoB;uBACZA,IAAP,GAAc8F,KAAK9F,IAAnB;oBACI6F,SAASpF,KAAT,KAAmBZ,SAAvB,EAAkC;2BAC1BY,KAAP,GAAeoF,SAASpF,KAAxB;iBADD,MAEO;2BACCA,KAAP,GAAeqF,KAAKrF,KAApB;;aALF,MAOO;oBACFoF,SAAS7F,IAAT,CAAciG,MAAd,CAAqB,CAArB,MAA4B,GAAhC,EAAqC;2BAC7BjG,IAAP,GAAcgG,kBAAkBH,SAAS7F,IAA3B,CAAd;iBADD,MAEO;wBACF,CAAC8F,KAAKC,QAAL,KAAkBlG,SAAlB,IAA+BiG,KAAKpB,IAAL,KAAc7E,SAA7C,IAA0DiG,KAAKtB,IAAL,KAAc3E,SAAzE,KAAuF,CAACiG,KAAK9F,IAAjG,EAAuG;+BAC/FA,IAAP,GAAc,MAAM6F,SAAS7F,IAA7B;qBADD,MAEO,IAAI,CAAC8F,KAAK9F,IAAV,EAAgB;+BACfA,IAAP,GAAc6F,SAAS7F,IAAvB;qBADM,MAEA;+BACCA,IAAP,GAAc8F,KAAK9F,IAAL,CAAUsC,KAAV,CAAgB,CAAhB,EAAmBwD,KAAK9F,IAAL,CAAUyC,WAAV,CAAsB,GAAtB,IAA6B,CAAhD,IAAqDoD,SAAS7F,IAA5E;;2BAEMA,IAAP,GAAcgG,kBAAkBJ,OAAO5F,IAAzB,CAAd;;uBAEMS,KAAP,GAAeoF,SAASpF,KAAxB;;;mBAGMsF,QAAP,GAAkBD,KAAKC,QAAvB;mBACOrB,IAAP,GAAcoB,KAAKpB,IAAnB;mBACOF,IAAP,GAAcsB,KAAKtB,IAAnB;;eAEM3F,MAAP,GAAgBiH,KAAKjH,MAArB;;WAGMwF,QAAP,GAAkBwB,SAASxB,QAA3B;WAEOuB,MAAP;;AACA;AAED,AAAA,SAAAD,OAAA,CAAwBJ,OAAxB,EAAwCE,WAAxC,EAA4DjG,OAA5D,EAAA;QACOgG,oBAAoBE,OAAO,EAAE7G,QAAS,MAAX,EAAP,EAA4BW,OAA5B,CAA1B;WACOW,UAAUmF,kBAAkBjF,MAAMkF,OAAN,EAAeC,iBAAf,CAAlB,EAAqDnF,MAAMoF,WAAN,EAAmBD,iBAAnB,CAArD,EAA4FA,iBAA5F,EAA+G,IAA/G,CAAV,EAAgIA,iBAAhI,CAAP;;AACA;AAID,AAAA,SAAAH,SAAA,CAA0BD,GAA1B,EAAmC5F,OAAnC,EAAA;QACK,OAAO4F,GAAP,KAAe,QAAnB,EAA6B;cACtBjF,UAAUE,MAAM+E,GAAN,EAAW5F,OAAX,CAAV,EAA+BA,OAA/B,CAAN;KADD,MAEO,IAAI0F,OAAOE,GAAP,MAAgB,QAApB,EAA8B;cAC9B/E,MAAMF,UAAyBiF,GAAzB,EAA8B5F,OAA9B,CAAN,EAA8CA,OAA9C,CAAN;;WAGM4F,GAAP;;AACA;AAID,AAAA,SAAAD,KAAA,CAAsBH,IAAtB,EAAgCC,IAAhC,EAA0CzF,OAA1C,EAAA;QACK,OAAOwF,IAAP,KAAgB,QAApB,EAA8B;eACtB7E,UAAUE,MAAM2E,IAAN,EAAYxF,OAAZ,CAAV,EAAgCA,OAAhC,CAAP;KADD,MAEO,IAAI0F,OAAOF,IAAP,MAAiB,QAArB,EAA+B;eAC9B7E,UAAyB6E,IAAzB,EAA+BxF,OAA/B,CAAP;;QAGG,OAAOyF,IAAP,KAAgB,QAApB,EAA8B;eACtB9E,UAAUE,MAAM4E,IAAN,EAAYzF,OAAZ,CAAV,EAAgCA,OAAhC,CAAP;KADD,MAEO,IAAI0F,OAAOD,IAAP,MAAiB,QAArB,EAA+B;eAC9B9E,UAAyB8E,IAAzB,EAA+BzF,OAA/B,CAAP;;WAGMwF,SAASC,IAAhB;;AACA;AAED,AAAA,SAAAF,eAAA,CAAgCzB,GAAhC,EAA4C9D,OAA5C,EAAA;WACQ8D,OAAOA,IAAIqB,QAAJ,GAAe5D,OAAf,CAAwB,CAACvB,OAAD,IAAY,CAACA,QAAQuC,GAArB,GAA2B6C,aAAaE,MAAxC,GAAiDD,aAAaC,MAAtF,EAA+F1D,UAA/F,CAAd;;AACA;AAED,AAAA,SAAAe,iBAAA,CAAkCmB,GAAlC,EAA8C9D,OAA9C,EAAA;WACQ8D,OAAOA,IAAIqB,QAAJ,GAAe5D,OAAf,CAAwB,CAACvB,OAAD,IAAY,CAACA,QAAQuC,GAArB,GAA2B6C,aAAa5D,WAAxC,GAAsD6D,aAAa7D,WAA3F,EAAyGuC,WAAzG,CAAd;CACA;;ADziBD,IAAMzD,UAA2B;YACvB,MADuB;gBAGnB,IAHmB;WAKxB,eAAUS,UAAV,EAAoCf,OAApC,EAAT;;YAEM,CAACe,WAAWmE,IAAhB,EAAsB;uBACVjF,KAAX,GAAmBc,WAAWd,KAAX,IAAoB,6BAAvC;;eAGMc,UAAP;KAX+B;eAcpB,mBAAUA,UAAV,EAAoCf,OAApC,EAAb;YACQ+E,SAAS7B,OAAOnC,WAAW1B,MAAlB,EAA0BU,WAA1B,OAA4C,OAA3D;;YAGIgB,WAAWiE,IAAX,MAAqBD,SAAS,GAAT,GAAe,EAApC,KAA2ChE,WAAWiE,IAAX,KAAoB,EAAnE,EAAuE;uBAC3DA,IAAX,GAAkB3E,SAAlB;;;YAIG,CAACU,WAAWP,IAAhB,EAAsB;uBACVA,IAAX,GAAkB,GAAlB;;;;;eAOMO,UAAP;;CA/BF,CAmCA;;ADlCA,IAAMT,YAA2B;YACvB,OADuB;gBAEnBX,QAAKgF,UAFc;WAGxBhF,QAAKkB,KAHmB;eAIpBlB,QAAKgB;CAJlB,CAOA;;ADHA,SAAAsE,QAAA,CAAkBL,YAAlB,EAAA;WACQ,OAAOA,aAAaG,MAApB,KAA+B,SAA/B,GAA2CH,aAAaG,MAAxD,GAAiE7B,OAAO0B,aAAavF,MAApB,EAA4BU,WAA5B,OAA8C,KAAtH;;;AAID,IAAMO,YAA2B;YACvB,IADuB;gBAGnB,IAHmB;WAKxB,eAAUS,UAAV,EAAoCf,OAApC,EAAT;YACQ4E,eAAe7D,UAArB;;qBAGagE,MAAb,GAAsBE,SAASL,YAAT,CAAtB;;qBAGaE,YAAb,GAA4B,CAACF,aAAapE,IAAb,IAAqB,GAAtB,KAA8BoE,aAAa3D,KAAb,GAAqB,MAAM2D,aAAa3D,KAAxC,GAAgD,EAA9E,CAA5B;qBACaT,IAAb,GAAoBH,SAApB;qBACaY,KAAb,GAAqBZ,SAArB;eAEOuE,YAAP;KAhB+B;eAmBpB,mBAAUA,YAAV,EAAqC5E,OAArC,EAAb;;YAEM4E,aAAaI,IAAb,MAAuBC,SAASL,YAAT,IAAyB,GAAzB,GAA+B,EAAtD,KAA6DA,aAAaI,IAAb,KAAsB,EAAvF,EAA2F;yBAC7EA,IAAb,GAAoB3E,SAApB;;;YAIG,OAAOuE,aAAaG,MAApB,KAA+B,SAAnC,EAA8C;yBAChC1F,MAAb,GAAuBuF,aAAaG,MAAb,GAAsB,KAAtB,GAA8B,IAArD;yBACaA,MAAb,GAAsB1E,SAAtB;;;YAIGuE,aAAaE,YAAjB,EAA+B;wCACRF,aAAaE,YAAb,CAA0BvB,KAA1B,CAAgC,GAAhC,CADQ;;gBACvB/C,IADuB;gBACjBS,KADiB;;yBAEjBT,IAAb,GAAqBA,QAAQA,SAAS,GAAjB,GAAuBA,IAAvB,GAA8BH,SAAnD;yBACaY,KAAb,GAAqBA,KAArB;yBACa6D,YAAb,GAA4BzE,SAA5B;;;qBAIYwE,QAAb,GAAwBxE,SAAxB;eAEOuE,YAAP;;CA1CF,CA8CA;;ADvDA,IAAMtE,YAA2B;YACvB,KADuB;gBAEnBb,UAAGkF,UAFgB;WAGxBlF,UAAGoB,KAHqB;eAIpBpB,UAAGkB;CAJhB,CAOA;;ADMA,IAAMoB,IAAkB,EAAxB;AACA,IAAM2C,QAAQ,IAAd;;AAGA,IAAMR,eAAe,4BAA4BQ,QAAQ,2EAAR,GAAsF,EAAlH,IAAwH,GAA7I;AACA,IAAMD,WAAW,aAAjB;AACA,IAAMH,eAAeE,OAAOA,OAAO,YAAYC,QAAZ,GAAuB,GAAvB,GAA6BA,QAA7B,GAAwCA,QAAxC,GAAmD,GAAnD,GAAyDA,QAAzD,GAAoEA,QAA3E,IAAuF,GAAvF,GAA6FD,OAAO,gBAAgBC,QAAhB,GAA2B,GAA3B,GAAiCA,QAAjC,GAA4CA,QAAnD,CAA7F,GAA4J,GAA5J,GAAkKD,OAAO,MAAMC,QAAN,GAAiBA,QAAxB,CAAzK,CAArB;;;;;;;;;;;;AAaA,IAAML,UAAU,uDAAhB;AACA,IAAMG,UAAU,4DAAhB;AACA,IAAMF,UAAUJ,MAAMM,OAAN,EAAe,YAAf,CAAhB;AACA,AACA,AACA,AACA,AAEA,AAEA,IAAMJ,gBAAgB,qCAAtB;AACA,AACA,AACA,AACA,AACA,AACA,AACA,AACA,AACA,AACA,AACA,AAEA,IAAMN,aAAa,IAAIG,MAAJ,CAAWE,YAAX,EAAyB,GAAzB,CAAnB;AACA,IAAM1C,cAAc,IAAIwC,MAAJ,CAAWM,YAAX,EAAyB,GAAzB,CAApB;AACA,IAAMtB,iBAAiB,IAAIgB,MAAJ,CAAWC,MAAM,KAAN,EAAaG,OAAb,EAAsB,OAAtB,EAA+B,OAA/B,EAAwCC,OAAxC,CAAX,EAA6D,GAA7D,CAAvB;AACA,AACA,IAAM1C,aAAa,IAAIqC,MAAJ,CAAWC,MAAM,KAAN,EAAaC,YAAb,EAA2BC,aAA3B,CAAX,EAAsD,GAAtD,CAAnB;AACA,IAAMrC,cAAcH,UAApB;AACA,AACA,AAEA,SAAAF,gBAAA,CAA0BqC,GAA1B,EAAA;QACOF,SAASG,YAAYD,GAAZ,CAAf;WACQ,CAACF,OAAOzD,KAAP,CAAa0D,UAAb,CAAD,GAA4BC,GAA5B,GAAkCF,MAA1C;;AAGD,IAAMtD,YAA8C;YAC1C,QAD0C;WAG3C,kBAAUS,UAAV,EAAoCf,OAApC,EAAT;YACQgC,mBAAmBjB,UAAzB;YACMoB,KAAKH,iBAAiBG,EAAjB,GAAuBH,iBAAiBxB,IAAjB,GAAwBwB,iBAAiBxB,IAAjB,CAAsB+C,KAAtB,CAA4B,GAA5B,CAAxB,GAA2D,EAA7F;yBACiB/C,IAAjB,GAAwBH,SAAxB;YAEI2B,iBAAiBf,KAArB,EAA4B;gBACvBuC,iBAAiB,KAArB;gBACM3B,UAAwB,EAA9B;gBACM8B,UAAU3B,iBAAiBf,KAAjB,CAAuBsC,KAAvB,CAA6B,GAA7B,CAAhB;iBAEK,IAAInB,IAAI,CAAR,EAAWe,KAAKQ,QAAQvC,MAA7B,EAAqCgB,IAAIe,EAAzC,EAA6C,EAAEf,CAA/C,EAAkD;oBAC3CqB,SAASE,QAAQvB,CAAR,EAAWmB,KAAX,CAAiB,GAAjB,CAAf;wBAEQE,OAAO,CAAP,CAAR;yBACM,IAAL;4BACOC,UAAUD,OAAO,CAAP,EAAUF,KAAV,CAAgB,GAAhB,CAAhB;6BACK,IAAInB,KAAI,CAAR,EAAWe,MAAKO,QAAQtC,MAA7B,EAAqCgB,KAAIe,GAAzC,EAA6C,EAAEf,EAA/C,EAAkD;+BAC9Cf,IAAH,CAAQqC,QAAQtB,EAAR,CAAR;;;yBAGG,SAAL;yCACkBF,OAAjB,GAA2BS,kBAAkBc,OAAO,CAAP,CAAlB,EAA6BzD,OAA7B,CAA3B;;yBAEI,MAAL;yCACkBiC,IAAjB,GAAwBU,kBAAkBc,OAAO,CAAP,CAAlB,EAA6BzD,OAA7B,CAAxB;;;yCAGiB,IAAjB;gCACQ2C,kBAAkBc,OAAO,CAAP,CAAlB,EAA6BzD,OAA7B,CAAR,IAAiD2C,kBAAkBc,OAAO,CAAP,CAAlB,EAA6BzD,OAA7B,CAAjD;;;;gBAKCwD,cAAJ,EAAoBxB,iBAAiBH,OAAjB,GAA2BA,OAA3B;;yBAGJZ,KAAjB,GAAyBZ,SAAzB;aAEK,IAAI+B,MAAI,CAAR,EAAWe,OAAKhB,GAAGf,MAAxB,EAAgCgB,MAAIe,IAApC,EAAwC,EAAEf,GAA1C,EAA6C;gBACtCiB,OAAOlB,GAAGC,GAAH,EAAMmB,KAAN,CAAY,GAAZ,CAAb;iBAEK,CAAL,IAAUZ,kBAAkBU,KAAK,CAAL,CAAlB,CAAV;gBAEI,CAACrD,QAAQsD,cAAb,EAA6B;;oBAExB;yBACE,CAAL,IAAUb,SAASC,OAAT,CAAiBC,kBAAkBU,KAAK,CAAL,CAAlB,EAA2BrD,OAA3B,EAAoCD,WAApC,EAAjB,CAAV;iBADD,CAEE,OAAOyC,CAAP,EAAU;qCACMvC,KAAjB,GAAyB+B,iBAAiB/B,KAAjB,IAA0B,6EAA6EuC,CAAhI;;aALF,MAOO;qBACD,CAAL,IAAUG,kBAAkBU,KAAK,CAAL,CAAlB,EAA2BrD,OAA3B,EAAoCD,WAApC,EAAV;;eAGEqC,GAAH,IAAQiB,KAAKlC,IAAL,CAAU,GAAV,CAAR;;eAGMa,gBAAP;KA5DkD;eA+DvC,sBAAUA,gBAAV,EAA6ChC,OAA7C,EAAb;YACQe,aAAaiB,gBAAnB;YACMG,KAAKiB,QAAQpB,iBAAiBG,EAAzB,CAAX;YACIA,EAAJ,EAAQ;iBACF,IAAIC,IAAI,CAAR,EAAWe,KAAKhB,GAAGf,MAAxB,EAAgCgB,IAAIe,EAApC,EAAwC,EAAEf,CAA1C,EAA6C;oBACtCS,SAASK,OAAOf,GAAGC,CAAH,CAAP,CAAf;oBACMW,QAAQF,OAAOI,WAAP,CAAmB,GAAnB,CAAd;oBACMZ,YAAaQ,OAAOC,KAAP,CAAa,CAAb,EAAgBC,KAAhB,CAAD,CAAyBxB,OAAzB,CAAiCC,WAAjC,EAA8CC,gBAA9C,EAAgEF,OAAhE,CAAwEC,WAAxE,EAAqFE,WAArF,EAAkGH,OAAlG,CAA0GyB,cAA1G,EAA0HpB,UAA1H,CAAlB;oBACIU,SAASO,OAAOC,KAAP,CAAaC,QAAQ,CAArB,CAAb;;oBAGI;6BACO,CAAC/C,QAAQuC,GAAT,GAAeE,SAASC,OAAT,CAAiBC,kBAAkBL,MAAlB,EAA0BtC,OAA1B,EAAmCD,WAAnC,EAAjB,CAAf,GAAoF0C,SAASG,SAAT,CAAmBN,MAAnB,CAA9F;iBADD,CAEE,OAAOE,CAAP,EAAU;+BACAvC,KAAX,GAAmBc,WAAWd,KAAX,IAAoB,0DAA0D,CAACD,QAAQuC,GAAT,GAAe,OAAf,GAAyB,SAAnF,IAAgG,iBAAhG,GAAoHC,CAA3J;;mBAGEJ,CAAH,IAAQC,YAAY,GAAZ,GAAkBC,MAA1B;;uBAGU9B,IAAX,GAAkB2B,GAAGhB,IAAH,CAAQ,GAAR,CAAlB;;YAGKU,UAAUG,iBAAiBH,OAAjB,GAA2BG,iBAAiBH,OAAjB,IAA4B,EAAvE;YAEIG,iBAAiBE,OAArB,EAA8BL,QAAQ,SAAR,IAAqBG,iBAAiBE,OAAtC;YAC1BF,iBAAiBC,IAArB,EAA2BJ,QAAQ,MAAR,IAAkBG,iBAAiBC,IAAnC;YAErBf,SAAS,EAAf;aACK,IAAMI,IAAX,IAAmBO,OAAnB,EAA4B;gBACvBA,QAAQP,IAAR,MAAkBS,EAAET,IAAF,CAAtB,EAA+B;uBACvBD,IAAP,CACCC,KAAKC,OAAL,CAAaC,WAAb,EAA0BC,gBAA1B,EAA4CF,OAA5C,CAAoDC,WAApD,EAAiEE,WAAjE,EAA8EH,OAA9E,CAAsFI,UAAtF,EAAkGC,UAAlG,IACA,GADA,GAEAC,QAAQP,IAAR,EAAcC,OAAd,CAAsBC,WAAtB,EAAmCC,gBAAnC,EAAqDF,OAArD,CAA6DC,WAA7D,EAA0EE,WAA1E,EAAuFH,OAAvF,CAA+FO,WAA/F,EAA4GF,UAA5G,CAHD;;;YAOEV,OAAOE,MAAX,EAAmB;uBACPH,KAAX,GAAmBC,OAAOC,IAAP,CAAY,GAAZ,CAAnB;;eAGMJ,UAAP;;CAzGF,CA6GA;;ADnKA,IAAMC,YAAY,iBAAlB;AACA,AAEA;AACA,IAAMV,YAAqD;YACjD,KADiD;WAGlD,kBAAUS,UAAV,EAAoCf,OAApC,EAAT;YACQc,UAAUC,WAAWP,IAAX,IAAmBO,WAAWP,IAAX,CAAgBL,KAAhB,CAAsBa,SAAtB,CAAnC;YACIpB,gBAAgBmB,UAApB;YAEID,OAAJ,EAAa;gBACNzB,SAASW,QAAQX,MAAR,IAAkBO,cAAcP,MAAhC,IAA0C,KAAzD;gBACMoB,MAAMK,QAAQ,CAAR,EAAWf,WAAX,EAAZ;gBACMF,MAAMiB,QAAQ,CAAR,CAAZ;gBACMF,YAAevB,MAAf,UAAyBW,QAAQS,GAAR,IAAeA,GAAxC,CAAN;gBACMC,gBAAgBvB,QAAQyB,SAAR,CAAtB;0BAEcH,GAAd,GAAoBA,GAApB;0BACcZ,GAAd,GAAoBA,GAApB;0BACcW,IAAd,GAAqBH,SAArB;gBAEIK,aAAJ,EAAmB;gCACFA,cAAcG,KAAd,CAAoBjB,aAApB,EAAmCI,OAAnC,CAAhB;;SAZF,MAcO;0BACQC,KAAd,GAAsBL,cAAcK,KAAd,IAAuB,wBAA7C;;eAGML,aAAP;KAzByD;eA4B9C,sBAAUA,aAAV,EAAuCI,OAAvC,EAAb;YACQX,SAASW,QAAQX,MAAR,IAAkBO,cAAcP,MAAhC,IAA0C,KAAzD;YACMoB,MAAMb,cAAca,GAA1B;YACMG,YAAevB,MAAf,UAAyBW,QAAQS,GAAR,IAAeA,GAAxC,CAAN;YACMC,gBAAgBvB,QAAQyB,SAAR,CAAtB;YAEIF,aAAJ,EAAmB;4BACFA,cAAcC,SAAd,CAAwBf,aAAxB,EAAuCI,OAAvC,CAAhB;;YAGKO,gBAAgBX,aAAtB;YACMC,MAAMD,cAAcC,GAA1B;sBACcW,IAAd,IAAwBC,OAAOT,QAAQS,GAAvC,UAA8CZ,GAA9C;eAEOU,aAAP;;CA1CF,CA8CA;;AD5DA,IAAMH,OAAO,0DAAb;AACA,AAEA;AACA,IAAME,YAAsE;YAClE,UADkE;WAGnE,eAAUV,aAAV,EAAuCI,OAAvC,EAAT;YACQF,iBAAiBF,aAAvB;uBACeR,IAAf,GAAsBU,eAAeD,GAArC;uBACeA,GAAf,GAAqBQ,SAArB;YAEI,CAACL,QAAQE,QAAT,KAAsB,CAACJ,eAAeV,IAAhB,IAAwB,CAACU,eAAeV,IAAf,CAAoBe,KAApB,CAA0BC,IAA1B,CAA/C,CAAJ,EAAqF;2BACrEH,KAAf,GAAuBH,eAAeG,KAAf,IAAwB,oBAA/C;;eAGMH,cAAP;KAZ0E;eAe/D,mBAAUA,cAAV,EAAyCE,OAAzC,EAAb;YACQJ,gBAAgBE,cAAtB;;sBAEcD,GAAd,GAAoB,CAACC,eAAeV,IAAf,IAAuB,EAAxB,EAA4BW,WAA5B,EAApB;eACOH,aAAP;;CAnBF,CAuBA;;ADhCAT,QAAQQ,QAAKN,MAAb,IAAuBM,OAAvB;AAEA,AACAR,QAAQO,UAAML,MAAd,IAAwBK,SAAxB;AAEA,AACAP,QAAQM,UAAGJ,MAAX,IAAqBI,SAArB;AAEA,AACAN,QAAQK,UAAIH,MAAZ,IAAsBG,SAAtB;AAEA,AACAL,QAAQI,UAAOF,MAAf,IAAyBE,SAAzB;AAEA,AACAJ,QAAQG,UAAID,MAAZ,IAAsBC,SAAtB;AAEA,AACAH,QAAQC,UAAKC,MAAb,IAAuBD,SAAvB,CAEA;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.min.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.min.d.ts new file mode 100644 index 0000000..da51e23 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.min.d.ts @@ -0,0 +1,59 @@ +export interface URIComponents { + scheme?: string; + userinfo?: string; + host?: string; + port?: number | string; + path?: string; + query?: string; + fragment?: string; + reference?: string; + error?: string; +} +export interface URIOptions { + scheme?: string; + reference?: string; + tolerant?: boolean; + absolutePath?: boolean; + iri?: boolean; + unicodeSupport?: boolean; + domainHost?: boolean; +} +export interface URISchemeHandler { + scheme: string; + parse(components: ParentComponents, options: Options): Components; + serialize(components: Components, options: Options): ParentComponents; + unicodeSupport?: boolean; + domainHost?: boolean; + absolutePath?: boolean; +} +export interface URIRegExps { + NOT_SCHEME: RegExp; + NOT_USERINFO: RegExp; + NOT_HOST: RegExp; + NOT_PATH: RegExp; + NOT_PATH_NOSCHEME: RegExp; + NOT_QUERY: RegExp; + NOT_FRAGMENT: RegExp; + ESCAPE: RegExp; + UNRESERVED: RegExp; + OTHER_CHARS: RegExp; + PCT_ENCODED: RegExp; + IPV4ADDRESS: RegExp; + IPV6ADDRESS: RegExp; +} +export declare const SCHEMES: { + [scheme: string]: URISchemeHandler; +}; +export declare function pctEncChar(chr: string): string; +export declare function pctDecChars(str: string): string; +export declare function parse(uriString: string, options?: URIOptions): URIComponents; +export declare function removeDotSegments(input: string): string; +export declare function serialize(components: URIComponents, options?: URIOptions): string; +export declare function resolveComponents(base: URIComponents, relative: URIComponents, options?: URIOptions, skipNormalization?: boolean): URIComponents; +export declare function resolve(baseURI: string, relativeURI: string, options?: URIOptions): string; +export declare function normalize(uri: string, options?: URIOptions): string; +export declare function normalize(uri: URIComponents, options?: URIOptions): URIComponents; +export declare function equal(uriA: string, uriB: string, options?: URIOptions): boolean; +export declare function equal(uriA: URIComponents, uriB: URIComponents, options?: URIOptions): boolean; +export declare function escapeComponent(str: string, options?: URIOptions): string; +export declare function unescapeComponent(str: string, options?: URIOptions): string; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.min.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.min.js new file mode 100644 index 0000000..fcd8458 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/es5/uri.all.min.js @@ -0,0 +1,3 @@ +/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r(e.URI=e.URI||{})}(this,function(e){"use strict";function r(){for(var e=arguments.length,r=Array(e),n=0;n1){r[0]=r[0].slice(0,-1);for(var t=r.length-1,o=1;o1&&(t=n[0]+"@",e=n[1]),e=e.replace(j,"."),t+f(e.split("."),r).join(".")}function p(e){for(var r=[],n=0,t=e.length;n=55296&&o<=56319&&n>6|192).toString(16).toUpperCase()+"%"+(63&r|128).toString(16).toUpperCase():"%"+(r>>12|224).toString(16).toUpperCase()+"%"+(r>>6&63|128).toString(16).toUpperCase()+"%"+(63&r|128).toString(16).toUpperCase()}function d(e){for(var r="",n=0,t=e.length;n=194&&o<224){if(t-n>=6){var a=parseInt(e.substr(n+4,2),16);r+=String.fromCharCode((31&o)<<6|63&a)}else r+=e.substr(n,6);n+=6}else if(o>=224){if(t-n>=9){var i=parseInt(e.substr(n+4,2),16),u=parseInt(e.substr(n+7,2),16);r+=String.fromCharCode((15&o)<<12|(63&i)<<6|63&u)}else r+=e.substr(n,9);n+=9}else r+=e.substr(n,3),n+=3}return r}function l(e,r){function n(e){var n=d(e);return n.match(r.UNRESERVED)?n:e}return e.scheme&&(e.scheme=String(e.scheme).replace(r.PCT_ENCODED,n).toLowerCase().replace(r.NOT_SCHEME,"")),e.userinfo!==undefined&&(e.userinfo=String(e.userinfo).replace(r.PCT_ENCODED,n).replace(r.NOT_USERINFO,h).replace(r.PCT_ENCODED,o)),e.host!==undefined&&(e.host=String(e.host).replace(r.PCT_ENCODED,n).toLowerCase().replace(r.NOT_HOST,h).replace(r.PCT_ENCODED,o)),e.path!==undefined&&(e.path=String(e.path).replace(r.PCT_ENCODED,n).replace(e.scheme?r.NOT_PATH:r.NOT_PATH_NOSCHEME,h).replace(r.PCT_ENCODED,o)),e.query!==undefined&&(e.query=String(e.query).replace(r.PCT_ENCODED,n).replace(r.NOT_QUERY,h).replace(r.PCT_ENCODED,o)),e.fragment!==undefined&&(e.fragment=String(e.fragment).replace(r.PCT_ENCODED,n).replace(r.NOT_FRAGMENT,h).replace(r.PCT_ENCODED,o)),e}function m(e){return e.replace(/^0*(.*)/,"$1")||"0"}function g(e,r){var n=e.match(r.IPV4ADDRESS)||[],t=T(n,2),o=t[1];return o?o.split(".").map(m).join("."):e}function v(e,r){var n=e.match(r.IPV6ADDRESS)||[],t=T(n,3),o=t[1],a=t[2];if(o){for(var i=o.toLowerCase().split("::").reverse(),u=T(i,2),s=u[0],f=u[1],c=f?f.split(":").map(m):[],p=s.split(":").map(m),h=r.IPV4ADDRESS.test(p[p.length-1]),d=h?7:8,l=p.length-d,v=Array(d),E=0;E1){var A=v.slice(0,y.index),D=v.slice(y.index+y.length);S=A.join(":")+"::"+D.join(":")}else S=v.join(":");return a&&(S+="%"+a),S}return e}function E(e){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n={},t=!1!==r.iri?R:F;"suffix"===r.reference&&(e=(r.scheme?r.scheme+":":"")+"//"+e);var o=e.match(K);if(o){W?(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5])):(n.scheme=o[1]||undefined,n.userinfo=-1!==e.indexOf("@")?o[3]:undefined,n.host=-1!==e.indexOf("//")?o[4]:undefined,n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=-1!==e.indexOf("?")?o[7]:undefined,n.fragment=-1!==e.indexOf("#")?o[8]:undefined,isNaN(n.port)&&(n.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?o[4]:undefined)),n.host&&(n.host=v(g(n.host,t),t)),n.scheme!==undefined||n.userinfo!==undefined||n.host!==undefined||n.port!==undefined||n.path||n.query!==undefined?n.scheme===undefined?n.reference="relative":n.fragment===undefined?n.reference="absolute":n.reference="uri":n.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");var a=J[(r.scheme||n.scheme||"").toLowerCase()];if(r.unicodeSupport||a&&a.unicodeSupport)l(n,t);else{if(n.host&&(r.domainHost||a&&a.domainHost))try{n.host=B.toASCII(n.host.replace(t.PCT_ENCODED,d).toLowerCase())}catch(i){n.error=n.error||"Host's domain name can not be converted to ASCII via punycode: "+i}l(n,F)}a&&a.parse&&a.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}function C(e,r){var n=!1!==r.iri?R:F,t=[];return e.userinfo!==undefined&&(t.push(e.userinfo),t.push("@")),e.host!==undefined&&t.push(v(g(String(e.host),n),n).replace(n.IPV6ADDRESS,function(e,r,n){return"["+r+(n?"%25"+n:"")+"]"})),"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):undefined}function y(e){for(var r=[];e.length;)if(e.match(X))e=e.replace(X,"");else if(e.match(ee))e=e.replace(ee,"/");else if(e.match(re))e=e.replace(re,"/"),r.pop();else if("."===e||".."===e)e="";else{var n=e.match(ne);if(!n)throw new Error("Unexpected dot segment condition");var t=n[0];e=e.slice(t.length),r.push(t)}return r.join("")}function S(e){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.iri?R:F,t=[],o=J[(r.scheme||e.scheme||"").toLowerCase()];if(o&&o.serialize&&o.serialize(e,r),e.host)if(n.IPV6ADDRESS.test(e.host));else if(r.domainHost||o&&o.domainHost)try{e.host=r.iri?B.toUnicode(e.host):B.toASCII(e.host.replace(n.PCT_ENCODED,d).toLowerCase())}catch(u){e.error=e.error||"Host's domain name can not be converted to "+(r.iri?"Unicode":"ASCII")+" via punycode: "+u}l(e,n),"suffix"!==r.reference&&e.scheme&&(t.push(e.scheme),t.push(":"));var a=C(e,r);if(a!==undefined&&("suffix"!==r.reference&&t.push("//"),t.push(a),e.path&&"/"!==e.path.charAt(0)&&t.push("/")),e.path!==undefined){var i=e.path;r.absolutePath||o&&o.absolutePath||(i=y(i)),a===undefined&&(i=i.replace(/^\/\//,"/%2F")),t.push(i)}return e.query!==undefined&&(t.push("?"),t.push(e.query)),e.fragment!==undefined&&(t.push("#"),t.push(e.fragment)),t.join("")}function A(e,r){var n=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{},t=arguments[3],o={};return t||(e=E(S(e,n),n),r=E(S(r,n),n)),n=n||{},!n.tolerant&&r.scheme?(o.scheme=r.scheme,o.userinfo=r.userinfo,o.host=r.host,o.port=r.port,o.path=y(r.path||""),o.query=r.query):(r.userinfo!==undefined||r.host!==undefined||r.port!==undefined?(o.userinfo=r.userinfo,o.host=r.host,o.port=r.port,o.path=y(r.path||""),o.query=r.query):(r.path?("/"===r.path.charAt(0)?o.path=y(r.path):(e.userinfo===undefined&&e.host===undefined&&e.port===undefined||e.path?e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+r.path:o.path=r.path:o.path="/"+r.path,o.path=y(o.path)),o.query=r.query):(o.path=e.path,r.query!==undefined?o.query=r.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=r.fragment,o}function D(e,r,n){var t=i({scheme:"null"},n);return S(A(E(e,t),E(r,t),t,!0),t)}function w(e,r){return"string"==typeof e?e=S(E(e,r),r):"object"===t(e)&&(e=E(S(e,r),r)),e}function b(e,r,n){return"string"==typeof e?e=S(E(e,n),n):"object"===t(e)&&(e=S(e,n)),"string"==typeof r?r=S(E(r,n),n):"object"===t(r)&&(r=S(r,n)),e===r}function x(e,r){return e&&e.toString().replace(r&&r.iri?R.ESCAPE:F.ESCAPE,h)}function O(e,r){return e&&e.toString().replace(r&&r.iri?R.PCT_ENCODED:F.PCT_ENCODED,d)}function N(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}function I(e){var r=d(e);return r.match(he)?r:e}var F=u(!1),R=u(!0),T=function(){function e(e,r){var n=[],t=!0,o=!1,a=undefined;try{for(var i,u=e[Symbol.iterator]();!(t=(i=u.next()).done)&&(n.push(i.value),!r||n.length!==r);t=!0);}catch(s){o=!0,a=s}finally{try{!t&&u["return"]&&u["return"]()}finally{if(o)throw a}}return n}return function(r,n){if(Array.isArray(r))return r;if(Symbol.iterator in Object(r))return e(r,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_=function(e){if(Array.isArray(e)){for(var r=0,n=Array(e.length);r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},z=Math.floor,L=String.fromCharCode,$=function(e){return String.fromCodePoint.apply(String,_(e))},M=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:36},V=function(e,r){return e+22+75*(e<26)-((0!=r)<<5)},k=function(e,r,n){var t=0;for(e=n?z(e/700):e>>1,e+=z(e/r);e>455;t+=36)e=z(e/35);return z(t+36*e/(e+38))},Z=function(e){var r=[],n=e.length,t=0,o=128,a=72,i=e.lastIndexOf("-");i<0&&(i=0);for(var u=0;u=128&&s("not-basic"),r.push(e.charCodeAt(u));for(var f=i>0?i+1:0;f=n&&s("invalid-input");var d=M(e.charCodeAt(f++));(d>=36||d>z((P-t)/p))&&s("overflow"),t+=d*p;var l=h<=a?1:h>=a+26?26:h-a;if(dz(P/m)&&s("overflow"),p*=m}var g=r.length+1;a=k(t-c,g,0==c),z(t/g)>P-o&&s("overflow"),o+=z(t/g),t%=g,r.splice(t++,0,o)}return String.fromCodePoint.apply(String,r)},G=function(e){var r=[];e=p(e);var n=e.length,t=128,o=0,a=72,i=!0,u=!1,f=undefined;try{for(var c,h=e[Symbol.iterator]();!(i=(c=h.next()).done);i=!0){var d=c.value;d<128&&r.push(L(d))}}catch(U){u=!0,f=U}finally{try{!i&&h["return"]&&h["return"]()}finally{if(u)throw f}}var l=r.length,m=l;for(l&&r.push("-");m=t&&Az((P-o)/D)&&s("overflow"),o+=(g-t)*D,t=g;var w=!0,b=!1,x=undefined;try{for(var O,N=e[Symbol.iterator]();!(w=(O=N.next()).done);w=!0){var I=O.value;if(IP&&s("overflow"),I==t){for(var F=o,R=36;;R+=36){var T=R<=a?1:R>=a+26?26:R-a;if(FA-Z\\x5E-\\x7E]",'[\\"\\\\]'),he=new RegExp(se,"g"),de=new RegExp(ce,"g"),le=new RegExp(r("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',pe),"g"),me=new RegExp(r("[^]",se,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),ge=me,ve={scheme:"mailto",parse:function(e,r){var n=e,t=n.to=n.path?n.path.split(","):[];if(n.path=undefined,n.query){for(var o=!1,a={},i=n.query.split("&"),u=0,s=i.length;u):string {\n\tif (sets.length > 1) {\n\t\tsets[0] = sets[0].slice(0, -1);\n\t\tconst xl = sets.length - 1;\n\t\tfor (let x = 1; x < xl; ++x) {\n\t\t\tsets[x] = sets[x].slice(1, -1);\n\t\t}\n\t\tsets[xl] = sets[xl].slice(1);\n\t\treturn sets.join('');\n\t} else {\n\t\treturn sets[0];\n\t}\n}\n\nexport function subexp(str:string):string {\n\treturn \"(?:\" + str + \")\";\n}\n\nexport function typeOf(o:any):string {\n\treturn o === undefined ? \"undefined\" : (o === null ? \"null\" : Object.prototype.toString.call(o).split(\" \").pop().split(\"]\").shift().toLowerCase());\n}\n\nexport function toUpperCase(str:string):string {\n\treturn str.toUpperCase();\n}\n\nexport function toArray(obj:any):Array {\n\treturn obj !== undefined && obj !== null ? (obj instanceof Array ? obj : (typeof obj.length !== \"number\" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj))) : [];\n}\n\n\nexport function assign(target: object, source: any): any {\n\tconst obj = target as any;\n\tif (source) {\n\t\tfor (const key in source) {\n\t\t\tobj[key] = source[key];\n\t\t}\n\t}\n\treturn obj;\n}","import { URIRegExps } from \"./uri\";\nimport { merge, subexp } from \"./util\";\n\nexport function buildExps(isIRI:boolean):URIRegExps {\n\tconst\n\t\tALPHA$$ = \"[A-Za-z]\",\n\t\tCR$ = \"[\\\\x0D]\",\n\t\tDIGIT$$ = \"[0-9]\",\n\t\tDQUOTE$$ = \"[\\\\x22]\",\n\t\tHEXDIG$$ = merge(DIGIT$$, \"[A-Fa-f]\"), //case-insensitive\n\t\tLF$$ = \"[\\\\x0A]\",\n\t\tSP$$ = \"[\\\\x20]\",\n\t\tPCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)), //expanded\n\t\tGEN_DELIMS$$ = \"[\\\\:\\\\/\\\\?\\\\#\\\\[\\\\]\\\\@]\",\n\t\tSUB_DELIMS$$ = \"[\\\\!\\\\$\\\\&\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\=]\",\n\t\tRESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),\n\t\tUCSCHAR$$ = isIRI ? \"[\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF]\" : \"[]\", //subset, excludes bidi control characters\n\t\tIPRIVATE$$ = isIRI ? \"[\\\\uE000-\\\\uF8FF]\" : \"[]\", //subset\n\t\tUNRESERVED$$ = merge(ALPHA$$, DIGIT$$, \"[\\\\-\\\\.\\\\_\\\\~]\", UCSCHAR$$),\n\t\tSCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\") + \"*\"),\n\t\tUSERINFO$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\")) + \"*\"),\n\t\tDEC_OCTET$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"[1-9]\" + DIGIT$$) + \"|\" + DIGIT$$),\n\t\tDEC_OCTET_RELAXED$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"0?[1-9]\" + DIGIT$$) + \"|0?0?\" + DIGIT$$), //relaxed parsing rules\n\t\tIPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$),\n\t\tH16$ = subexp(HEXDIG$$ + \"{1,4}\"),\n\t\tLS32$ = subexp(subexp(H16$ + \"\\\\:\" + H16$) + \"|\" + IPV4ADDRESS$),\n\t\tIPV6ADDRESS1$ = subexp( subexp(H16$ + \"\\\\:\") + \"{6}\" + LS32$), // 6( h16 \":\" ) ls32\n\t\tIPV6ADDRESS2$ = subexp( \"\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{5}\" + LS32$), // \"::\" 5( h16 \":\" ) ls32\n\t\tIPV6ADDRESS3$ = subexp(subexp( H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{4}\" + LS32$), //[ h16 ] \"::\" 4( h16 \":\" ) ls32\n\t\tIPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,1}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{3}\" + LS32$), //[ *1( h16 \":\" ) h16 ] \"::\" 3( h16 \":\" ) ls32\n\t\tIPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,2}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{2}\" + LS32$), //[ *2( h16 \":\" ) h16 ] \"::\" 2( h16 \":\" ) ls32\n\t\tIPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,3}\" + H16$) + \"?\\\\:\\\\:\" + H16$ + \"\\\\:\" + LS32$), //[ *3( h16 \":\" ) h16 ] \"::\" h16 \":\" ls32\n\t\tIPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,4}\" + H16$) + \"?\\\\:\\\\:\" + LS32$), //[ *4( h16 \":\" ) h16 ] \"::\" ls32\n\t\tIPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,5}\" + H16$) + \"?\\\\:\\\\:\" + H16$ ), //[ *5( h16 \":\" ) h16 ] \"::\" h16\n\t\tIPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,6}\" + H16$) + \"?\\\\:\\\\:\" ), //[ *6( h16 \":\" ) h16 ] \"::\"\n\t\tIPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join(\"|\")),\n\t\tZONEID$ = subexp(subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$) + \"+\"), //RFC 6874\n\t\tIPV6ADDRZ$ = subexp(IPV6ADDRESS$ + \"\\\\%25\" + ZONEID$), //RFC 6874\n\t\tIPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + ZONEID$), //RFC 6874, with relaxed parsing rules\n\t\tIPVFUTURE$ = subexp(\"[vV]\" + HEXDIG$$ + \"+\\\\.\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\") + \"+\"),\n\t\tIP_LITERAL$ = subexp(\"\\\\[\" + subexp(IPV6ADDRZ_RELAXED$ + \"|\" + IPV6ADDRESS$ + \"|\" + IPVFUTURE$) + \"\\\\]\"), //RFC 6874\n\t\tREG_NAME$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$)) + \"*\"),\n\t\tHOST$ = subexp(IP_LITERAL$ + \"|\" + IPV4ADDRESS$ + \"(?!\" + REG_NAME$ + \")\" + \"|\" + REG_NAME$),\n\t\tPORT$ = subexp(DIGIT$$ + \"*\"),\n\t\tAUTHORITY$ = subexp(subexp(USERINFO$ + \"@\") + \"?\" + HOST$ + subexp(\"\\\\:\" + PORT$) + \"?\"),\n\t\tPCHAR$ = subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@]\")),\n\t\tSEGMENT$ = subexp(PCHAR$ + \"*\"),\n\t\tSEGMENT_NZ$ = subexp(PCHAR$ + \"+\"),\n\t\tSEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\@]\")) + \"+\"),\n\t\tPATH_ABEMPTY$ = subexp(subexp(\"\\\\/\" + SEGMENT$) + \"*\"),\n\t\tPATH_ABSOLUTE$ = subexp(\"\\\\/\" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + \"?\"), //simplified\n\t\tPATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_EMPTY$ = \"(?!\" + PCHAR$ + \")\",\n\t\tPATH$ = subexp(PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tQUERY$ = subexp(subexp(PCHAR$ + \"|\" + merge(\"[\\\\/\\\\?]\", IPRIVATE$$)) + \"*\"),\n\t\tFRAGMENT$ = subexp(subexp(PCHAR$ + \"|[\\\\/\\\\?]\") + \"*\"),\n\t\tHIER_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tURI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tRELATIVE_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$),\n\t\tRELATIVE$ = subexp(RELATIVE_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tURI_REFERENCE$ = subexp(URI$ + \"|\" + RELATIVE$),\n\t\tABSOLUTE_URI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\"),\n\n\t\tGENERIC_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tRELATIVE_REF$ = \"^(){0}\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tABSOLUTE_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?$\",\n\t\tSAMEDOC_REF$ = \"^\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tAUTHORITY_REF$ = \"^\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?$\"\n\t;\n\n\treturn {\n\t\tNOT_SCHEME : new RegExp(merge(\"[^]\", ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\"), \"g\"),\n\t\tNOT_USERINFO : new RegExp(merge(\"[^\\\\%\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_HOST : new RegExp(merge(\"[^\\\\%\\\\[\\\\]\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH : new RegExp(merge(\"[^\\\\%\\\\/\\\\:\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH_NOSCHEME : new RegExp(merge(\"[^\\\\%\\\\/\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_QUERY : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\", IPRIVATE$$), \"g\"),\n\t\tNOT_FRAGMENT : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\"), \"g\"),\n\t\tESCAPE : new RegExp(merge(\"[^]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tUNRESERVED : new RegExp(UNRESERVED$$, \"g\"),\n\t\tOTHER_CHARS : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, RESERVED$$), \"g\"),\n\t\tPCT_ENCODED : new RegExp(PCT_ENCODED$, \"g\"),\n\t\tIPV4ADDRESS : new RegExp(\"^(\" + IPV4ADDRESS$ + \")$\"),\n\t\tIPV6ADDRESS : new RegExp(\"^\\\\[?(\" + IPV6ADDRESS$ + \")\" + subexp(subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + \"(\" + ZONEID$ + \")\") + \"?\\\\]?$\") //RFC 6874, with relaxed parsing rules\n\t};\n}\n\nexport default buildExps(false);\n","'use strict';\n\n/** Highest positive signed 32-bit float value */\nconst maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1\n\n/** Bootstring parameters */\nconst base = 36;\nconst tMin = 1;\nconst tMax = 26;\nconst skew = 38;\nconst damp = 700;\nconst initialBias = 72;\nconst initialN = 128; // 0x80\nconst delimiter = '-'; // '\\x2D'\n\n/** Regular expressions */\nconst regexPunycode = /^xn--/;\nconst regexNonASCII = /[^\\0-\\x7E]/; // non-ASCII chars\nconst regexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g; // RFC 3490 separators\n\n/** Error messages */\nconst errors = {\n\t'overflow': 'Overflow: input needs wider integers to process',\n\t'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n\t'invalid-input': 'Invalid input'\n};\n\n/** Convenience shortcuts */\nconst baseMinusTMin = base - tMin;\nconst floor = Math.floor;\nconst stringFromCharCode = String.fromCharCode;\n\n/*--------------------------------------------------------------------------*/\n\n/**\n * A generic error utility function.\n * @private\n * @param {String} type The error type.\n * @returns {Error} Throws a `RangeError` with the applicable error message.\n */\nfunction error(type) {\n\tthrow new RangeError(errors[type]);\n}\n\n/**\n * A generic `Array#map` utility function.\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} callback The function that gets called for every array\n * item.\n * @returns {Array} A new array of values returned by the callback function.\n */\nfunction map(array, fn) {\n\tconst result = [];\n\tlet length = array.length;\n\twhile (length--) {\n\t\tresult[length] = fn(array[length]);\n\t}\n\treturn result;\n}\n\n/**\n * A simple `Array#map`-like wrapper to work with domain name strings or email\n * addresses.\n * @private\n * @param {String} domain The domain name or email address.\n * @param {Function} callback The function that gets called for every\n * character.\n * @returns {Array} A new string of characters returned by the callback\n * function.\n */\nfunction mapDomain(string, fn) {\n\tconst parts = string.split('@');\n\tlet result = '';\n\tif (parts.length > 1) {\n\t\t// In email addresses, only the domain name should be punycoded. Leave\n\t\t// the local part (i.e. everything up to `@`) intact.\n\t\tresult = parts[0] + '@';\n\t\tstring = parts[1];\n\t}\n\t// Avoid `split(regex)` for IE8 compatibility. See #17.\n\tstring = string.replace(regexSeparators, '\\x2E');\n\tconst labels = string.split('.');\n\tconst encoded = map(labels, fn).join('.');\n\treturn result + encoded;\n}\n\n/**\n * Creates an array containing the numeric code points of each Unicode\n * character in the string. While JavaScript uses UCS-2 internally,\n * this function will convert a pair of surrogate halves (each of which\n * UCS-2 exposes as separate characters) into a single code point,\n * matching UTF-16.\n * @see `punycode.ucs2.encode`\n * @see \n * @memberOf punycode.ucs2\n * @name decode\n * @param {String} string The Unicode input string (UCS-2).\n * @returns {Array} The new array of code points.\n */\nfunction ucs2decode(string) {\n\tconst output = [];\n\tlet counter = 0;\n\tconst length = string.length;\n\twhile (counter < length) {\n\t\tconst value = string.charCodeAt(counter++);\n\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t// It's a high surrogate, and there is a next character.\n\t\t\tconst extra = string.charCodeAt(counter++);\n\t\t\tif ((extra & 0xFC00) == 0xDC00) { // Low surrogate.\n\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t} else {\n\t\t\t\t// It's an unmatched surrogate; only append this code unit, in case the\n\t\t\t\t// next code unit is the high surrogate of a surrogate pair.\n\t\t\t\toutput.push(value);\n\t\t\t\tcounter--;\n\t\t\t}\n\t\t} else {\n\t\t\toutput.push(value);\n\t\t}\n\t}\n\treturn output;\n}\n\n/**\n * Creates a string based on an array of numeric code points.\n * @see `punycode.ucs2.decode`\n * @memberOf punycode.ucs2\n * @name encode\n * @param {Array} codePoints The array of numeric code points.\n * @returns {String} The new Unicode string (UCS-2).\n */\nconst ucs2encode = array => String.fromCodePoint(...array);\n\n/**\n * Converts a basic code point into a digit/integer.\n * @see `digitToBasic()`\n * @private\n * @param {Number} codePoint The basic numeric code point value.\n * @returns {Number} The numeric value of a basic code point (for use in\n * representing integers) in the range `0` to `base - 1`, or `base` if\n * the code point does not represent a value.\n */\nconst basicToDigit = function(codePoint) {\n\tif (codePoint - 0x30 < 0x0A) {\n\t\treturn codePoint - 0x16;\n\t}\n\tif (codePoint - 0x41 < 0x1A) {\n\t\treturn codePoint - 0x41;\n\t}\n\tif (codePoint - 0x61 < 0x1A) {\n\t\treturn codePoint - 0x61;\n\t}\n\treturn base;\n};\n\n/**\n * Converts a digit/integer into a basic code point.\n * @see `basicToDigit()`\n * @private\n * @param {Number} digit The numeric value of a basic code point.\n * @returns {Number} The basic code point whose value (when used for\n * representing integers) is `digit`, which needs to be in the range\n * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n * used; else, the lowercase form is used. The behavior is undefined\n * if `flag` is non-zero and `digit` has no uppercase form.\n */\nconst digitToBasic = function(digit, flag) {\n\t// 0..25 map to ASCII a..z or A..Z\n\t// 26..35 map to ASCII 0..9\n\treturn digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n};\n\n/**\n * Bias adaptation function as per section 3.4 of RFC 3492.\n * https://tools.ietf.org/html/rfc3492#section-3.4\n * @private\n */\nconst adapt = function(delta, numPoints, firstTime) {\n\tlet k = 0;\n\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\tdelta += floor(delta / numPoints);\n\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\tdelta = floor(delta / baseMinusTMin);\n\t}\n\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n};\n\n/**\n * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n * symbols.\n * @memberOf punycode\n * @param {String} input The Punycode string of ASCII-only symbols.\n * @returns {String} The resulting string of Unicode symbols.\n */\nconst decode = function(input) {\n\t// Don't use UCS-2.\n\tconst output = [];\n\tconst inputLength = input.length;\n\tlet i = 0;\n\tlet n = initialN;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points: let `basic` be the number of input code\n\t// points before the last delimiter, or `0` if there is none, then copy\n\t// the first basic code points to the output.\n\n\tlet basic = input.lastIndexOf(delimiter);\n\tif (basic < 0) {\n\t\tbasic = 0;\n\t}\n\n\tfor (let j = 0; j < basic; ++j) {\n\t\t// if it's not a basic code point\n\t\tif (input.charCodeAt(j) >= 0x80) {\n\t\t\terror('not-basic');\n\t\t}\n\t\toutput.push(input.charCodeAt(j));\n\t}\n\n\t// Main decoding loop: start just after the last delimiter if any basic code\n\t// points were copied; start at the beginning otherwise.\n\n\tfor (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {\n\n\t\t// `index` is the index of the next character to be consumed.\n\t\t// Decode a generalized variable-length integer into `delta`,\n\t\t// which gets added to `i`. The overflow checking is easier\n\t\t// if we increase `i` as we go, then subtract off its starting\n\t\t// value at the end to obtain `delta`.\n\t\tlet oldi = i;\n\t\tfor (let w = 1, k = base; /* no condition */; k += base) {\n\n\t\t\tif (index >= inputLength) {\n\t\t\t\terror('invalid-input');\n\t\t\t}\n\n\t\t\tconst digit = basicToDigit(input.charCodeAt(index++));\n\n\t\t\tif (digit >= base || digit > floor((maxInt - i) / w)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\ti += digit * w;\n\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n\t\t\tif (digit < t) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst baseMinusT = base - t;\n\t\t\tif (w > floor(maxInt / baseMinusT)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tw *= baseMinusT;\n\n\t\t}\n\n\t\tconst out = output.length + 1;\n\t\tbias = adapt(i - oldi, out, oldi == 0);\n\n\t\t// `i` was supposed to wrap around from `out` to `0`,\n\t\t// incrementing `n` each time, so we'll fix that now:\n\t\tif (floor(i / out) > maxInt - n) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tn += floor(i / out);\n\t\ti %= out;\n\n\t\t// Insert `n` at position `i` of the output.\n\t\toutput.splice(i++, 0, n);\n\n\t}\n\n\treturn String.fromCodePoint(...output);\n};\n\n/**\n * Converts a string of Unicode symbols (e.g. a domain name label) to a\n * Punycode string of ASCII-only symbols.\n * @memberOf punycode\n * @param {String} input The string of Unicode symbols.\n * @returns {String} The resulting Punycode string of ASCII-only symbols.\n */\nconst encode = function(input) {\n\tconst output = [];\n\n\t// Convert the input in UCS-2 to an array of Unicode code points.\n\tinput = ucs2decode(input);\n\n\t// Cache the length.\n\tlet inputLength = input.length;\n\n\t// Initialize the state.\n\tlet n = initialN;\n\tlet delta = 0;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points.\n\tfor (const currentValue of input) {\n\t\tif (currentValue < 0x80) {\n\t\t\toutput.push(stringFromCharCode(currentValue));\n\t\t}\n\t}\n\n\tlet basicLength = output.length;\n\tlet handledCPCount = basicLength;\n\n\t// `handledCPCount` is the number of code points that have been handled;\n\t// `basicLength` is the number of basic code points.\n\n\t// Finish the basic string with a delimiter unless it's empty.\n\tif (basicLength) {\n\t\toutput.push(delimiter);\n\t}\n\n\t// Main encoding loop:\n\twhile (handledCPCount < inputLength) {\n\n\t\t// All non-basic code points < n have been handled already. Find the next\n\t\t// larger one:\n\t\tlet m = maxInt;\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue >= n && currentValue < m) {\n\t\t\t\tm = currentValue;\n\t\t\t}\n\t\t}\n\n\t\t// Increase `delta` enough to advance the decoder's state to ,\n\t\t// but guard against overflow.\n\t\tconst handledCPCountPlusOne = handledCPCount + 1;\n\t\tif (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tdelta += (m - n) * handledCPCountPlusOne;\n\t\tn = m;\n\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue < n && ++delta > maxInt) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\t\t\tif (currentValue == n) {\n\t\t\t\t// Represent delta as a generalized variable-length integer.\n\t\t\t\tlet q = delta;\n\t\t\t\tfor (let k = base; /* no condition */; k += base) {\n\t\t\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\t\t\t\t\tif (q < t) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst qMinusT = q - t;\n\t\t\t\t\tconst baseMinusT = base - t;\n\t\t\t\t\toutput.push(\n\t\t\t\t\t\tstringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n\t\t\t\t\t);\n\t\t\t\t\tq = floor(qMinusT / baseMinusT);\n\t\t\t\t}\n\n\t\t\t\toutput.push(stringFromCharCode(digitToBasic(q, 0)));\n\t\t\t\tbias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n\t\t\t\tdelta = 0;\n\t\t\t\t++handledCPCount;\n\t\t\t}\n\t\t}\n\n\t\t++delta;\n\t\t++n;\n\n\t}\n\treturn output.join('');\n};\n\n/**\n * Converts a Punycode string representing a domain name or an email address\n * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n * it doesn't matter if you call it on a string that has already been\n * converted to Unicode.\n * @memberOf punycode\n * @param {String} input The Punycoded domain name or email address to\n * convert to Unicode.\n * @returns {String} The Unicode representation of the given Punycode\n * string.\n */\nconst toUnicode = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexPunycode.test(string)\n\t\t\t? decode(string.slice(4).toLowerCase())\n\t\t\t: string;\n\t});\n};\n\n/**\n * Converts a Unicode string representing a domain name or an email address to\n * Punycode. Only the non-ASCII parts of the domain name will be converted,\n * i.e. it doesn't matter if you call it with a domain that's already in\n * ASCII.\n * @memberOf punycode\n * @param {String} input The domain name or email address to convert, as a\n * Unicode string.\n * @returns {String} The Punycode representation of the given domain name or\n * email address.\n */\nconst toASCII = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexNonASCII.test(string)\n\t\t\t? 'xn--' + encode(string)\n\t\t\t: string;\n\t});\n};\n\n/*--------------------------------------------------------------------------*/\n\n/** Define the public API */\nconst punycode = {\n\t/**\n\t * A string representing the current Punycode.js version number.\n\t * @memberOf punycode\n\t * @type String\n\t */\n\t'version': '2.1.0',\n\t/**\n\t * An object of methods to convert from JavaScript's internal character\n\t * representation (UCS-2) to Unicode code points, and back.\n\t * @see \n\t * @memberOf punycode\n\t * @type Object\n\t */\n\t'ucs2': {\n\t\t'decode': ucs2decode,\n\t\t'encode': ucs2encode\n\t},\n\t'decode': decode,\n\t'encode': encode,\n\t'toASCII': toASCII,\n\t'toUnicode': toUnicode\n};\n\nexport default punycode;\n","/**\n * URI.js\n *\n * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.\n * @author Gary Court\n * @see http://github.com/garycourt/uri-js\n */\n\n/**\n * Copyright 2011 Gary Court. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are\n * permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of\n * conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice, this list\n * of conditions and the following disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those of the\n * authors and should not be interpreted as representing official policies, either expressed\n * or implied, of Gary Court.\n */\n\nimport URI_PROTOCOL from \"./regexps-uri\";\nimport IRI_PROTOCOL from \"./regexps-iri\";\nimport punycode from \"punycode\";\nimport { toUpperCase, typeOf, assign } from \"./util\";\n\nexport interface URIComponents {\n\tscheme?:string;\n\tuserinfo?:string;\n\thost?:string;\n\tport?:number|string;\n\tpath?:string;\n\tquery?:string;\n\tfragment?:string;\n\treference?:string;\n\terror?:string;\n}\n\nexport interface URIOptions {\n\tscheme?:string;\n\treference?:string;\n\ttolerant?:boolean;\n\tabsolutePath?:boolean;\n\tiri?:boolean;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n}\n\nexport interface URISchemeHandler {\n\tscheme:string;\n\tparse(components:ParentComponents, options:Options):Components;\n\tserialize(components:Components, options:Options):ParentComponents;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n\tabsolutePath?:boolean;\n}\n\nexport interface URIRegExps {\n\tNOT_SCHEME : RegExp,\n\tNOT_USERINFO : RegExp,\n\tNOT_HOST : RegExp,\n\tNOT_PATH : RegExp,\n\tNOT_PATH_NOSCHEME : RegExp,\n\tNOT_QUERY : RegExp,\n\tNOT_FRAGMENT : RegExp,\n\tESCAPE : RegExp,\n\tUNRESERVED : RegExp,\n\tOTHER_CHARS : RegExp,\n\tPCT_ENCODED : RegExp,\n\tIPV4ADDRESS : RegExp,\n\tIPV6ADDRESS : RegExp,\n}\n\nexport const SCHEMES:{[scheme:string]:URISchemeHandler} = {};\n\nexport function pctEncChar(chr:string):string {\n\tconst c = chr.charCodeAt(0);\n\tlet e:string;\n\n\tif (c < 16) e = \"%0\" + c.toString(16).toUpperCase();\n\telse if (c < 128) e = \"%\" + c.toString(16).toUpperCase();\n\telse if (c < 2048) e = \"%\" + ((c >> 6) | 192).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\telse e = \"%\" + ((c >> 12) | 224).toString(16).toUpperCase() + \"%\" + (((c >> 6) & 63) | 128).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\n\treturn e;\n}\n\nexport function pctDecChars(str:string):string {\n\tlet newStr = \"\";\n\tlet i = 0;\n\tconst il = str.length;\n\n\twhile (i < il) {\n\t\tconst c = parseInt(str.substr(i + 1, 2), 16);\n\n\t\tif (c < 128) {\n\t\t\tnewStr += String.fromCharCode(c);\n\t\t\ti += 3;\n\t\t}\n\t\telse if (c >= 194 && c < 224) {\n\t\t\tif ((il - i) >= 6) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 31) << 6) | (c2 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 6);\n\t\t\t}\n\t\t\ti += 6;\n\t\t}\n\t\telse if (c >= 224) {\n\t\t\tif ((il - i) >= 9) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tconst c3 = parseInt(str.substr(i + 7, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 9);\n\t\t\t}\n\t\t\ti += 9;\n\t\t}\n\t\telse {\n\t\t\tnewStr += str.substr(i, 3);\n\t\t\ti += 3;\n\t\t}\n\t}\n\n\treturn newStr;\n}\n\nfunction _normalizeComponentEncoding(components:URIComponents, protocol:URIRegExps) {\n\tfunction decodeUnreserved(str:string):string {\n\t\tconst decStr = pctDecChars(str);\n\t\treturn (!decStr.match(protocol.UNRESERVED) ? str : decStr);\n\t}\n\n\tif (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, \"\");\n\tif (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace((components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME), pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\n\treturn components;\n};\n\nfunction _stripLeadingZeros(str:string):string {\n\treturn str.replace(/^0*(.*)/, \"$1\") || \"0\";\n}\n\nfunction _normalizeIPv4(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV4ADDRESS) || [];\n\tconst [, address] = matches;\n\t\n\tif (address) {\n\t\treturn address.split(\".\").map(_stripLeadingZeros).join(\".\");\n\t} else {\n\t\treturn host;\n\t}\n}\n\nfunction _normalizeIPv6(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV6ADDRESS) || [];\n\tconst [, address, zone] = matches;\n\n\tif (address) {\n\t\tconst [last, first] = address.toLowerCase().split('::').reverse();\n\t\tconst firstFields = first ? first.split(\":\").map(_stripLeadingZeros) : [];\n\t\tconst lastFields = last.split(\":\").map(_stripLeadingZeros);\n\t\tconst isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);\n\t\tconst fieldCount = isLastFieldIPv4Address ? 7 : 8;\n\t\tconst lastFieldsStart = lastFields.length - fieldCount;\n\t\tconst fields = Array(fieldCount);\n\n\t\tfor (let x = 0; x < fieldCount; ++x) {\n\t\t\tfields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';\n\t\t}\n\n\t\tif (isLastFieldIPv4Address) {\n\t\t\tfields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);\n\t\t}\n\n\t\tconst allZeroFields = fields.reduce>((acc, field, index) => {\n\t\t\tif (!field || field === \"0\") {\n\t\t\t\tconst lastLongest = acc[acc.length - 1];\n\t\t\t\tif (lastLongest && lastLongest.index + lastLongest.length === index) {\n\t\t\t\t\tlastLongest.length++;\n\t\t\t\t} else {\n\t\t\t\t\tacc.push({ index, length : 1 });\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, []);\n\n\t\tconst longestZeroFields = allZeroFields.sort((a, b) => b.length - a.length)[0];\n\n\t\tlet newHost:string;\n\t\tif (longestZeroFields && longestZeroFields.length > 1) {\n\t\t\tconst newFirst = fields.slice(0, longestZeroFields.index) ;\n\t\t\tconst newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);\n\t\t\tnewHost = newFirst.join(\":\") + \"::\" + newLast.join(\":\");\n\t\t} else {\n\t\t\tnewHost = fields.join(\":\");\n\t\t}\n\n\t\tif (zone) {\n\t\t\tnewHost += \"%\" + zone;\n\t\t}\n\n\t\treturn newHost;\n\t} else {\n\t\treturn host;\n\t}\n}\n\nconst URI_PARSE = /^(?:([^:\\/?#]+):)?(?:\\/\\/((?:([^\\/?#@]*)@)?(\\[[^\\/?#\\]]+\\]|[^\\/?#:]*)(?:\\:(\\d*))?))?([^?#]*)(?:\\?([^#]*))?(?:#((?:.|\\n|\\r)*))?/i;\nconst NO_MATCH_IS_UNDEFINED = ((\"\").match(/(){0}/))[1] === undefined;\n\nexport function parse(uriString:string, options:URIOptions = {}):URIComponents {\n\tconst components:URIComponents = {};\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\n\tif (options.reference === \"suffix\") uriString = (options.scheme ? options.scheme + \":\" : \"\") + \"//\" + uriString;\n\n\tconst matches = uriString.match(URI_PARSE);\n\n\tif (matches) {\n\t\tif (NO_MATCH_IS_UNDEFINED) {\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1];\n\t\t\tcomponents.userinfo = matches[3];\n\t\t\tcomponents.host = matches[4];\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = matches[7];\n\t\t\tcomponents.fragment = matches[8];\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = matches[5];\n\t\t\t}\n\t\t} else { //IE FIX for improper RegExp matching\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1] || undefined;\n\t\t\tcomponents.userinfo = (uriString.indexOf(\"@\") !== -1 ? matches[3] : undefined);\n\t\t\tcomponents.host = (uriString.indexOf(\"//\") !== -1 ? matches[4] : undefined);\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = (uriString.indexOf(\"?\") !== -1 ? matches[7] : undefined);\n\t\t\tcomponents.fragment = (uriString.indexOf(\"#\") !== -1 ? matches[8] : undefined);\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = (uriString.match(/\\/\\/(?:.|\\n)*\\:(?:\\/|\\?|\\#|$)/) ? matches[4] : undefined);\n\t\t\t}\n\t\t}\n\n\t\tif (components.host) {\n\t\t\t//normalize IP hosts\n\t\t\tcomponents.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);\n\t\t}\n\n\t\t//determine reference type\n\t\tif (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {\n\t\t\tcomponents.reference = \"same-document\";\n\t\t} else if (components.scheme === undefined) {\n\t\t\tcomponents.reference = \"relative\";\n\t\t} else if (components.fragment === undefined) {\n\t\t\tcomponents.reference = \"absolute\";\n\t\t} else {\n\t\t\tcomponents.reference = \"uri\";\n\t\t}\n\n\t\t//check for reference errors\n\t\tif (options.reference && options.reference !== \"suffix\" && options.reference !== components.reference) {\n\t\t\tcomponents.error = components.error || \"URI is not a \" + options.reference + \" reference.\";\n\t\t}\n\n\t\t//find scheme handler\n\t\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t\t//check if scheme can't handle IRIs\n\t\tif (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n\t\t\t//if host component is a domain name\n\t\t\tif (components.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost))) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\tcomponents.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//convert IRI -> URI\n\t\t\t_normalizeComponentEncoding(components, URI_PROTOCOL);\n\t\t} else {\n\t\t\t//normalize encodings\n\t\t\t_normalizeComponentEncoding(components, protocol);\n\t\t}\n\n\t\t//perform scheme specific parsing\n\t\tif (schemeHandler && schemeHandler.parse) {\n\t\t\tschemeHandler.parse(components, options);\n\t\t}\n\t} else {\n\t\tcomponents.error = components.error || \"URI can not be parsed.\";\n\t}\n\n\treturn components;\n};\n\nfunction _recomposeAuthority(components:URIComponents, options:URIOptions):string|undefined {\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array = [];\n\n\tif (components.userinfo !== undefined) {\n\t\turiTokens.push(components.userinfo);\n\t\turiTokens.push(\"@\");\n\t}\n\n\tif (components.host !== undefined) {\n\t\t//normalize IP hosts, add brackets and escape zone separator for IPv6\n\t\turiTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, (_, $1, $2) => \"[\" + $1 + ($2 ? \"%25\" + $2 : \"\") + \"]\"));\n\t}\n\n\tif (typeof components.port === \"number\" || typeof components.port === \"string\") {\n\t\turiTokens.push(\":\");\n\t\turiTokens.push(String(components.port));\n\t}\n\n\treturn uriTokens.length ? uriTokens.join(\"\") : undefined;\n};\n\nconst RDS1 = /^\\.\\.?\\//;\nconst RDS2 = /^\\/\\.(\\/|$)/;\nconst RDS3 = /^\\/\\.\\.(\\/|$)/;\nconst RDS4 = /^\\.\\.?$/;\nconst RDS5 = /^\\/?(?:.|\\n)*?(?=\\/|$)/;\n\nexport function removeDotSegments(input:string):string {\n\tconst output:Array = [];\n\n\twhile (input.length) {\n\t\tif (input.match(RDS1)) {\n\t\t\tinput = input.replace(RDS1, \"\");\n\t\t} else if (input.match(RDS2)) {\n\t\t\tinput = input.replace(RDS2, \"/\");\n\t\t} else if (input.match(RDS3)) {\n\t\t\tinput = input.replace(RDS3, \"/\");\n\t\t\toutput.pop();\n\t\t} else if (input === \".\" || input === \"..\") {\n\t\t\tinput = \"\";\n\t\t} else {\n\t\t\tconst im = input.match(RDS5);\n\t\t\tif (im) {\n\t\t\t\tconst s = im[0];\n\t\t\t\tinput = input.slice(s.length);\n\t\t\t\toutput.push(s);\n\t\t\t} else {\n\t\t\t\tthrow new Error(\"Unexpected dot segment condition\");\n\t\t\t}\n\t\t}\n\t}\n\n\treturn output.join(\"\");\n};\n\nexport function serialize(components:URIComponents, options:URIOptions = {}):string {\n\tconst protocol = (options.iri ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array = [];\n\n\t//find scheme handler\n\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t//perform scheme specific serialization\n\tif (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);\n\n\tif (components.host) {\n\t\t//if host component is an IPv6 address\n\t\tif (protocol.IPV6ADDRESS.test(components.host)) {\n\t\t\t//TODO: normalize IPv6 address as per RFC 5952\n\t\t}\n\n\t\t//if host component is a domain name\n\t\telse if (options.domainHost || (schemeHandler && schemeHandler.domainHost)) {\n\t\t\t//convert IDN via punycode\n\t\t\ttry {\n\t\t\t\tcomponents.host = (!options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host));\n\t\t\t} catch (e) {\n\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t}\n\t\t}\n\t}\n\n\t//normalize encoding\n\t_normalizeComponentEncoding(components, protocol);\n\n\tif (options.reference !== \"suffix\" && components.scheme) {\n\t\turiTokens.push(components.scheme);\n\t\turiTokens.push(\":\");\n\t}\n\n\tconst authority = _recomposeAuthority(components, options);\n\tif (authority !== undefined) {\n\t\tif (options.reference !== \"suffix\") {\n\t\t\turiTokens.push(\"//\");\n\t\t}\n\n\t\turiTokens.push(authority);\n\n\t\tif (components.path && components.path.charAt(0) !== \"/\") {\n\t\t\turiTokens.push(\"/\");\n\t\t}\n\t}\n\n\tif (components.path !== undefined) {\n\t\tlet s = components.path;\n\n\t\tif (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n\t\t\ts = removeDotSegments(s);\n\t\t}\n\n\t\tif (authority === undefined) {\n\t\t\ts = s.replace(/^\\/\\//, \"/%2F\"); //don't allow the path to start with \"//\"\n\t\t}\n\n\t\turiTokens.push(s);\n\t}\n\n\tif (components.query !== undefined) {\n\t\turiTokens.push(\"?\");\n\t\turiTokens.push(components.query);\n\t}\n\n\tif (components.fragment !== undefined) {\n\t\turiTokens.push(\"#\");\n\t\turiTokens.push(components.fragment);\n\t}\n\n\treturn uriTokens.join(\"\"); //merge tokens into a string\n};\n\nexport function resolveComponents(base:URIComponents, relative:URIComponents, options:URIOptions = {}, skipNormalization?:boolean):URIComponents {\n\tconst target:URIComponents = {};\n\n\tif (!skipNormalization) {\n\t\tbase = parse(serialize(base, options), options); //normalize base components\n\t\trelative = parse(serialize(relative, options), options); //normalize relative components\n\t}\n\toptions = options || {};\n\n\tif (!options.tolerant && relative.scheme) {\n\t\ttarget.scheme = relative.scheme;\n\t\t//target.authority = relative.authority;\n\t\ttarget.userinfo = relative.userinfo;\n\t\ttarget.host = relative.host;\n\t\ttarget.port = relative.port;\n\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\ttarget.query = relative.query;\n\t} else {\n\t\tif (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n\t\t\t//target.authority = relative.authority;\n\t\t\ttarget.userinfo = relative.userinfo;\n\t\t\ttarget.host = relative.host;\n\t\t\ttarget.port = relative.port;\n\t\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\t\ttarget.query = relative.query;\n\t\t} else {\n\t\t\tif (!relative.path) {\n\t\t\t\ttarget.path = base.path;\n\t\t\t\tif (relative.query !== undefined) {\n\t\t\t\t\ttarget.query = relative.query;\n\t\t\t\t} else {\n\t\t\t\t\ttarget.query = base.query;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (relative.path.charAt(0) === \"/\") {\n\t\t\t\t\ttarget.path = removeDotSegments(relative.path);\n\t\t\t\t} else {\n\t\t\t\t\tif ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n\t\t\t\t\t\ttarget.path = \"/\" + relative.path;\n\t\t\t\t\t} else if (!base.path) {\n\t\t\t\t\t\ttarget.path = relative.path;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget.path = base.path.slice(0, base.path.lastIndexOf(\"/\") + 1) + relative.path;\n\t\t\t\t\t}\n\t\t\t\t\ttarget.path = removeDotSegments(target.path);\n\t\t\t\t}\n\t\t\t\ttarget.query = relative.query;\n\t\t\t}\n\t\t\t//target.authority = base.authority;\n\t\t\ttarget.userinfo = base.userinfo;\n\t\t\ttarget.host = base.host;\n\t\t\ttarget.port = base.port;\n\t\t}\n\t\ttarget.scheme = base.scheme;\n\t}\n\n\ttarget.fragment = relative.fragment;\n\n\treturn target;\n};\n\nexport function resolve(baseURI:string, relativeURI:string, options?:URIOptions):string {\n\tconst schemelessOptions = assign({ scheme : 'null' }, options);\n\treturn serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);\n};\n\nexport function normalize(uri:string, options?:URIOptions):string;\nexport function normalize(uri:URIComponents, options?:URIOptions):URIComponents;\nexport function normalize(uri:any, options?:URIOptions):any {\n\tif (typeof uri === \"string\") {\n\t\turi = serialize(parse(uri, options), options);\n\t} else if (typeOf(uri) === \"object\") {\n\t\turi = parse(serialize(uri, options), options);\n\t}\n\n\treturn uri;\n};\n\nexport function equal(uriA:string, uriB:string, options?: URIOptions):boolean;\nexport function equal(uriA:URIComponents, uriB:URIComponents, options?:URIOptions):boolean;\nexport function equal(uriA:any, uriB:any, options?:URIOptions):boolean {\n\tif (typeof uriA === \"string\") {\n\t\turiA = serialize(parse(uriA, options), options);\n\t} else if (typeOf(uriA) === \"object\") {\n\t\turiA = serialize(uriA, options);\n\t}\n\n\tif (typeof uriB === \"string\") {\n\t\turiB = serialize(parse(uriB, options), options);\n\t} else if (typeOf(uriB) === \"object\") {\n\t\turiB = serialize(uriB, options);\n\t}\n\n\treturn uriA === uriB;\n};\n\nexport function escapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE), pctEncChar);\n};\n\nexport function unescapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED), pctDecChars);\n};\n","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nexport interface WSComponents extends URIComponents {\n\tresourceName?: string;\n\tsecure?: boolean;\n}\n\nfunction isSecure(wsComponents:WSComponents):boolean {\n\treturn typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === \"wss\";\n}\n\n//RFC 6455\nconst handler:URISchemeHandler = {\n\tscheme : \"ws\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):WSComponents {\n\t\tconst wsComponents = components as WSComponents;\n\n\t\t//indicate if the secure flag is set\n\t\twsComponents.secure = isSecure(wsComponents);\n\n\t\t//construct resouce name\n\t\twsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '');\n\t\twsComponents.path = undefined;\n\t\twsComponents.query = undefined;\n\n\t\treturn wsComponents;\n\t},\n\n\tserialize : function (wsComponents:WSComponents, options:URIOptions):URIComponents {\n\t\t//normalize the default port\n\t\tif (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === \"\") {\n\t\t\twsComponents.port = undefined;\n\t\t}\n\n\t\t//ensure scheme matches secure flag\n\t\tif (typeof wsComponents.secure === 'boolean') {\n\t\t\twsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws');\n\t\t\twsComponents.secure = undefined;\n\t\t}\n\n\t\t//reconstruct path from resource name\n\t\tif (wsComponents.resourceName) {\n\t\t\tconst [path, query] = wsComponents.resourceName.split('?');\n\t\t\twsComponents.path = (path && path !== '/' ? path : undefined);\n\t\t\twsComponents.query = query;\n\t\t\twsComponents.resourceName = undefined;\n\t\t}\n\n\t\t//forbid fragment component\n\t\twsComponents.fragment = undefined;\n\n\t\treturn wsComponents;\n\t}\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, pctDecChars, unescapeComponent } from \"../uri\";\nimport punycode from \"punycode\";\nimport { merge, subexp, toUpperCase, toArray } from \"../util\";\n\nexport interface MailtoHeaders {\n\t[hfname:string]:string\n}\n\nexport interface MailtoComponents extends URIComponents {\n\tto:Array,\n\theaders?:MailtoHeaders,\n\tsubject?:string,\n\tbody?:string\n}\n\nconst O:MailtoHeaders = {};\nconst isIRI = true;\n\n//RFC 3986\nconst UNRESERVED$$ = \"[A-Za-z0-9\\\\-\\\\.\\\\_\\\\~\" + (isIRI ? \"\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF\" : \"\") + \"]\";\nconst HEXDIG$$ = \"[0-9A-Fa-f]\"; //case-insensitive\nconst PCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)); //expanded\n\n//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =\n//const ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\#\\\\$\\\\%\\\\&\\\\'\\\\*\\\\+\\\\-\\\\/\\\\=\\\\?\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QTEXT$$ = \"[\\\\x01-\\\\x08\\\\x0B\\\\x0C\\\\x0E-\\\\x1F\\\\x7F]\"; //(%d1-8 / %d11-12 / %d14-31 / %d127)\n//const QTEXT$$ = merge(\"[\\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E]\", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext\n//const VCHAR$$ = \"[\\\\x21-\\\\x7E]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QP$ = subexp(\"\\\\\\\\\" + merge(\"[\\\\x00\\\\x0D\\\\x0A]\", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext\n//const FWS$ = subexp(subexp(WSP$$ + \"*\" + \"\\\\x0D\\\\x0A\") + \"?\" + WSP$$ + \"+\");\n//const QUOTED_PAIR$ = subexp(subexp(\"\\\\\\\\\" + subexp(VCHAR$$ + \"|\" + WSP$$)) + \"|\" + OBS_QP$);\n//const QUOTED_STRING$ = subexp('\\\\\"' + subexp(FWS$ + \"?\" + QCONTENT$) + \"*\" + FWS$ + \"?\" + '\\\\\"');\nconst ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\$\\\\%\\\\'\\\\*\\\\+\\\\-\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\nconst QTEXT$$ = \"[\\\\!\\\\$\\\\%\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\-\\\\.0-9\\\\<\\\\>A-Z\\\\x5E-\\\\x7E]\";\nconst VCHAR$$ = merge(QTEXT$$, \"[\\\\\\\"\\\\\\\\]\");\nconst DOT_ATOM_TEXT$ = subexp(ATEXT$$ + \"+\" + subexp(\"\\\\.\" + ATEXT$$ + \"+\") + \"*\");\nconst QUOTED_PAIR$ = subexp(\"\\\\\\\\\" + VCHAR$$);\nconst QCONTENT$ = subexp(QTEXT$$ + \"|\" + QUOTED_PAIR$);\nconst QUOTED_STRING$ = subexp('\\\\\"' + QCONTENT$ + \"*\" + '\\\\\"');\n\n//RFC 6068\nconst DTEXT_NO_OBS$$ = \"[\\\\x21-\\\\x5A\\\\x5E-\\\\x7E]\"; //%d33-90 / %d94-126\nconst SOME_DELIMS$$ = \"[\\\\!\\\\$\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\:\\\\@]\";\nconst QCHAR$ = subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$ + \"|\" + SOME_DELIMS$$);\nconst DOMAIN$ = subexp(DOT_ATOM_TEXT$ + \"|\" + \"\\\\[\" + DTEXT_NO_OBS$$ + \"*\" + \"\\\\]\");\nconst LOCAL_PART$ = subexp(DOT_ATOM_TEXT$ + \"|\" + QUOTED_STRING$);\nconst ADDR_SPEC$ = subexp(LOCAL_PART$ + \"\\\\@\" + DOMAIN$);\nconst TO$ = subexp(ADDR_SPEC$ + subexp(\"\\\\,\" + ADDR_SPEC$) + \"*\");\nconst HFNAME$ = subexp(QCHAR$ + \"*\");\nconst HFVALUE$ = HFNAME$;\nconst HFIELD$ = subexp(HFNAME$ + \"\\\\=\" + HFVALUE$);\nconst HFIELDS2$ = subexp(HFIELD$ + subexp(\"\\\\&\" + HFIELD$) + \"*\");\nconst HFIELDS$ = subexp(\"\\\\?\" + HFIELDS2$);\nconst MAILTO_URI = new RegExp(\"^mailto\\\\:\" + TO$ + \"?\" + HFIELDS$ + \"?$\");\n\nconst UNRESERVED = new RegExp(UNRESERVED$$, \"g\");\nconst PCT_ENCODED = new RegExp(PCT_ENCODED$, \"g\");\nconst NOT_LOCAL_PART = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", '[\\\\\"]', VCHAR$$), \"g\");\nconst NOT_DOMAIN = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", \"[\\\\[]\", DTEXT_NO_OBS$$, \"[\\\\]]\"), \"g\");\nconst NOT_HFNAME = new RegExp(merge(\"[^]\", UNRESERVED$$, SOME_DELIMS$$), \"g\");\nconst NOT_HFVALUE = NOT_HFNAME;\nconst TO = new RegExp(\"^\" + TO$ + \"$\");\nconst HFIELDS = new RegExp(\"^\" + HFIELDS2$ + \"$\");\n\nfunction decodeUnreserved(str:string):string {\n\tconst decStr = pctDecChars(str);\n\treturn (!decStr.match(UNRESERVED) ? str : decStr);\n}\n\nconst handler:URISchemeHandler = {\n\tscheme : \"mailto\",\n\n\tparse : function (components:URIComponents, options:URIOptions):MailtoComponents {\n\t\tconst mailtoComponents = components as MailtoComponents;\n\t\tconst to = mailtoComponents.to = (mailtoComponents.path ? mailtoComponents.path.split(\",\") : []);\n\t\tmailtoComponents.path = undefined;\n\n\t\tif (mailtoComponents.query) {\n\t\t\tlet unknownHeaders = false\n\t\t\tconst headers:MailtoHeaders = {};\n\t\t\tconst hfields = mailtoComponents.query.split(\"&\");\n\n\t\t\tfor (let x = 0, xl = hfields.length; x < xl; ++x) {\n\t\t\t\tconst hfield = hfields[x].split(\"=\");\n\n\t\t\t\tswitch (hfield[0]) {\n\t\t\t\t\tcase \"to\":\n\t\t\t\t\t\tconst toAddrs = hfield[1].split(\",\");\n\t\t\t\t\t\tfor (let x = 0, xl = toAddrs.length; x < xl; ++x) {\n\t\t\t\t\t\t\tto.push(toAddrs[x]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"subject\":\n\t\t\t\t\t\tmailtoComponents.subject = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"body\":\n\t\t\t\t\t\tmailtoComponents.body = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tunknownHeaders = true;\n\t\t\t\t\t\theaders[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (unknownHeaders) mailtoComponents.headers = headers;\n\t\t}\n\n\t\tmailtoComponents.query = undefined;\n\n\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\tconst addr = to[x].split(\"@\");\n\n\t\t\taddr[0] = unescapeComponent(addr[0]);\n\n\t\t\tif (!options.unicodeSupport) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\taddr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tmailtoComponents.error = mailtoComponents.error || \"Email address's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\taddr[1] = unescapeComponent(addr[1], options).toLowerCase();\n\t\t\t}\n\n\t\t\tto[x] = addr.join(\"@\");\n\t\t}\n\n\t\treturn mailtoComponents;\n\t},\n\n\tserialize : function (mailtoComponents:MailtoComponents, options:URIOptions):URIComponents {\n\t\tconst components = mailtoComponents as URIComponents;\n\t\tconst to = toArray(mailtoComponents.to);\n\t\tif (to) {\n\t\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\t\tconst toAddr = String(to[x]);\n\t\t\t\tconst atIdx = toAddr.lastIndexOf(\"@\");\n\t\t\t\tconst localPart = (toAddr.slice(0, atIdx)).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);\n\t\t\t\tlet domain = toAddr.slice(atIdx + 1);\n\n\t\t\t\t//convert IDN via punycode\n\t\t\t\ttry {\n\t\t\t\t\tdomain = (!options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain));\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Email address's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t\t}\n\n\t\t\t\tto[x] = localPart + \"@\" + domain;\n\t\t\t}\n\n\t\t\tcomponents.path = to.join(\",\");\n\t\t}\n\n\t\tconst headers = mailtoComponents.headers = mailtoComponents.headers || {};\n\n\t\tif (mailtoComponents.subject) headers[\"subject\"] = mailtoComponents.subject;\n\t\tif (mailtoComponents.body) headers[\"body\"] = mailtoComponents.body;\n\n\t\tconst fields = [];\n\t\tfor (const name in headers) {\n\t\t\tif (headers[name] !== O[name]) {\n\t\t\t\tfields.push(\n\t\t\t\t\tname.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) +\n\t\t\t\t\t\"=\" +\n\t\t\t\t\theaders[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (fields.length) {\n\t\t\tcomponents.query = fields.join(\"&\");\n\t\t}\n\n\t\treturn components;\n\t}\n}\n\nexport default handler;","import { URIRegExps } from \"./uri\";\nimport { buildExps } from \"./regexps-uri\";\n\nexport default buildExps(true);\n","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"http\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\t//report missing host\n\t\tif (!components.host) {\n\t\t\tcomponents.error = components.error || \"HTTP URIs must have a host.\";\n\t\t}\n\n\t\treturn components;\n\t},\n\n\tserialize : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\tconst secure = String(components.scheme).toLowerCase() === \"https\";\n\n\t\t//normalize the default port\n\t\tif (components.port === (secure ? 443 : 80) || components.port === \"\") {\n\t\t\tcomponents.port = undefined;\n\t\t}\n\t\t\n\t\t//normalize the empty path\n\t\tif (!components.path) {\n\t\t\tcomponents.path = \"/\";\n\t\t}\n\n\t\t//NOTE: We do not parse query strings for HTTP URIs\n\t\t//as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n\t\t//and not the HTTP spec.\n\n\t\treturn components;\n\t}\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport http from \"./http\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"https\",\n\tdomainHost : http.domainHost,\n\tparse : http.parse,\n\tserialize : http.serialize\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport ws from \"./ws\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"wss\",\n\tdomainHost : ws.domainHost,\n\tparse : ws.parse,\n\tserialize : ws.serialize\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, SCHEMES } from \"../uri\";\n\nexport interface URNComponents extends URIComponents {\n\tnid?:string;\n\tnss?:string;\n}\n\nexport interface URNOptions extends URIOptions {\n\tnid?:string;\n}\n\nconst NID$ = \"(?:[0-9A-Za-z][0-9A-Za-z\\\\-]{1,31})\";\nconst PCT_ENCODED$ = \"(?:\\\\%[0-9A-Fa-f]{2})\";\nconst TRANS$$ = \"[0-9A-Za-z\\\\(\\\\)\\\\+\\\\,\\\\-\\\\.\\\\:\\\\=\\\\@\\\\;\\\\$\\\\_\\\\!\\\\*\\\\'\\\\/\\\\?\\\\#]\";\nconst NSS$ = \"(?:(?:\" + PCT_ENCODED$ + \"|\" + TRANS$$ + \")+)\";\nconst URN_SCHEME = new RegExp(\"^urn\\\\:(\" + NID$ + \")$\");\nconst URN_PATH = new RegExp(\"^(\" + NID$ + \")\\\\:(\" + NSS$ + \")$\");\nconst URN_PARSE = /^([^\\:]+)\\:(.*)/;\nconst URN_EXCLUDED = /[\\x00-\\x20\\\\\\\"\\&\\<\\>\\[\\]\\^\\`\\{\\|\\}\\~\\x7F-\\xFF]/g;\n\n//RFC 2141\nconst handler:URISchemeHandler = {\n\tscheme : \"urn\",\n\n\tparse : function (components:URIComponents, options:URNOptions):URNComponents {\n\t\tconst matches = components.path && components.path.match(URN_PARSE);\n\t\tlet urnComponents = components as URNComponents;\n\n\t\tif (matches) {\n\t\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\t\tconst nid = matches[1].toLowerCase();\n\t\t\tconst nss = matches[2];\n\t\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\t\turnComponents.nid = nid;\n\t\t\turnComponents.nss = nss;\n\t\t\turnComponents.path = undefined;\n\n\t\t\tif (schemeHandler) {\n\t\t\t\turnComponents = schemeHandler.parse(urnComponents, options) as URNComponents;\n\t\t\t}\n\t\t} else {\n\t\t\turnComponents.error = urnComponents.error || \"URN can not be parsed.\";\n\t\t}\n\n\t\treturn urnComponents;\n\t},\n\n\tserialize : function (urnComponents:URNComponents, options:URNOptions):URIComponents {\n\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\tconst nid = urnComponents.nid;\n\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\tif (schemeHandler) {\n\t\t\turnComponents = schemeHandler.serialize(urnComponents, options) as URNComponents;\n\t\t}\n\n\t\tconst uriComponents = urnComponents as URIComponents;\n\t\tconst nss = urnComponents.nss;\n\t\turiComponents.path = `${nid || options.nid}:${nss}`;\n\n\t\treturn uriComponents;\n\t},\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { URNComponents } from \"./urn\";\nimport { SCHEMES } from \"../uri\";\n\nexport interface UUIDComponents extends URNComponents {\n\tuuid?: string;\n}\n\nconst UUID = /^[0-9A-Fa-f]{8}(?:\\-[0-9A-Fa-f]{4}){3}\\-[0-9A-Fa-f]{12}$/;\nconst UUID_PARSE = /^[0-9A-Fa-f\\-]{36}/;\n\n//RFC 4122\nconst handler:URISchemeHandler = {\n\tscheme : \"urn:uuid\",\n\n\tparse : function (urnComponents:URNComponents, options:URIOptions):UUIDComponents {\n\t\tconst uuidComponents = urnComponents as UUIDComponents;\n\t\tuuidComponents.uuid = uuidComponents.nss;\n\t\tuuidComponents.nss = undefined;\n\n\t\tif (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {\n\t\t\tuuidComponents.error = uuidComponents.error || \"UUID is not valid.\";\n\t\t}\n\n\t\treturn uuidComponents;\n\t},\n\n\tserialize : function (uuidComponents:UUIDComponents, options:URIOptions):URNComponents {\n\t\tconst urnComponents = uuidComponents as URNComponents;\n\t\t//normalize UUID\n\t\turnComponents.nss = (uuidComponents.uuid || \"\").toLowerCase();\n\t\treturn urnComponents;\n\t},\n};\n\nexport default handler;","import { SCHEMES } from \"./uri\";\n\nimport http from \"./schemes/http\";\nSCHEMES[http.scheme] = http;\n\nimport https from \"./schemes/https\";\nSCHEMES[https.scheme] = https;\n\nimport ws from \"./schemes/ws\";\nSCHEMES[ws.scheme] = ws;\n\nimport wss from \"./schemes/wss\";\nSCHEMES[wss.scheme] = wss;\n\nimport mailto from \"./schemes/mailto\";\nSCHEMES[mailto.scheme] = mailto;\n\nimport urn from \"./schemes/urn\";\nSCHEMES[urn.scheme] = urn;\n\nimport uuid from \"./schemes/urn-uuid\";\nSCHEMES[uuid.scheme] = uuid;\n\nexport * from \"./uri\";\n"]} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/index.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/index.d.ts new file mode 100644 index 0000000..f6be760 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/index.d.ts @@ -0,0 +1 @@ +export * from "./uri"; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/index.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/index.js new file mode 100644 index 0000000..e3531b5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/index.js @@ -0,0 +1,17 @@ +import { SCHEMES } from "./uri"; +import http from "./schemes/http"; +SCHEMES[http.scheme] = http; +import https from "./schemes/https"; +SCHEMES[https.scheme] = https; +import ws from "./schemes/ws"; +SCHEMES[ws.scheme] = ws; +import wss from "./schemes/wss"; +SCHEMES[wss.scheme] = wss; +import mailto from "./schemes/mailto"; +SCHEMES[mailto.scheme] = mailto; +import urn from "./schemes/urn"; +SCHEMES[urn.scheme] = urn; +import uuid from "./schemes/urn-uuid"; +SCHEMES[uuid.scheme] = uuid; +export * from "./uri"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/index.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/index.js.map new file mode 100644 index 0000000..0971f6e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAEhC,OAAO,IAAI,MAAM,gBAAgB,CAAC;AAClC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;AAE5B,OAAO,KAAK,MAAM,iBAAiB,CAAC;AACpC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC;AAE9B,OAAO,EAAE,MAAM,cAAc,CAAC;AAC9B,OAAO,CAAC,EAAE,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;AAExB,OAAO,GAAG,MAAM,eAAe,CAAC;AAChC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC;AAE1B,OAAO,MAAM,MAAM,kBAAkB,CAAC;AACtC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;AAEhC,OAAO,GAAG,MAAM,eAAe,CAAC;AAChC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC;AAE1B,OAAO,IAAI,MAAM,oBAAoB,CAAC;AACtC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;AAE5B,cAAc,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-iri.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-iri.d.ts new file mode 100644 index 0000000..c91cdac --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-iri.d.ts @@ -0,0 +1,3 @@ +import { URIRegExps } from "./uri"; +declare const _default: URIRegExps; +export default _default; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-iri.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-iri.js new file mode 100644 index 0000000..34e7de9 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-iri.js @@ -0,0 +1,3 @@ +import { buildExps } from "./regexps-uri"; +export default buildExps(true); +//# sourceMappingURL=regexps-iri.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-iri.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-iri.js.map new file mode 100644 index 0000000..2269c58 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-iri.js.map @@ -0,0 +1 @@ +{"version":3,"file":"regexps-iri.js","sourceRoot":"","sources":["../../src/regexps-iri.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1C,eAAe,SAAS,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-uri.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-uri.d.ts new file mode 100644 index 0000000..6096bda --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-uri.d.ts @@ -0,0 +1,4 @@ +import { URIRegExps } from "./uri"; +export declare function buildExps(isIRI: boolean): URIRegExps; +declare const _default: URIRegExps; +export default _default; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-uri.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-uri.js new file mode 100644 index 0000000..1cc659f --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-uri.js @@ -0,0 +1,42 @@ +import { merge, subexp } from "./util"; +export function buildExps(isIRI) { + const ALPHA$$ = "[A-Za-z]", CR$ = "[\\x0D]", DIGIT$$ = "[0-9]", DQUOTE$$ = "[\\x22]", HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), //case-insensitive + LF$$ = "[\\x0A]", SP$$ = "[\\x20]", PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), //expanded + GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", //subset, excludes bidi control characters + IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", //subset + UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), //relaxed parsing rules + IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), H16$ = subexp(HEXDIG$$ + "{1,4}"), LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), // 6( h16 ":" ) ls32 + IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), // "::" 5( h16 ":" ) ls32 + IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), //[ h16 ] "::" 4( h16 ":" ) ls32 + IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), //[ *4( h16 ":" ) h16 ] "::" ls32 + IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), //[ *5( h16 ":" ) h16 ] "::" h16 + IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), //[ *6( h16 ":" ) h16 ] "::" + IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), //RFC 6874 + IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), //RFC 6874 + IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), //RFC 6874, with relaxed parsing rules + IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), //RFC 6874 + REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), PORT$ = subexp(DIGIT$$ + "*"), AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), SEGMENT$ = subexp(PCHAR$ + "*"), SEGMENT_NZ$ = subexp(PCHAR$ + "+"), SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), //simplified + PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), //simplified + PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), //simplified + PATH_EMPTY$ = "(?!" + PCHAR$ + ")", PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; + return { + NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), + NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), + NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), + ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), + UNRESERVED: new RegExp(UNRESERVED$$, "g"), + OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), + PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), + IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), + IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules + }; +} +export default buildExps(false); +//# sourceMappingURL=regexps-uri.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-uri.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-uri.js.map new file mode 100644 index 0000000..cb028b8 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/regexps-uri.js.map @@ -0,0 +1 @@ +{"version":3,"file":"regexps-uri.js","sourceRoot":"","sources":["../../src/regexps-uri.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEvC,MAAM,oBAAoB,KAAa;IACtC,MACC,OAAO,GAAG,UAAU,EACpB,GAAG,GAAG,SAAS,EACf,OAAO,GAAG,OAAO,EACjB,QAAQ,GAAG,SAAS,EACpB,QAAQ,GAAG,KAAK,CAAC,OAAO,EAAE,UAAU,CAAC,EAAG,kBAAkB;IAC1D,IAAI,GAAG,SAAS,EAChB,IAAI,GAAG,SAAS,EAChB,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,GAAG,QAAQ,GAAG,GAAG,GAAG,QAAQ,GAAG,QAAQ,GAAG,GAAG,GAAG,QAAQ,GAAG,QAAQ,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,aAAa,GAAG,QAAQ,GAAG,GAAG,GAAG,QAAQ,GAAG,QAAQ,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,GAAG,GAAG,QAAQ,GAAG,QAAQ,CAAC,CAAC,EAAG,UAAU;IACvO,YAAY,GAAG,yBAAyB,EACxC,YAAY,GAAG,qCAAqC,EACpD,UAAU,GAAG,KAAK,CAAC,YAAY,EAAE,YAAY,CAAC,EAC9C,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,6EAA6E,CAAC,CAAC,CAAC,IAAI,EAAG,0CAA0C;IACrJ,UAAU,GAAG,KAAK,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,IAAI,EAAG,QAAQ;IAC1D,YAAY,GAAG,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,SAAS,CAAC,EACnE,OAAO,GAAG,MAAM,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,aAAa,CAAC,GAAG,GAAG,CAAC,EACxE,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,YAAY,GAAG,GAAG,GAAG,KAAK,CAAC,YAAY,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC,GAAG,GAAG,CAAC,EACjG,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,QAAQ,GAAG,OAAO,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,GAAG,GAAG,OAAO,GAAG,OAAO,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC,GAAG,GAAG,GAAG,OAAO,CAAC,EACnK,kBAAkB,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,QAAQ,GAAG,OAAO,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,GAAG,GAAG,OAAO,GAAG,OAAO,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,OAAO,GAAG,OAAO,CAAC,EAAG,uBAAuB;IAC3M,YAAY,GAAG,MAAM,CAAC,kBAAkB,GAAG,KAAK,GAAG,kBAAkB,GAAG,KAAK,GAAG,kBAAkB,GAAG,KAAK,GAAG,kBAAkB,CAAC,EAChI,IAAI,GAAG,MAAM,CAAC,QAAQ,GAAG,OAAO,CAAC,EACjC,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,GAAG,KAAK,GAAG,IAAI,CAAC,GAAG,GAAG,GAAG,YAAY,CAAC,EAChE,aAAa,GAAG,MAAM,CAA6D,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,EAAE,8CAA8C;IACxK,aAAa,GAAG,MAAM,CAAkD,QAAQ,GAAG,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,EAAE,8CAA8C;IACxK,aAAa,GAAG,MAAM,CAAC,MAAM,CAAkC,IAAI,CAAC,GAAG,SAAS,GAAG,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,EAAE,8CAA8C;IACxK,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,OAAO,GAAG,IAAI,CAAC,GAAG,SAAS,GAAG,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,EAAE,8CAA8C;IACxK,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,OAAO,GAAG,IAAI,CAAC,GAAG,SAAS,GAAG,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,EAAE,8CAA8C;IACxK,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,OAAO,GAAG,IAAI,CAAC,GAAG,SAAS,GAAU,IAAI,GAAG,KAAK,GAAY,KAAK,CAAC,EAAE,8CAA8C;IACxK,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,OAAO,GAAG,IAAI,CAAC,GAAG,SAAS,GAAkC,KAAK,CAAC,EAAE,8CAA8C;IACxK,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,OAAO,GAAG,IAAI,CAAC,GAAG,SAAS,GAAkC,IAAI,CAAE,EAAE,6CAA6C;IACvK,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,OAAO,GAAG,IAAI,CAAC,GAAG,SAAS,CAAwC,EAAE,4BAA4B;IACtJ,YAAY,GAAG,MAAM,CAAC,CAAC,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EACxK,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,YAAY,GAAG,GAAG,GAAG,YAAY,CAAC,GAAG,GAAG,CAAC,EAAG,UAAU;IAC9E,UAAU,GAAG,MAAM,CAAC,YAAY,GAAG,OAAO,GAAG,OAAO,CAAC,EAAG,UAAU;IAClE,kBAAkB,GAAG,MAAM,CAAC,YAAY,GAAG,MAAM,CAAC,cAAc,GAAG,QAAQ,GAAG,MAAM,CAAC,GAAG,OAAO,CAAC,EAAG,sCAAsC;IACzI,UAAU,GAAG,MAAM,CAAC,MAAM,GAAG,QAAQ,GAAG,MAAM,GAAG,KAAK,CAAC,YAAY,EAAE,YAAY,EAAE,OAAO,CAAC,GAAG,GAAG,CAAC,EAClG,WAAW,GAAG,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,kBAAkB,GAAG,GAAG,GAAG,YAAY,GAAG,GAAG,GAAG,UAAU,CAAC,GAAG,KAAK,CAAC,EAAG,UAAU;IACrH,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,YAAY,GAAG,GAAG,GAAG,KAAK,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC,GAAG,GAAG,CAAC,EACxF,KAAK,GAAG,MAAM,CAAC,WAAW,GAAG,GAAG,GAAG,YAAY,GAAG,KAAK,GAAG,SAAS,GAAG,GAAG,GAAG,GAAG,GAAG,SAAS,CAAC,EAC5F,KAAK,GAAG,MAAM,CAAC,OAAO,GAAG,GAAG,CAAC,EAC7B,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,GAAG,GAAG,CAAC,GAAG,GAAG,GAAG,KAAK,GAAG,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC,EACxF,MAAM,GAAG,MAAM,CAAC,YAAY,GAAG,GAAG,GAAG,KAAK,CAAC,YAAY,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC,EACnF,QAAQ,GAAG,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,EAC/B,WAAW,GAAG,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,EAClC,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC,YAAY,GAAG,GAAG,GAAG,KAAK,CAAC,YAAY,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC,GAAG,GAAG,CAAC,EACtG,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,GAAG,QAAQ,CAAC,GAAG,GAAG,CAAC,EACtD,cAAc,GAAG,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,WAAW,GAAG,aAAa,CAAC,GAAG,GAAG,CAAC,EAAG,YAAY;IACzF,cAAc,GAAG,MAAM,CAAC,cAAc,GAAG,aAAa,CAAC,EAAG,YAAY;IACtE,cAAc,GAAG,MAAM,CAAC,WAAW,GAAG,aAAa,CAAC,EAAG,YAAY;IACnE,WAAW,GAAG,KAAK,GAAG,MAAM,GAAG,GAAG,EAClC,KAAK,GAAG,MAAM,CAAC,aAAa,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,WAAW,CAAC,EACtH,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,GAAG,GAAG,KAAK,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,GAAG,GAAG,CAAC,EAC3E,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,WAAW,CAAC,GAAG,GAAG,CAAC,EACtD,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,GAAG,UAAU,GAAG,aAAa,CAAC,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,WAAW,CAAC,EACpI,IAAI,GAAG,MAAM,CAAC,OAAO,GAAG,KAAK,GAAG,UAAU,GAAG,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,KAAK,GAAG,SAAS,CAAC,GAAG,GAAG,CAAC,EAC5G,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,GAAG,UAAU,GAAG,aAAa,CAAC,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,WAAW,CAAC,EACxI,SAAS,GAAG,MAAM,CAAC,cAAc,GAAG,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,KAAK,GAAG,SAAS,CAAC,GAAG,GAAG,CAAC,EACnG,cAAc,GAAG,MAAM,CAAC,IAAI,GAAG,GAAG,GAAG,SAAS,CAAC,EAC/C,aAAa,GAAG,MAAM,CAAC,OAAO,GAAG,KAAK,GAAG,UAAU,GAAG,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,GAAG,GAAG,CAAC,EAEnF,YAAY,GAAG,IAAI,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,GAAG,MAAM,CAAC,GAAG,GAAG,SAAS,GAAG,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK,GAAG,GAAG,GAAG,MAAM,CAAC,MAAM,GAAG,KAAK,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,GAAG,aAAa,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,WAAW,GAAG,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,GAAG,GAAG,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,MAAM,GAAG,SAAS,GAAG,GAAG,CAAC,GAAG,IAAI,EAC7U,aAAa,GAAG,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,GAAG,MAAM,CAAC,GAAG,GAAG,SAAS,GAAG,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK,GAAG,GAAG,GAAG,MAAM,CAAC,MAAM,GAAG,KAAK,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,GAAG,aAAa,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,WAAW,GAAG,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,GAAG,GAAG,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,MAAM,GAAG,SAAS,GAAG,GAAG,CAAC,GAAG,IAAI,EAC/T,aAAa,GAAG,IAAI,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,GAAG,MAAM,CAAC,GAAG,GAAG,SAAS,GAAG,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK,GAAG,GAAG,GAAG,MAAM,CAAC,MAAM,GAAG,KAAK,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,GAAG,aAAa,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,cAAc,GAAG,GAAG,GAAG,WAAW,GAAG,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,GAAG,GAAG,CAAC,GAAG,IAAI,EACrS,YAAY,GAAG,GAAG,GAAG,MAAM,CAAC,MAAM,GAAG,SAAS,GAAG,GAAG,CAAC,GAAG,IAAI,EAC5D,cAAc,GAAG,GAAG,GAAG,MAAM,CAAC,GAAG,GAAG,SAAS,GAAG,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK,GAAG,GAAG,GAAG,MAAM,CAAC,MAAM,GAAG,KAAK,GAAG,GAAG,CAAC,GAAG,IAAI,CAChH;IAED,OAAO;QACN,UAAU,EAAG,IAAI,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,CAAC,EAAE,GAAG,CAAC;QAC3E,YAAY,EAAG,IAAI,MAAM,CAAC,KAAK,CAAC,WAAW,EAAE,YAAY,EAAE,YAAY,CAAC,EAAE,GAAG,CAAC;QAC9E,QAAQ,EAAG,IAAI,MAAM,CAAC,KAAK,CAAC,iBAAiB,EAAE,YAAY,EAAE,YAAY,CAAC,EAAE,GAAG,CAAC;QAChF,QAAQ,EAAG,IAAI,MAAM,CAAC,KAAK,CAAC,iBAAiB,EAAE,YAAY,EAAE,YAAY,CAAC,EAAE,GAAG,CAAC;QAChF,iBAAiB,EAAG,IAAI,MAAM,CAAC,KAAK,CAAC,cAAc,EAAE,YAAY,EAAE,YAAY,CAAC,EAAE,GAAG,CAAC;QACtF,SAAS,EAAG,IAAI,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,YAAY,EAAE,YAAY,EAAE,gBAAgB,EAAE,UAAU,CAAC,EAAE,GAAG,CAAC;QACtG,YAAY,EAAG,IAAI,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,YAAY,EAAE,YAAY,EAAE,gBAAgB,CAAC,EAAE,GAAG,CAAC;QAC7F,MAAM,EAAG,IAAI,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,YAAY,EAAE,YAAY,CAAC,EAAE,GAAG,CAAC;QAClE,UAAU,EAAG,IAAI,MAAM,CAAC,YAAY,EAAE,GAAG,CAAC;QAC1C,WAAW,EAAG,IAAI,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,YAAY,EAAE,UAAU,CAAC,EAAE,GAAG,CAAC;QACxE,WAAW,EAAG,IAAI,MAAM,CAAC,YAAY,EAAE,GAAG,CAAC;QAC3C,WAAW,EAAG,IAAI,MAAM,CAAC,IAAI,GAAG,YAAY,GAAG,IAAI,CAAC;QACpD,WAAW,EAAG,IAAI,MAAM,CAAC,QAAQ,GAAG,YAAY,GAAG,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,GAAG,QAAQ,GAAG,MAAM,CAAC,GAAG,GAAG,GAAG,OAAO,GAAG,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAE,sCAAsC;KACrL,CAAC;AACH,CAAC;AAED,eAAe,SAAS,CAAC,KAAK,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/http.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/http.d.ts new file mode 100644 index 0000000..fe5b2f3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/http.d.ts @@ -0,0 +1,3 @@ +import { URISchemeHandler } from "../uri"; +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/http.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/http.js new file mode 100644 index 0000000..6abf0fe --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/http.js @@ -0,0 +1,28 @@ +const handler = { + scheme: "http", + domainHost: true, + parse: function (components, options) { + //report missing host + if (!components.host) { + components.error = components.error || "HTTP URIs must have a host."; + } + return components; + }, + serialize: function (components, options) { + const secure = String(components.scheme).toLowerCase() === "https"; + //normalize the default port + if (components.port === (secure ? 443 : 80) || components.port === "") { + components.port = undefined; + } + //normalize the empty path + if (!components.path) { + components.path = "/"; + } + //NOTE: We do not parse query strings for HTTP URIs + //as WWW Form Url Encoded query strings are part of the HTML4+ spec, + //and not the HTTP spec. + return components; + } +}; +export default handler; +//# sourceMappingURL=http.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/http.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/http.js.map new file mode 100644 index 0000000..8211897 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/http.js.map @@ -0,0 +1 @@ +{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/schemes/http.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,GAAoB;IAChC,MAAM,EAAG,MAAM;IAEf,UAAU,EAAG,IAAI;IAEjB,KAAK,EAAG,UAAU,UAAwB,EAAE,OAAkB;QAC7D,qBAAqB;QACrB,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE;YACrB,UAAU,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,IAAI,6BAA6B,CAAC;SACrE;QAED,OAAO,UAAU,CAAC;IACnB,CAAC;IAED,SAAS,EAAG,UAAU,UAAwB,EAAE,OAAkB;QACjE,MAAM,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,KAAK,OAAO,CAAC;QAEnE,4BAA4B;QAC5B,IAAI,UAAU,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,UAAU,CAAC,IAAI,KAAK,EAAE,EAAE;YACtE,UAAU,CAAC,IAAI,GAAG,SAAS,CAAC;SAC5B;QAED,0BAA0B;QAC1B,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE;YACrB,UAAU,CAAC,IAAI,GAAG,GAAG,CAAC;SACtB;QAED,mDAAmD;QACnD,oEAAoE;QACpE,wBAAwB;QAExB,OAAO,UAAU,CAAC;IACnB,CAAC;CACD,CAAC;AAEF,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/https.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/https.d.ts new file mode 100644 index 0000000..fe5b2f3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/https.d.ts @@ -0,0 +1,3 @@ +import { URISchemeHandler } from "../uri"; +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/https.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/https.js new file mode 100644 index 0000000..ec4b6e7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/https.js @@ -0,0 +1,9 @@ +import http from "./http"; +const handler = { + scheme: "https", + domainHost: http.domainHost, + parse: http.parse, + serialize: http.serialize +}; +export default handler; +//# sourceMappingURL=https.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/https.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/https.js.map new file mode 100644 index 0000000..385b8ef --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/https.js.map @@ -0,0 +1 @@ +{"version":3,"file":"https.js","sourceRoot":"","sources":["../../../src/schemes/https.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,QAAQ,CAAC;AAE1B,MAAM,OAAO,GAAoB;IAChC,MAAM,EAAG,OAAO;IAChB,UAAU,EAAG,IAAI,CAAC,UAAU;IAC5B,KAAK,EAAG,IAAI,CAAC,KAAK;IAClB,SAAS,EAAG,IAAI,CAAC,SAAS;CAC1B,CAAA;AAED,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/mailto.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/mailto.d.ts new file mode 100644 index 0000000..e2aefc2 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/mailto.d.ts @@ -0,0 +1,12 @@ +import { URISchemeHandler, URIComponents } from "../uri"; +export interface MailtoHeaders { + [hfname: string]: string; +} +export interface MailtoComponents extends URIComponents { + to: Array; + headers?: MailtoHeaders; + subject?: string; + body?: string; +} +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/mailto.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/mailto.js new file mode 100644 index 0000000..2553713 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/mailto.js @@ -0,0 +1,148 @@ +import { pctEncChar, pctDecChars, unescapeComponent } from "../uri"; +import punycode from "punycode"; +import { merge, subexp, toUpperCase, toArray } from "../util"; +const O = {}; +const isIRI = true; +//RFC 3986 +const UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; +const HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive +const PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded +//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = +//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) +//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext +//const VCHAR$$ = "[\\x21-\\x7E]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext +//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); +//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); +//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); +const ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; +const QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; +const VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); +const DOT_ATOM_TEXT$ = subexp(ATEXT$$ + "+" + subexp("\\." + ATEXT$$ + "+") + "*"); +const QUOTED_PAIR$ = subexp("\\\\" + VCHAR$$); +const QCONTENT$ = subexp(QTEXT$$ + "|" + QUOTED_PAIR$); +const QUOTED_STRING$ = subexp('\\"' + QCONTENT$ + "*" + '\\"'); +//RFC 6068 +const DTEXT_NO_OBS$$ = "[\\x21-\\x5A\\x5E-\\x7E]"; //%d33-90 / %d94-126 +const SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; +const QCHAR$ = subexp(UNRESERVED$$ + "|" + PCT_ENCODED$ + "|" + SOME_DELIMS$$); +const DOMAIN$ = subexp(DOT_ATOM_TEXT$ + "|" + "\\[" + DTEXT_NO_OBS$$ + "*" + "\\]"); +const LOCAL_PART$ = subexp(DOT_ATOM_TEXT$ + "|" + QUOTED_STRING$); +const ADDR_SPEC$ = subexp(LOCAL_PART$ + "\\@" + DOMAIN$); +const TO$ = subexp(ADDR_SPEC$ + subexp("\\," + ADDR_SPEC$) + "*"); +const HFNAME$ = subexp(QCHAR$ + "*"); +const HFVALUE$ = HFNAME$; +const HFIELD$ = subexp(HFNAME$ + "\\=" + HFVALUE$); +const HFIELDS2$ = subexp(HFIELD$ + subexp("\\&" + HFIELD$) + "*"); +const HFIELDS$ = subexp("\\?" + HFIELDS2$); +const MAILTO_URI = new RegExp("^mailto\\:" + TO$ + "?" + HFIELDS$ + "?$"); +const UNRESERVED = new RegExp(UNRESERVED$$, "g"); +const PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); +const NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); +const NOT_DOMAIN = new RegExp(merge("[^]", ATEXT$$, "[\\.]", "[\\[]", DTEXT_NO_OBS$$, "[\\]]"), "g"); +const NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); +const NOT_HFVALUE = NOT_HFNAME; +const TO = new RegExp("^" + TO$ + "$"); +const HFIELDS = new RegExp("^" + HFIELDS2$ + "$"); +function decodeUnreserved(str) { + const decStr = pctDecChars(str); + return (!decStr.match(UNRESERVED) ? str : decStr); +} +const handler = { + scheme: "mailto", + parse: function (components, options) { + const mailtoComponents = components; + const to = mailtoComponents.to = (mailtoComponents.path ? mailtoComponents.path.split(",") : []); + mailtoComponents.path = undefined; + if (mailtoComponents.query) { + let unknownHeaders = false; + const headers = {}; + const hfields = mailtoComponents.query.split("&"); + for (let x = 0, xl = hfields.length; x < xl; ++x) { + const hfield = hfields[x].split("="); + switch (hfield[0]) { + case "to": + const toAddrs = hfield[1].split(","); + for (let x = 0, xl = toAddrs.length; x < xl; ++x) { + to.push(toAddrs[x]); + } + break; + case "subject": + mailtoComponents.subject = unescapeComponent(hfield[1], options); + break; + case "body": + mailtoComponents.body = unescapeComponent(hfield[1], options); + break; + default: + unknownHeaders = true; + headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); + break; + } + } + if (unknownHeaders) + mailtoComponents.headers = headers; + } + mailtoComponents.query = undefined; + for (let x = 0, xl = to.length; x < xl; ++x) { + const addr = to[x].split("@"); + addr[0] = unescapeComponent(addr[0]); + if (!options.unicodeSupport) { + //convert Unicode IDN -> ASCII IDN + try { + addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); + } + catch (e) { + mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; + } + } + else { + addr[1] = unescapeComponent(addr[1], options).toLowerCase(); + } + to[x] = addr.join("@"); + } + return mailtoComponents; + }, + serialize: function (mailtoComponents, options) { + const components = mailtoComponents; + const to = toArray(mailtoComponents.to); + if (to) { + for (let x = 0, xl = to.length; x < xl; ++x) { + const toAddr = String(to[x]); + const atIdx = toAddr.lastIndexOf("@"); + const localPart = (toAddr.slice(0, atIdx)).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); + let domain = toAddr.slice(atIdx + 1); + //convert IDN via punycode + try { + domain = (!options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain)); + } + catch (e) { + components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + to[x] = localPart + "@" + domain; + } + components.path = to.join(","); + } + const headers = mailtoComponents.headers = mailtoComponents.headers || {}; + if (mailtoComponents.subject) + headers["subject"] = mailtoComponents.subject; + if (mailtoComponents.body) + headers["body"] = mailtoComponents.body; + const fields = []; + for (const name in headers) { + if (headers[name] !== O[name]) { + fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + + "=" + + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); + } + } + if (fields.length) { + components.query = fields.join("&"); + } + return components; + } +}; +export default handler; +//# sourceMappingURL=mailto.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/mailto.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/mailto.js.map new file mode 100644 index 0000000..82dba9a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/mailto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mailto.js","sourceRoot":"","sources":["../../../src/schemes/mailto.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAC;AACpE,OAAO,QAAQ,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAa9D,MAAM,CAAC,GAAiB,EAAE,CAAC;AAC3B,MAAM,KAAK,GAAG,IAAI,CAAC;AAEnB,UAAU;AACV,MAAM,YAAY,GAAG,wBAAwB,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,2EAA2E,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC;AACjJ,MAAM,QAAQ,GAAG,aAAa,CAAC,CAAE,kBAAkB;AACnD,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,GAAG,QAAQ,GAAG,GAAG,GAAG,QAAQ,GAAG,QAAQ,GAAG,GAAG,GAAG,QAAQ,GAAG,QAAQ,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,aAAa,GAAG,QAAQ,GAAG,GAAG,GAAG,QAAQ,GAAG,QAAQ,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,GAAG,GAAG,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAE,UAAU;AAE7O,qEAAqE;AACrE,yFAAyF;AACzF,+BAA+B;AAC/B,uGAAuG;AACvG,+GAA+G;AAC/G,kCAAkC;AAClC,+BAA+B;AAC/B,wGAAwG;AACxG,8EAA8E;AAC9E,8FAA8F;AAC9F,mGAAmG;AACnG,MAAM,OAAO,GAAG,uDAAuD,CAAC;AACxE,MAAM,OAAO,GAAG,4DAA4D,CAAC;AAC7E,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;AAC7C,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,GAAG,GAAG,GAAG,MAAM,CAAC,KAAK,GAAG,OAAO,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC;AACnF,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,GAAG,OAAO,CAAC,CAAC;AAC9C,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,GAAG,GAAG,GAAG,YAAY,CAAC,CAAC;AACvD,MAAM,cAAc,GAAG,MAAM,CAAC,KAAK,GAAG,SAAS,GAAG,GAAG,GAAG,KAAK,CAAC,CAAC;AAE/D,UAAU;AACV,MAAM,cAAc,GAAG,0BAA0B,CAAC,CAAE,oBAAoB;AACxE,MAAM,aAAa,GAAG,qCAAqC,CAAC;AAC5D,MAAM,MAAM,GAAG,MAAM,CAAC,YAAY,GAAG,GAAG,GAAG,YAAY,GAAG,GAAG,GAAG,aAAa,CAAC,CAAC;AAC/E,MAAM,OAAO,GAAG,MAAM,CAAC,cAAc,GAAG,GAAG,GAAG,KAAK,GAAG,cAAc,GAAG,GAAG,GAAG,KAAK,CAAC,CAAC;AACpF,MAAM,WAAW,GAAG,MAAM,CAAC,cAAc,GAAG,GAAG,GAAG,cAAc,CAAC,CAAC;AAClE,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,GAAG,KAAK,GAAG,OAAO,CAAC,CAAC;AACzD,MAAM,GAAG,GAAG,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,KAAK,GAAG,UAAU,CAAC,GAAG,GAAG,CAAC,CAAC;AAClE,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC;AACrC,MAAM,QAAQ,GAAG,OAAO,CAAC;AACzB,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,GAAG,KAAK,GAAG,QAAQ,CAAC,CAAC;AACnD,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,GAAG,OAAO,CAAC,GAAG,GAAG,CAAC,CAAC;AAClE,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,GAAG,SAAS,CAAC,CAAC;AAC3C,MAAM,UAAU,GAAG,IAAI,MAAM,CAAC,YAAY,GAAG,GAAG,GAAG,GAAG,GAAG,QAAQ,GAAG,IAAI,CAAC,CAAC;AAE1E,MAAM,UAAU,GAAG,IAAI,MAAM,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;AACjD,MAAM,WAAW,GAAG,IAAI,MAAM,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;AAClD,MAAM,cAAc,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,CAAC;AACzF,MAAM,UAAU,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,CAAC;AACrG,MAAM,UAAU,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,YAAY,EAAE,aAAa,CAAC,EAAE,GAAG,CAAC,CAAC;AAC9E,MAAM,WAAW,GAAG,UAAU,CAAC;AAC/B,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;AACvC,MAAM,OAAO,GAAG,IAAI,MAAM,CAAC,GAAG,GAAG,SAAS,GAAG,GAAG,CAAC,CAAC;AAElD,0BAA0B,GAAU;IACnC,MAAM,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;IAChC,OAAO,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AACnD,CAAC;AAED,MAAM,OAAO,GAAuC;IACnD,MAAM,EAAG,QAAQ;IAEjB,KAAK,EAAG,UAAU,UAAwB,EAAE,OAAkB;QAC7D,MAAM,gBAAgB,GAAG,UAA8B,CAAC;QACxD,MAAM,EAAE,GAAG,gBAAgB,CAAC,EAAE,GAAG,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QACjG,gBAAgB,CAAC,IAAI,GAAG,SAAS,CAAC;QAElC,IAAI,gBAAgB,CAAC,KAAK,EAAE;YAC3B,IAAI,cAAc,GAAG,KAAK,CAAA;YAC1B,MAAM,OAAO,GAAiB,EAAE,CAAC;YACjC,MAAM,OAAO,GAAG,gBAAgB,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAElD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE;gBACjD,MAAM,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;gBAErC,QAAQ,MAAM,CAAC,CAAC,CAAC,EAAE;oBAClB,KAAK,IAAI;wBACR,MAAM,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;wBACrC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE;4BACjD,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;yBACpB;wBACD,MAAM;oBACP,KAAK,SAAS;wBACb,gBAAgB,CAAC,OAAO,GAAG,iBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;wBACjE,MAAM;oBACP,KAAK,MAAM;wBACV,gBAAgB,CAAC,IAAI,GAAG,iBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;wBAC9D,MAAM;oBACP;wBACC,cAAc,GAAG,IAAI,CAAC;wBACtB,OAAO,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,GAAG,iBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;wBACvF,MAAM;iBACP;aACD;YAED,IAAI,cAAc;gBAAE,gBAAgB,CAAC,OAAO,GAAG,OAAO,CAAC;SACvD;QAED,gBAAgB,CAAC,KAAK,GAAG,SAAS,CAAC;QAEnC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE;YAC5C,MAAM,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAE9B,IAAI,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;YAErC,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE;gBAC5B,kCAAkC;gBAClC,IAAI;oBACH,IAAI,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;iBAC9E;gBAAC,OAAO,CAAC,EAAE;oBACX,gBAAgB,CAAC,KAAK,GAAG,gBAAgB,CAAC,KAAK,IAAI,0EAA0E,GAAG,CAAC,CAAC;iBAClI;aACD;iBAAM;gBACN,IAAI,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC;aAC5D;YAED,EAAE,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SACvB;QAED,OAAO,gBAAgB,CAAC;IACzB,CAAC;IAED,SAAS,EAAG,UAAU,gBAAiC,EAAE,OAAkB;QAC1E,MAAM,UAAU,GAAG,gBAAiC,CAAC;QACrD,MAAM,EAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC,EAAE,CAAC,CAAC;QACxC,IAAI,EAAE,EAAE;YACP,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE;gBAC5C,MAAM,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC7B,MAAM,KAAK,GAAG,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;gBACtC,MAAM,SAAS,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,UAAU,CAAC,CAAC;gBACxJ,IAAI,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;gBAErC,0BAA0B;gBAC1B,IAAI;oBACH,MAAM,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,iBAAiB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;iBAC1H;gBAAC,OAAO,CAAC,EAAE;oBACX,UAAU,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,IAAI,sDAAsD,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,iBAAiB,GAAG,CAAC,CAAC;iBAC7J;gBAED,EAAE,CAAC,CAAC,CAAC,GAAG,SAAS,GAAG,GAAG,GAAG,MAAM,CAAC;aACjC;YAED,UAAU,CAAC,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SAC/B;QAED,MAAM,OAAO,GAAG,gBAAgB,CAAC,OAAO,GAAG,gBAAgB,CAAC,OAAO,IAAI,EAAE,CAAC;QAE1E,IAAI,gBAAgB,CAAC,OAAO;YAAE,OAAO,CAAC,SAAS,CAAC,GAAG,gBAAgB,CAAC,OAAO,CAAC;QAC5E,IAAI,gBAAgB,CAAC,IAAI;YAAE,OAAO,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC,IAAI,CAAC;QAEnE,MAAM,MAAM,GAAG,EAAE,CAAC;QAClB,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE;YAC3B,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,EAAE;gBAC9B,MAAM,CAAC,IAAI,CACV,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC;oBAC7G,GAAG;oBACH,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,UAAU,CAAC,CACvH,CAAC;aACF;SACD;QACD,IAAI,MAAM,CAAC,MAAM,EAAE;YAClB,UAAU,CAAC,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SACpC;QAED,OAAO,UAAU,CAAC;IACnB,CAAC;CACD,CAAA;AAED,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn-uuid.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn-uuid.d.ts new file mode 100644 index 0000000..e75f2e7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn-uuid.d.ts @@ -0,0 +1,7 @@ +import { URISchemeHandler, URIOptions } from "../uri"; +import { URNComponents } from "./urn"; +export interface UUIDComponents extends URNComponents { + uuid?: string; +} +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js new file mode 100644 index 0000000..d1fce49 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js @@ -0,0 +1,23 @@ +const UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; +const UUID_PARSE = /^[0-9A-Fa-f\-]{36}/; +//RFC 4122 +const handler = { + scheme: "urn:uuid", + parse: function (urnComponents, options) { + const uuidComponents = urnComponents; + uuidComponents.uuid = uuidComponents.nss; + uuidComponents.nss = undefined; + if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { + uuidComponents.error = uuidComponents.error || "UUID is not valid."; + } + return uuidComponents; + }, + serialize: function (uuidComponents, options) { + const urnComponents = uuidComponents; + //normalize UUID + urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); + return urnComponents; + }, +}; +export default handler; +//# sourceMappingURL=urn-uuid.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js.map new file mode 100644 index 0000000..3b7a8b3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"urn-uuid.js","sourceRoot":"","sources":["../../../src/schemes/urn-uuid.ts"],"names":[],"mappings":"AAQA,MAAM,IAAI,GAAG,0DAA0D,CAAC;AACxE,MAAM,UAAU,GAAG,oBAAoB,CAAC;AAExC,UAAU;AACV,MAAM,OAAO,GAA+D;IAC3E,MAAM,EAAG,UAAU;IAEnB,KAAK,EAAG,UAAU,aAA2B,EAAE,OAAkB;QAChE,MAAM,cAAc,GAAG,aAA+B,CAAC;QACvD,cAAc,CAAC,IAAI,GAAG,cAAc,CAAC,GAAG,CAAC;QACzC,cAAc,CAAC,GAAG,GAAG,SAAS,CAAC;QAE/B,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI,CAAC,CAAC,cAAc,CAAC,IAAI,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE;YACpF,cAAc,CAAC,KAAK,GAAG,cAAc,CAAC,KAAK,IAAI,oBAAoB,CAAC;SACpE;QAED,OAAO,cAAc,CAAC;IACvB,CAAC;IAED,SAAS,EAAG,UAAU,cAA6B,EAAE,OAAkB;QACtE,MAAM,aAAa,GAAG,cAA+B,CAAC;QACtD,gBAAgB;QAChB,aAAa,CAAC,GAAG,GAAG,CAAC,cAAc,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QAC9D,OAAO,aAAa,CAAC;IACtB,CAAC;CACD,CAAC;AAEF,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn.d.ts new file mode 100644 index 0000000..7e0c2fb --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn.d.ts @@ -0,0 +1,10 @@ +import { URISchemeHandler, URIComponents, URIOptions } from "../uri"; +export interface URNComponents extends URIComponents { + nid?: string; + nss?: string; +} +export interface URNOptions extends URIOptions { + nid?: string; +} +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn.js new file mode 100644 index 0000000..5d3f10a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn.js @@ -0,0 +1,49 @@ +import { SCHEMES } from "../uri"; +const NID$ = "(?:[0-9A-Za-z][0-9A-Za-z\\-]{1,31})"; +const PCT_ENCODED$ = "(?:\\%[0-9A-Fa-f]{2})"; +const TRANS$$ = "[0-9A-Za-z\\(\\)\\+\\,\\-\\.\\:\\=\\@\\;\\$\\_\\!\\*\\'\\/\\?\\#]"; +const NSS$ = "(?:(?:" + PCT_ENCODED$ + "|" + TRANS$$ + ")+)"; +const URN_SCHEME = new RegExp("^urn\\:(" + NID$ + ")$"); +const URN_PATH = new RegExp("^(" + NID$ + ")\\:(" + NSS$ + ")$"); +const URN_PARSE = /^([^\:]+)\:(.*)/; +const URN_EXCLUDED = /[\x00-\x20\\\"\&\<\>\[\]\^\`\{\|\}\~\x7F-\xFF]/g; +//RFC 2141 +const handler = { + scheme: "urn", + parse: function (components, options) { + const matches = components.path && components.path.match(URN_PARSE); + let urnComponents = components; + if (matches) { + const scheme = options.scheme || urnComponents.scheme || "urn"; + const nid = matches[1].toLowerCase(); + const nss = matches[2]; + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = SCHEMES[urnScheme]; + urnComponents.nid = nid; + urnComponents.nss = nss; + urnComponents.path = undefined; + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options); + } + } + else { + urnComponents.error = urnComponents.error || "URN can not be parsed."; + } + return urnComponents; + }, + serialize: function (urnComponents, options) { + const scheme = options.scheme || urnComponents.scheme || "urn"; + const nid = urnComponents.nid; + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = SCHEMES[urnScheme]; + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options); + } + const uriComponents = urnComponents; + const nss = urnComponents.nss; + uriComponents.path = `${nid || options.nid}:${nss}`; + return uriComponents; + }, +}; +export default handler; +//# sourceMappingURL=urn.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn.js.map new file mode 100644 index 0000000..ea43b0b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/urn.js.map @@ -0,0 +1 @@ +{"version":3,"file":"urn.js","sourceRoot":"","sources":["../../../src/schemes/urn.ts"],"names":[],"mappings":"AACA,OAAO,EAAc,OAAO,EAAE,MAAM,QAAQ,CAAC;AAW7C,MAAM,IAAI,GAAG,qCAAqC,CAAC;AACnD,MAAM,YAAY,GAAG,uBAAuB,CAAC;AAC7C,MAAM,OAAO,GAAG,mEAAmE,CAAC;AACpF,MAAM,IAAI,GAAG,QAAQ,GAAG,YAAY,GAAG,GAAG,GAAG,OAAO,GAAG,KAAK,CAAC;AAC7D,MAAM,UAAU,GAAG,IAAI,MAAM,CAAC,UAAU,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC;AACxD,MAAM,QAAQ,GAAG,IAAI,MAAM,CAAC,IAAI,GAAG,IAAI,GAAG,OAAO,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC;AACjE,MAAM,SAAS,GAAG,iBAAiB,CAAC;AACpC,MAAM,YAAY,GAAG,iDAAiD,CAAC;AAEvE,UAAU;AACV,MAAM,OAAO,GAA8C;IAC1D,MAAM,EAAG,KAAK;IAEd,KAAK,EAAG,UAAU,UAAwB,EAAE,OAAkB;QAC7D,MAAM,OAAO,GAAG,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QACpE,IAAI,aAAa,GAAG,UAA2B,CAAC;QAEhD,IAAI,OAAO,EAAE;YACZ,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,aAAa,CAAC,MAAM,IAAI,KAAK,CAAC;YAC/D,MAAM,GAAG,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;YACrC,MAAM,GAAG,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YACvB,MAAM,SAAS,GAAG,GAAG,MAAM,IAAI,OAAO,CAAC,GAAG,IAAI,GAAG,EAAE,CAAC;YACpD,MAAM,aAAa,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;YAEzC,aAAa,CAAC,GAAG,GAAG,GAAG,CAAC;YACxB,aAAa,CAAC,GAAG,GAAG,GAAG,CAAC;YACxB,aAAa,CAAC,IAAI,GAAG,SAAS,CAAC;YAE/B,IAAI,aAAa,EAAE;gBAClB,aAAa,GAAG,aAAa,CAAC,KAAK,CAAC,aAAa,EAAE,OAAO,CAAkB,CAAC;aAC7E;SACD;aAAM;YACN,aAAa,CAAC,KAAK,GAAG,aAAa,CAAC,KAAK,IAAI,wBAAwB,CAAC;SACtE;QAED,OAAO,aAAa,CAAC;IACtB,CAAC;IAED,SAAS,EAAG,UAAU,aAA2B,EAAE,OAAkB;QACpE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,aAAa,CAAC,MAAM,IAAI,KAAK,CAAC;QAC/D,MAAM,GAAG,GAAG,aAAa,CAAC,GAAG,CAAC;QAC9B,MAAM,SAAS,GAAG,GAAG,MAAM,IAAI,OAAO,CAAC,GAAG,IAAI,GAAG,EAAE,CAAC;QACpD,MAAM,aAAa,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;QAEzC,IAAI,aAAa,EAAE;YAClB,aAAa,GAAG,aAAa,CAAC,SAAS,CAAC,aAAa,EAAE,OAAO,CAAkB,CAAC;SACjF;QAED,MAAM,aAAa,GAAG,aAA8B,CAAC;QACrD,MAAM,GAAG,GAAG,aAAa,CAAC,GAAG,CAAC;QAC9B,aAAa,CAAC,IAAI,GAAG,GAAG,GAAG,IAAI,OAAO,CAAC,GAAG,IAAI,GAAG,EAAE,CAAC;QAEpD,OAAO,aAAa,CAAC;IACtB,CAAC;CACD,CAAC;AAEF,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/ws.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/ws.d.ts new file mode 100644 index 0000000..47f4835 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/ws.d.ts @@ -0,0 +1,7 @@ +import { URISchemeHandler, URIComponents } from "../uri"; +export interface WSComponents extends URIComponents { + resourceName?: string; + secure?: boolean; +} +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/ws.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/ws.js new file mode 100644 index 0000000..9277f03 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/ws.js @@ -0,0 +1,41 @@ +function isSecure(wsComponents) { + return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; +} +//RFC 6455 +const handler = { + scheme: "ws", + domainHost: true, + parse: function (components, options) { + const wsComponents = components; + //indicate if the secure flag is set + wsComponents.secure = isSecure(wsComponents); + //construct resouce name + wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); + wsComponents.path = undefined; + wsComponents.query = undefined; + return wsComponents; + }, + serialize: function (wsComponents, options) { + //normalize the default port + if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { + wsComponents.port = undefined; + } + //ensure scheme matches secure flag + if (typeof wsComponents.secure === 'boolean') { + wsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws'); + wsComponents.secure = undefined; + } + //reconstruct path from resource name + if (wsComponents.resourceName) { + const [path, query] = wsComponents.resourceName.split('?'); + wsComponents.path = (path && path !== '/' ? path : undefined); + wsComponents.query = query; + wsComponents.resourceName = undefined; + } + //forbid fragment component + wsComponents.fragment = undefined; + return wsComponents; + } +}; +export default handler; +//# sourceMappingURL=ws.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/ws.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/ws.js.map new file mode 100644 index 0000000..186818c --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/ws.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ws.js","sourceRoot":"","sources":["../../../src/schemes/ws.ts"],"names":[],"mappings":"AAOA,kBAAkB,YAAyB;IAC1C,OAAO,OAAO,YAAY,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,KAAK,KAAK,CAAC;AAC7H,CAAC;AAED,UAAU;AACV,MAAM,OAAO,GAAoB;IAChC,MAAM,EAAG,IAAI;IAEb,UAAU,EAAG,IAAI;IAEjB,KAAK,EAAG,UAAU,UAAwB,EAAE,OAAkB;QAC7D,MAAM,YAAY,GAAG,UAA0B,CAAC;QAEhD,oCAAoC;QACpC,YAAY,CAAC,MAAM,GAAG,QAAQ,CAAC,YAAY,CAAC,CAAC;QAE7C,wBAAwB;QACxB,YAAY,CAAC,YAAY,GAAG,CAAC,YAAY,CAAC,IAAI,IAAI,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QAC9G,YAAY,CAAC,IAAI,GAAG,SAAS,CAAC;QAC9B,YAAY,CAAC,KAAK,GAAG,SAAS,CAAC;QAE/B,OAAO,YAAY,CAAC;IACrB,CAAC;IAED,SAAS,EAAG,UAAU,YAAyB,EAAE,OAAkB;QAClE,4BAA4B;QAC5B,IAAI,YAAY,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,YAAY,CAAC,IAAI,KAAK,EAAE,EAAE;YAC1F,YAAY,CAAC,IAAI,GAAG,SAAS,CAAC;SAC9B;QAED,mCAAmC;QACnC,IAAI,OAAO,YAAY,CAAC,MAAM,KAAK,SAAS,EAAE;YAC7C,YAAY,CAAC,MAAM,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAC3D,YAAY,CAAC,MAAM,GAAG,SAAS,CAAC;SAChC;QAED,qCAAqC;QACrC,IAAI,YAAY,CAAC,YAAY,EAAE;YAC9B,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,YAAY,CAAC,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC3D,YAAY,CAAC,IAAI,GAAG,CAAC,IAAI,IAAI,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;YAC9D,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;YAC3B,YAAY,CAAC,YAAY,GAAG,SAAS,CAAC;SACtC;QAED,2BAA2B;QAC3B,YAAY,CAAC,QAAQ,GAAG,SAAS,CAAC;QAElC,OAAO,YAAY,CAAC;IACrB,CAAC;CACD,CAAC;AAEF,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/wss.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/wss.d.ts new file mode 100644 index 0000000..fe5b2f3 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/wss.d.ts @@ -0,0 +1,3 @@ +import { URISchemeHandler } from "../uri"; +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/wss.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/wss.js new file mode 100644 index 0000000..d1e22cc --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/wss.js @@ -0,0 +1,9 @@ +import ws from "./ws"; +const handler = { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize +}; +export default handler; +//# sourceMappingURL=wss.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/wss.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/wss.js.map new file mode 100644 index 0000000..e19006d --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/schemes/wss.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wss.js","sourceRoot":"","sources":["../../../src/schemes/wss.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,MAAM,CAAC;AAEtB,MAAM,OAAO,GAAoB;IAChC,MAAM,EAAG,KAAK;IACd,UAAU,EAAG,EAAE,CAAC,UAAU;IAC1B,KAAK,EAAG,EAAE,CAAC,KAAK;IAChB,SAAS,EAAG,EAAE,CAAC,SAAS;CACxB,CAAA;AAED,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/uri.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/uri.d.ts new file mode 100644 index 0000000..da51e23 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/uri.d.ts @@ -0,0 +1,59 @@ +export interface URIComponents { + scheme?: string; + userinfo?: string; + host?: string; + port?: number | string; + path?: string; + query?: string; + fragment?: string; + reference?: string; + error?: string; +} +export interface URIOptions { + scheme?: string; + reference?: string; + tolerant?: boolean; + absolutePath?: boolean; + iri?: boolean; + unicodeSupport?: boolean; + domainHost?: boolean; +} +export interface URISchemeHandler { + scheme: string; + parse(components: ParentComponents, options: Options): Components; + serialize(components: Components, options: Options): ParentComponents; + unicodeSupport?: boolean; + domainHost?: boolean; + absolutePath?: boolean; +} +export interface URIRegExps { + NOT_SCHEME: RegExp; + NOT_USERINFO: RegExp; + NOT_HOST: RegExp; + NOT_PATH: RegExp; + NOT_PATH_NOSCHEME: RegExp; + NOT_QUERY: RegExp; + NOT_FRAGMENT: RegExp; + ESCAPE: RegExp; + UNRESERVED: RegExp; + OTHER_CHARS: RegExp; + PCT_ENCODED: RegExp; + IPV4ADDRESS: RegExp; + IPV6ADDRESS: RegExp; +} +export declare const SCHEMES: { + [scheme: string]: URISchemeHandler; +}; +export declare function pctEncChar(chr: string): string; +export declare function pctDecChars(str: string): string; +export declare function parse(uriString: string, options?: URIOptions): URIComponents; +export declare function removeDotSegments(input: string): string; +export declare function serialize(components: URIComponents, options?: URIOptions): string; +export declare function resolveComponents(base: URIComponents, relative: URIComponents, options?: URIOptions, skipNormalization?: boolean): URIComponents; +export declare function resolve(baseURI: string, relativeURI: string, options?: URIOptions): string; +export declare function normalize(uri: string, options?: URIOptions): string; +export declare function normalize(uri: URIComponents, options?: URIOptions): URIComponents; +export declare function equal(uriA: string, uriB: string, options?: URIOptions): boolean; +export declare function equal(uriA: URIComponents, uriB: URIComponents, options?: URIOptions): boolean; +export declare function escapeComponent(str: string, options?: URIOptions): string; +export declare function unescapeComponent(str: string, options?: URIOptions): string; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/uri.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/uri.js new file mode 100644 index 0000000..659ce26 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/uri.js @@ -0,0 +1,480 @@ +/** + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author Gary Court + * @see http://github.com/garycourt/uri-js + */ +/** + * Copyright 2011 Gary Court. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. + */ +import URI_PROTOCOL from "./regexps-uri"; +import IRI_PROTOCOL from "./regexps-iri"; +import punycode from "punycode"; +import { toUpperCase, typeOf, assign } from "./util"; +export const SCHEMES = {}; +export function pctEncChar(chr) { + const c = chr.charCodeAt(0); + let e; + if (c < 16) + e = "%0" + c.toString(16).toUpperCase(); + else if (c < 128) + e = "%" + c.toString(16).toUpperCase(); + else if (c < 2048) + e = "%" + ((c >> 6) | 192).toString(16).toUpperCase() + "%" + ((c & 63) | 128).toString(16).toUpperCase(); + else + e = "%" + ((c >> 12) | 224).toString(16).toUpperCase() + "%" + (((c >> 6) & 63) | 128).toString(16).toUpperCase() + "%" + ((c & 63) | 128).toString(16).toUpperCase(); + return e; +} +export function pctDecChars(str) { + let newStr = ""; + let i = 0; + const il = str.length; + while (i < il) { + const c = parseInt(str.substr(i + 1, 2), 16); + if (c < 128) { + newStr += String.fromCharCode(c); + i += 3; + } + else if (c >= 194 && c < 224) { + if ((il - i) >= 6) { + const c2 = parseInt(str.substr(i + 4, 2), 16); + newStr += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + } + else { + newStr += str.substr(i, 6); + } + i += 6; + } + else if (c >= 224) { + if ((il - i) >= 9) { + const c2 = parseInt(str.substr(i + 4, 2), 16); + const c3 = parseInt(str.substr(i + 7, 2), 16); + newStr += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + } + else { + newStr += str.substr(i, 9); + } + i += 9; + } + else { + newStr += str.substr(i, 3); + i += 3; + } + } + return newStr; +} +function _normalizeComponentEncoding(components, protocol) { + function decodeUnreserved(str) { + const decStr = pctDecChars(str); + return (!decStr.match(protocol.UNRESERVED) ? str : decStr); + } + if (components.scheme) + components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); + if (components.userinfo !== undefined) + components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.host !== undefined) + components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.path !== undefined) + components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace((components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME), pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.query !== undefined) + components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.fragment !== undefined) + components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + return components; +} +; +function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; +} +function _normalizeIPv4(host, protocol) { + const matches = host.match(protocol.IPV4ADDRESS) || []; + const [, address] = matches; + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); + } + else { + return host; + } +} +function _normalizeIPv6(host, protocol) { + const matches = host.match(protocol.IPV6ADDRESS) || []; + const [, address, zone] = matches; + if (address) { + const [last, first] = address.toLowerCase().split('::').reverse(); + const firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; + const lastFields = last.split(":").map(_stripLeadingZeros); + const isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); + const fieldCount = isLastFieldIPv4Address ? 7 : 8; + const lastFieldsStart = lastFields.length - fieldCount; + const fields = Array(fieldCount); + for (let x = 0; x < fieldCount; ++x) { + fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; + } + if (isLastFieldIPv4Address) { + fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); + } + const allZeroFields = fields.reduce((acc, field, index) => { + if (!field || field === "0") { + const lastLongest = acc[acc.length - 1]; + if (lastLongest && lastLongest.index + lastLongest.length === index) { + lastLongest.length++; + } + else { + acc.push({ index, length: 1 }); + } + } + return acc; + }, []); + const longestZeroFields = allZeroFields.sort((a, b) => b.length - a.length)[0]; + let newHost; + if (longestZeroFields && longestZeroFields.length > 1) { + const newFirst = fields.slice(0, longestZeroFields.index); + const newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); + newHost = newFirst.join(":") + "::" + newLast.join(":"); + } + else { + newHost = fields.join(":"); + } + if (zone) { + newHost += "%" + zone; + } + return newHost; + } + else { + return host; + } +} +const URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; +const NO_MATCH_IS_UNDEFINED = ("").match(/(){0}/)[1] === undefined; +export function parse(uriString, options = {}) { + const components = {}; + const protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL); + if (options.reference === "suffix") + uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; + const matches = uriString.match(URI_PARSE); + if (matches) { + if (NO_MATCH_IS_UNDEFINED) { + //store each component + components.scheme = matches[1]; + components.userinfo = matches[3]; + components.host = matches[4]; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = matches[7]; + components.fragment = matches[8]; + //fix port number + if (isNaN(components.port)) { + components.port = matches[5]; + } + } + else { //IE FIX for improper RegExp matching + //store each component + components.scheme = matches[1] || undefined; + components.userinfo = (uriString.indexOf("@") !== -1 ? matches[3] : undefined); + components.host = (uriString.indexOf("//") !== -1 ? matches[4] : undefined); + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = (uriString.indexOf("?") !== -1 ? matches[7] : undefined); + components.fragment = (uriString.indexOf("#") !== -1 ? matches[8] : undefined); + //fix port number + if (isNaN(components.port)) { + components.port = (uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined); + } + } + if (components.host) { + //normalize IP hosts + components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); + } + //determine reference type + if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { + components.reference = "same-document"; + } + else if (components.scheme === undefined) { + components.reference = "relative"; + } + else if (components.fragment === undefined) { + components.reference = "absolute"; + } + else { + components.reference = "uri"; + } + //check for reference errors + if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { + components.error = components.error || "URI is not a " + options.reference + " reference."; + } + //find scheme handler + const schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + //if host component is a domain name + if (components.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost))) { + //convert Unicode IDN -> ASCII IDN + try { + components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); + } + catch (e) { + components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; + } + } + //convert IRI -> URI + _normalizeComponentEncoding(components, URI_PROTOCOL); + } + else { + //normalize encodings + _normalizeComponentEncoding(components, protocol); + } + //perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(components, options); + } + } + else { + components.error = components.error || "URI can not be parsed."; + } + return components; +} +; +function _recomposeAuthority(components, options) { + const protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL); + const uriTokens = []; + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo); + uriTokens.push("@"); + } + if (components.host !== undefined) { + //normalize IP hosts, add brackets and escape zone separator for IPv6 + uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, (_, $1, $2) => "[" + $1 + ($2 ? "%25" + $2 : "") + "]")); + } + if (typeof components.port === "number" || typeof components.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(components.port)); + } + return uriTokens.length ? uriTokens.join("") : undefined; +} +; +const RDS1 = /^\.\.?\//; +const RDS2 = /^\/\.(\/|$)/; +const RDS3 = /^\/\.\.(\/|$)/; +const RDS4 = /^\.\.?$/; +const RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; +export function removeDotSegments(input) { + const output = []; + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, ""); + } + else if (input.match(RDS2)) { + input = input.replace(RDS2, "/"); + } + else if (input.match(RDS3)) { + input = input.replace(RDS3, "/"); + output.pop(); + } + else if (input === "." || input === "..") { + input = ""; + } + else { + const im = input.match(RDS5); + if (im) { + const s = im[0]; + input = input.slice(s.length); + output.push(s); + } + else { + throw new Error("Unexpected dot segment condition"); + } + } + } + return output.join(""); +} +; +export function serialize(components, options = {}) { + const protocol = (options.iri ? IRI_PROTOCOL : URI_PROTOCOL); + const uriTokens = []; + //find scheme handler + const schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) + schemeHandler.serialize(components, options); + if (components.host) { + //if host component is an IPv6 address + if (protocol.IPV6ADDRESS.test(components.host)) { + //TODO: normalize IPv6 address as per RFC 5952 + } + //if host component is a domain name + else if (options.domainHost || (schemeHandler && schemeHandler.domainHost)) { + //convert IDN via punycode + try { + components.host = (!options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host)); + } + catch (e) { + components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + } + } + //normalize encoding + _normalizeComponentEncoding(components, protocol); + if (options.reference !== "suffix" && components.scheme) { + uriTokens.push(components.scheme); + uriTokens.push(":"); + } + const authority = _recomposeAuthority(components, options); + if (authority !== undefined) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (components.path && components.path.charAt(0) !== "/") { + uriTokens.push("/"); + } + } + if (components.path !== undefined) { + let s = components.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === undefined) { + s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" + } + uriTokens.push(s); + } + if (components.query !== undefined) { + uriTokens.push("?"); + uriTokens.push(components.query); + } + if (components.fragment !== undefined) { + uriTokens.push("#"); + uriTokens.push(components.fragment); + } + return uriTokens.join(""); //merge tokens into a string +} +; +export function resolveComponents(base, relative, options = {}, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); //normalize base components + relative = parse(serialize(relative, options), options); //normalize relative components + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } + else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } + else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== undefined) { + target.query = relative.query; + } + else { + target.query = base.query; + } + } + else { + if (relative.path.charAt(0) === "/") { + target.path = removeDotSegments(relative.path); + } + else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = "/" + relative.path; + } + else if (!base.path) { + target.path = relative.path; + } + else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + //target.authority = base.authority; + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; +} +; +export function resolve(baseURI, relativeURI, options) { + const schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); +} +; +export function normalize(uri, options) { + if (typeof uri === "string") { + uri = serialize(parse(uri, options), options); + } + else if (typeOf(uri) === "object") { + uri = parse(serialize(uri, options), options); + } + return uri; +} +; +export function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = serialize(parse(uriA, options), options); + } + else if (typeOf(uriA) === "object") { + uriA = serialize(uriA, options); + } + if (typeof uriB === "string") { + uriB = serialize(parse(uriB, options), options); + } + else if (typeOf(uriB) === "object") { + uriB = serialize(uriB, options); + } + return uriA === uriB; +} +; +export function escapeComponent(str, options) { + return str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE), pctEncChar); +} +; +export function unescapeComponent(str, options) { + return str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED), pctDecChars); +} +; +//# sourceMappingURL=uri.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/uri.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/uri.js.map new file mode 100644 index 0000000..2e72ab1 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/uri.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uri.js","sourceRoot":"","sources":["../../src/uri.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,QAAQ,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAiDrD,MAAM,CAAC,MAAM,OAAO,GAAsC,EAAE,CAAC;AAE7D,MAAM,qBAAqB,GAAU;IACpC,MAAM,CAAC,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC5B,IAAI,CAAQ,CAAC;IAEb,IAAI,CAAC,GAAG,EAAE;QAAE,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/C,IAAI,CAAC,GAAG,GAAG;QAAE,CAAC,GAAG,GAAG,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;SACpD,IAAI,CAAC,GAAG,IAAI;QAAE,CAAC,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;;QACxH,CAAC,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IAE3K,OAAO,CAAC,CAAC;AACV,CAAC;AAED,MAAM,sBAAsB,GAAU;IACrC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,MAAM,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;IAEtB,OAAO,CAAC,GAAG,EAAE,EAAE;QACd,MAAM,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAE7C,IAAI,CAAC,GAAG,GAAG,EAAE;YACZ,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;YACjC,CAAC,IAAI,CAAC,CAAC;SACP;aACI,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,GAAG,EAAE;YAC7B,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE;gBAClB,MAAM,EAAE,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;gBAC9C,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;aAC3D;iBAAM;gBACN,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;aAC3B;YACD,CAAC,IAAI,CAAC,CAAC;SACP;aACI,IAAI,CAAC,IAAI,GAAG,EAAE;YAClB,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE;gBAClB,MAAM,EAAE,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;gBAC9C,MAAM,EAAE,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;gBAC9C,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;aAC/E;iBAAM;gBACN,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;aAC3B;YACD,CAAC,IAAI,CAAC,CAAC;SACP;aACI;YACJ,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;YAC3B,CAAC,IAAI,CAAC,CAAC;SACP;KACD;IAED,OAAO,MAAM,CAAC;AACf,CAAC;AAED,qCAAqC,UAAwB,EAAE,QAAmB;IACjF,0BAA0B,GAAU;QACnC,MAAM,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;QAChC,OAAO,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;IAC5D,CAAC;IAED,IAAI,UAAU,CAAC,MAAM;QAAE,UAAU,CAAC,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IACpK,IAAI,UAAU,CAAC,QAAQ,KAAK,SAAS;QAAE,UAAU,CAAC,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;IAC/N,IAAI,UAAU,CAAC,IAAI,KAAK,SAAS;QAAE,UAAU,CAAC,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;IAC7N,IAAI,UAAU,CAAC,IAAI,KAAK,SAAS;QAAE,UAAU,CAAC,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,OAAO,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,UAAU,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;IAClQ,IAAI,UAAU,CAAC,KAAK,KAAK,SAAS;QAAE,UAAU,CAAC,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;IACnN,IAAI,UAAU,CAAC,QAAQ,KAAK,SAAS;QAAE,UAAU,CAAC,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;IAE/N,OAAO,UAAU,CAAC;AACnB,CAAC;AAAA,CAAC;AAEF,4BAA4B,GAAU;IACrC,OAAO,GAAG,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,CAAC,IAAI,GAAG,CAAC;AAC5C,CAAC;AAED,wBAAwB,IAAW,EAAE,QAAmB;IACvD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;IACvD,MAAM,CAAC,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC;IAE5B,IAAI,OAAO,EAAE;QACZ,OAAO,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;KAC5D;SAAM;QACN,OAAO,IAAI,CAAC;KACZ;AACF,CAAC;AAED,wBAAwB,IAAW,EAAE,QAAmB;IACvD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;IACvD,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC;IAElC,IAAI,OAAO,EAAE;QACZ,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,CAAC;QAClE,MAAM,WAAW,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1E,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;QAC3D,MAAM,sBAAsB,GAAG,QAAQ,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;QAC5F,MAAM,UAAU,GAAG,sBAAsB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAClD,MAAM,eAAe,GAAG,UAAU,CAAC,MAAM,GAAG,UAAU,CAAC;QACvD,MAAM,MAAM,GAAG,KAAK,CAAS,UAAU,CAAC,CAAC;QAEzC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,EAAE,EAAE,CAAC,EAAE;YACpC,MAAM,CAAC,CAAC,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,eAAe,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;SACpE;QAED,IAAI,sBAAsB,EAAE;YAC3B,MAAM,CAAC,UAAU,GAAG,CAAC,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,UAAU,GAAG,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;SAC1E;QAED,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAsC,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;YAC9F,IAAI,CAAC,KAAK,IAAI,KAAK,KAAK,GAAG,EAAE;gBAC5B,MAAM,WAAW,GAAG,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;gBACxC,IAAI,WAAW,IAAI,WAAW,CAAC,KAAK,GAAG,WAAW,CAAC,MAAM,KAAK,KAAK,EAAE;oBACpE,WAAW,CAAC,MAAM,EAAE,CAAC;iBACrB;qBAAM;oBACN,GAAG,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,EAAG,CAAC,EAAE,CAAC,CAAC;iBAChC;aACD;YACD,OAAO,GAAG,CAAC;QACZ,CAAC,EAAE,EAAE,CAAC,CAAC;QAEP,MAAM,iBAAiB,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAE/E,IAAI,OAAc,CAAC;QACnB,IAAI,iBAAiB,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE;YACtD,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,iBAAiB,CAAC,KAAK,CAAC,CAAE;YAC3D,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,iBAAiB,CAAC,KAAK,GAAG,iBAAiB,CAAC,MAAM,CAAC,CAAC;YACjF,OAAO,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SACxD;aAAM;YACN,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SAC3B;QAED,IAAI,IAAI,EAAE;YACT,OAAO,IAAI,GAAG,GAAG,IAAI,CAAC;SACtB;QAED,OAAO,OAAO,CAAC;KACf;SAAM;QACN,OAAO,IAAI,CAAC;KACZ;AACF,CAAC;AAED,MAAM,SAAS,GAAG,iIAAiI,CAAC;AACpJ,MAAM,qBAAqB,GAAsB,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAE,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC;AAEvF,MAAM,gBAAgB,SAAgB,EAAE,UAAqB,EAAE;IAC9D,MAAM,UAAU,GAAiB,EAAE,CAAC;IACpC,MAAM,QAAQ,GAAG,CAAC,OAAO,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;IAEvE,IAAI,OAAO,CAAC,SAAS,KAAK,QAAQ;QAAE,SAAS,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,GAAG,SAAS,CAAC;IAEhH,MAAM,OAAO,GAAG,SAAS,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IAE3C,IAAI,OAAO,EAAE;QACZ,IAAI,qBAAqB,EAAE;YAC1B,sBAAsB;YACtB,UAAU,CAAC,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YAC/B,UAAU,CAAC,QAAQ,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YACjC,UAAU,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YAC7B,UAAU,CAAC,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAC3C,UAAU,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACnC,UAAU,CAAC,KAAK,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YAC9B,UAAU,CAAC,QAAQ,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YAEjC,iBAAiB;YACjB,IAAI,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;gBAC3B,UAAU,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;aAC7B;SACD;aAAM,EAAG,qCAAqC;YAC9C,sBAAsB;YACtB,UAAU,CAAC,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,SAAS,CAAC;YAC5C,UAAU,CAAC,QAAQ,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;YAC/E,UAAU,CAAC,IAAI,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;YAC5E,UAAU,CAAC,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAC3C,UAAU,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACnC,UAAU,CAAC,KAAK,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;YAC5E,UAAU,CAAC,QAAQ,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;YAE/E,iBAAiB;YACjB,IAAI,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;gBAC3B,UAAU,CAAC,IAAI,GAAG,CAAC,SAAS,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;aAC9F;SACD;QAED,IAAI,UAAU,CAAC,IAAI,EAAE;YACpB,oBAAoB;YACpB,UAAU,CAAC,IAAI,GAAG,cAAc,CAAC,cAAc,CAAC,UAAU,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;SACtF;QAED,0BAA0B;QAC1B,IAAI,UAAU,CAAC,MAAM,KAAK,SAAS,IAAI,UAAU,CAAC,QAAQ,KAAK,SAAS,IAAI,UAAU,CAAC,IAAI,KAAK,SAAS,IAAI,UAAU,CAAC,IAAI,KAAK,SAAS,IAAI,CAAC,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,KAAK,KAAK,SAAS,EAAE;YACjM,UAAU,CAAC,SAAS,GAAG,eAAe,CAAC;SACvC;aAAM,IAAI,UAAU,CAAC,MAAM,KAAK,SAAS,EAAE;YAC3C,UAAU,CAAC,SAAS,GAAG,UAAU,CAAC;SAClC;aAAM,IAAI,UAAU,CAAC,QAAQ,KAAK,SAAS,EAAE;YAC7C,UAAU,CAAC,SAAS,GAAG,UAAU,CAAC;SAClC;aAAM;YACN,UAAU,CAAC,SAAS,GAAG,KAAK,CAAC;SAC7B;QAED,4BAA4B;QAC5B,IAAI,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,SAAS,KAAK,QAAQ,IAAI,OAAO,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS,EAAE;YACtG,UAAU,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,IAAI,eAAe,GAAG,OAAO,CAAC,SAAS,GAAG,aAAa,CAAC;SAC3F;QAED,qBAAqB;QACrB,MAAM,aAAa,GAAG,OAAO,CAAC,CAAC,OAAO,CAAC,MAAM,IAAI,UAAU,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;QAEzF,mCAAmC;QACnC,IAAI,CAAC,OAAO,CAAC,cAAc,IAAI,CAAC,CAAC,aAAa,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC,EAAE;YACjF,oCAAoC;YACpC,IAAI,UAAU,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,UAAU,IAAI,CAAC,aAAa,IAAI,aAAa,CAAC,UAAU,CAAC,CAAC,EAAE;gBAC3F,kCAAkC;gBAClC,IAAI;oBACH,UAAU,CAAC,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;iBAC7G;gBAAC,OAAO,CAAC,EAAE;oBACX,UAAU,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,IAAI,iEAAiE,GAAG,CAAC,CAAC;iBAC7G;aACD;YACD,oBAAoB;YACpB,2BAA2B,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;SACtD;aAAM;YACN,qBAAqB;YACrB,2BAA2B,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;SAClD;QAED,iCAAiC;QACjC,IAAI,aAAa,IAAI,aAAa,CAAC,KAAK,EAAE;YACzC,aAAa,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;SACzC;KACD;SAAM;QACN,UAAU,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,IAAI,wBAAwB,CAAC;KAChE;IAED,OAAO,UAAU,CAAC;AACnB,CAAC;AAAA,CAAC;AAEF,6BAA6B,UAAwB,EAAE,OAAkB;IACxE,MAAM,QAAQ,GAAG,CAAC,OAAO,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;IACvE,MAAM,SAAS,GAAiB,EAAE,CAAC;IAEnC,IAAI,UAAU,CAAC,QAAQ,KAAK,SAAS,EAAE;QACtC,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;QACpC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;KACpB;IAED,IAAI,UAAU,CAAC,IAAI,KAAK,SAAS,EAAE;QAClC,qEAAqE;QACrE,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,cAAc,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,GAAG,GAAG,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;KAClL;IAED,IAAI,OAAO,UAAU,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,UAAU,CAAC,IAAI,KAAK,QAAQ,EAAE;QAC/E,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACpB,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;KACxC;IAED,OAAO,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC;AAAA,CAAC;AAEF,MAAM,IAAI,GAAG,UAAU,CAAC;AACxB,MAAM,IAAI,GAAG,aAAa,CAAC;AAC3B,MAAM,IAAI,GAAG,eAAe,CAAC;AAC7B,MAAM,IAAI,GAAG,SAAS,CAAC;AACvB,MAAM,IAAI,GAAG,wBAAwB,CAAC;AAEtC,MAAM,4BAA4B,KAAY;IAC7C,MAAM,MAAM,GAAiB,EAAE,CAAC;IAEhC,OAAO,KAAK,CAAC,MAAM,EAAE;QACpB,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE;YACtB,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;SAChC;aAAM,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE;YAC7B,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;SACjC;aAAM,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE;YAC7B,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;YACjC,MAAM,CAAC,GAAG,EAAE,CAAC;SACb;aAAM,IAAI,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,IAAI,EAAE;YAC3C,KAAK,GAAG,EAAE,CAAC;SACX;aAAM;YACN,MAAM,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC7B,IAAI,EAAE,EAAE;gBACP,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;gBAChB,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;gBAC9B,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;aACf;iBAAM;gBACN,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;aACpD;SACD;KACD;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACxB,CAAC;AAAA,CAAC;AAEF,MAAM,oBAAoB,UAAwB,EAAE,UAAqB,EAAE;IAC1E,MAAM,QAAQ,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;IAC7D,MAAM,SAAS,GAAiB,EAAE,CAAC;IAEnC,qBAAqB;IACrB,MAAM,aAAa,GAAG,OAAO,CAAC,CAAC,OAAO,CAAC,MAAM,IAAI,UAAU,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;IAEzF,uCAAuC;IACvC,IAAI,aAAa,IAAI,aAAa,CAAC,SAAS;QAAE,aAAa,CAAC,SAAS,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAE3F,IAAI,UAAU,CAAC,IAAI,EAAE;QACpB,sCAAsC;QACtC,IAAI,QAAQ,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;YAC/C,8CAA8C;SAC9C;QAED,oCAAoC;aAC/B,IAAI,OAAO,CAAC,UAAU,IAAI,CAAC,aAAa,IAAI,aAAa,CAAC,UAAU,CAAC,EAAE;YAC3E,0BAA0B;YAC1B,IAAI;gBACH,UAAU,CAAC,IAAI,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;aACpK;YAAC,OAAO,CAAC,EAAE;gBACX,UAAU,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,IAAI,6CAA6C,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,iBAAiB,GAAG,CAAC,CAAC;aACpJ;SACD;KACD;IAED,oBAAoB;IACpB,2BAA2B,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAElD,IAAI,OAAO,CAAC,SAAS,KAAK,QAAQ,IAAI,UAAU,CAAC,MAAM,EAAE;QACxD,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QAClC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;KACpB;IAED,MAAM,SAAS,GAAG,mBAAmB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAC3D,IAAI,SAAS,KAAK,SAAS,EAAE;QAC5B,IAAI,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YACnC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;SACrB;QAED,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAE1B,IAAI,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;YACzD,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SACpB;KACD;IAED,IAAI,UAAU,CAAC,IAAI,KAAK,SAAS,EAAE;QAClC,IAAI,CAAC,GAAG,UAAU,CAAC,IAAI,CAAC;QAExB,IAAI,CAAC,OAAO,CAAC,YAAY,IAAI,CAAC,CAAC,aAAa,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC,EAAE;YAC7E,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC;SACzB;QAED,IAAI,SAAS,KAAK,SAAS,EAAE;YAC5B,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAE,yCAAyC;SAC1E;QAED,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;KAClB;IAED,IAAI,UAAU,CAAC,KAAK,KAAK,SAAS,EAAE;QACnC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACpB,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;KACjC;IAED,IAAI,UAAU,CAAC,QAAQ,KAAK,SAAS,EAAE;QACtC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACpB,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;KACpC;IAED,OAAO,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAE,4BAA4B;AACzD,CAAC;AAAA,CAAC;AAEF,MAAM,4BAA4B,IAAkB,EAAE,QAAsB,EAAE,UAAqB,EAAE,EAAE,iBAA0B;IAChI,MAAM,MAAM,GAAiB,EAAE,CAAC;IAEhC,IAAI,CAAC,iBAAiB,EAAE;QACvB,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAE,2BAA2B;QAC7E,QAAQ,GAAG,KAAK,CAAC,SAAS,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAE,+BAA+B;KACzF;IACD,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;IAExB,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,EAAE;QACzC,MAAM,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC;QAChC,wCAAwC;QACxC,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC,QAAQ,CAAC;QACpC,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC;QAC5B,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC;QAC5B,MAAM,CAAC,IAAI,GAAG,iBAAiB,CAAC,QAAQ,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC;QACrD,MAAM,CAAC,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;KAC9B;SAAM;QACN,IAAI,QAAQ,CAAC,QAAQ,KAAK,SAAS,IAAI,QAAQ,CAAC,IAAI,KAAK,SAAS,IAAI,QAAQ,CAAC,IAAI,KAAK,SAAS,EAAE;YAClG,wCAAwC;YACxC,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC,QAAQ,CAAC;YACpC,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC;YAC5B,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC;YAC5B,MAAM,CAAC,IAAI,GAAG,iBAAiB,CAAC,QAAQ,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC;YACrD,MAAM,CAAC,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;SAC9B;aAAM;YACN,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE;gBACnB,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;gBACxB,IAAI,QAAQ,CAAC,KAAK,KAAK,SAAS,EAAE;oBACjC,MAAM,CAAC,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;iBAC9B;qBAAM;oBACN,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;iBAC1B;aACD;iBAAM;gBACN,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;oBACpC,MAAM,CAAC,IAAI,GAAG,iBAAiB,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;iBAC/C;qBAAM;oBACN,IAAI,CAAC,IAAI,CAAC,QAAQ,KAAK,SAAS,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE;wBACtG,MAAM,CAAC,IAAI,GAAG,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC;qBAClC;yBAAM,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE;wBACtB,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC;qBAC5B;yBAAM;wBACN,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC;qBACjF;oBACD,MAAM,CAAC,IAAI,GAAG,iBAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;iBAC7C;gBACD,MAAM,CAAC,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;aAC9B;YACD,oCAAoC;YACpC,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;YAChC,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;YACxB,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;SACxB;QACD,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;KAC5B;IAED,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC,QAAQ,CAAC;IAEpC,OAAO,MAAM,CAAC;AACf,CAAC;AAAA,CAAC;AAEF,MAAM,kBAAkB,OAAc,EAAE,WAAkB,EAAE,OAAmB;IAC9E,MAAM,iBAAiB,GAAG,MAAM,CAAC,EAAE,MAAM,EAAG,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;IAC/D,OAAO,SAAS,CAAC,iBAAiB,CAAC,KAAK,CAAC,OAAO,EAAE,iBAAiB,CAAC,EAAE,KAAK,CAAC,WAAW,EAAE,iBAAiB,CAAC,EAAE,iBAAiB,EAAE,IAAI,CAAC,EAAE,iBAAiB,CAAC,CAAC;AAC3J,CAAC;AAAA,CAAC;AAIF,MAAM,oBAAoB,GAAO,EAAE,OAAmB;IACrD,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAC5B,GAAG,GAAG,SAAS,CAAC,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;KAC9C;SAAM,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,QAAQ,EAAE;QACpC,GAAG,GAAG,KAAK,CAAC,SAAS,CAAgB,GAAG,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;KAC7D;IAED,OAAO,GAAG,CAAC;AACZ,CAAC;AAAA,CAAC;AAIF,MAAM,gBAAgB,IAAQ,EAAE,IAAQ,EAAE,OAAmB;IAC5D,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC7B,IAAI,GAAG,SAAS,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;KAChD;SAAM,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,QAAQ,EAAE;QACrC,IAAI,GAAG,SAAS,CAAgB,IAAI,EAAE,OAAO,CAAC,CAAC;KAC/C;IAED,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC7B,IAAI,GAAG,SAAS,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;KAChD;SAAM,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,QAAQ,EAAE;QACrC,IAAI,GAAG,SAAS,CAAgB,IAAI,EAAE,OAAO,CAAC,CAAC;KAC/C;IAED,OAAO,IAAI,KAAK,IAAI,CAAC;AACtB,CAAC;AAAA,CAAC;AAEF,MAAM,0BAA0B,GAAU,EAAE,OAAmB;IAC9D,OAAO,GAAG,IAAI,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,UAAU,CAAC,CAAC;AAC1H,CAAC;AAAA,CAAC;AAEF,MAAM,4BAA4B,GAAU,EAAE,OAAmB;IAChE,OAAO,GAAG,IAAI,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,WAAW,CAAC,CAAC,CAAC,YAAY,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC,CAAC;AACrI,CAAC;AAAA,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/util.d.ts b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/util.d.ts new file mode 100644 index 0000000..7c12857 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/util.d.ts @@ -0,0 +1,6 @@ +export declare function merge(...sets: Array): string; +export declare function subexp(str: string): string; +export declare function typeOf(o: any): string; +export declare function toUpperCase(str: string): string; +export declare function toArray(obj: any): Array; +export declare function assign(target: object, source: any): any; diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/util.js b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/util.js new file mode 100644 index 0000000..072711e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/util.js @@ -0,0 +1,36 @@ +export function merge(...sets) { + if (sets.length > 1) { + sets[0] = sets[0].slice(0, -1); + const xl = sets.length - 1; + for (let x = 1; x < xl; ++x) { + sets[x] = sets[x].slice(1, -1); + } + sets[xl] = sets[xl].slice(1); + return sets.join(''); + } + else { + return sets[0]; + } +} +export function subexp(str) { + return "(?:" + str + ")"; +} +export function typeOf(o) { + return o === undefined ? "undefined" : (o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase()); +} +export function toUpperCase(str) { + return str.toUpperCase(); +} +export function toArray(obj) { + return obj !== undefined && obj !== null ? (obj instanceof Array ? obj : (typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj))) : []; +} +export function assign(target, source) { + const obj = target; + if (source) { + for (const key in source) { + obj[key] = source[key]; + } + } + return obj; +} +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/util.js.map b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/util.js.map new file mode 100644 index 0000000..05d9df0 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/dist/esnext/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":"AAAA,MAAM,gBAAgB,GAAG,IAAkB;IAC1C,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;QACpB,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QAC/B,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE;YAC5B,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;SAC/B;QACD,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC7B,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;KACrB;SAAM;QACN,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC;KACf;AACF,CAAC;AAED,MAAM,iBAAiB,GAAU;IAChC,OAAO,KAAK,GAAG,GAAG,GAAG,GAAG,CAAC;AAC1B,CAAC;AAED,MAAM,iBAAiB,CAAK;IAC3B,OAAO,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;AACpJ,CAAC;AAED,MAAM,sBAAsB,GAAU;IACrC,OAAO,GAAG,CAAC,WAAW,EAAE,CAAC;AAC1B,CAAC;AAED,MAAM,kBAAkB,GAAO;IAC9B,OAAO,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,GAAG,CAAC,MAAM,KAAK,QAAQ,IAAI,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACvM,CAAC;AAGD,MAAM,iBAAiB,MAAc,EAAE,MAAW;IACjD,MAAM,GAAG,GAAG,MAAa,CAAC;IAC1B,IAAI,MAAM,EAAE;QACX,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE;YACzB,GAAG,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;SACvB;KACD;IACD,OAAO,GAAG,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/node_modules/mathjs/examples/node_modules/uri-js/package.json b/node_modules/mathjs/examples/node_modules/uri-js/package.json new file mode 100644 index 0000000..de95d91 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/package.json @@ -0,0 +1,77 @@ +{ + "name": "uri-js", + "version": "4.4.1", + "description": "An RFC 3986/3987 compliant, scheme extendable URI/IRI parsing/validating/resolving library for JavaScript.", + "main": "dist/es5/uri.all.js", + "types": "dist/es5/uri.all.d.ts", + "directories": { + "test": "tests" + }, + "files": [ + "dist", + "package.json", + "yarn.lock", + "README.md", + "CHANGELOG", + "LICENSE" + ], + "scripts": { + "build:esnext": "tsc", + "build:es5": "rollup -c && cp dist/esnext/uri.d.ts dist/es5/uri.all.d.ts && npm run build:es5:fix-sourcemap", + "build:es5:fix-sourcemap": "sorcery -i dist/es5/uri.all.js", + "build:es5:min": "uglifyjs dist/es5/uri.all.js --support-ie8 --output dist/es5/uri.all.min.js --in-source-map dist/es5/uri.all.js.map --source-map uri.all.min.js.map --comments --compress --mangle --pure-funcs merge subexp && mv uri.all.min.js.map dist/es5/ && cp dist/es5/uri.all.d.ts dist/es5/uri.all.min.d.ts", + "build": "npm run build:esnext && npm run build:es5 && npm run build:es5:min", + "clean": "rm -rf dist", + "test": "mocha -u mocha-qunit-ui dist/es5/uri.all.js tests/tests.js" + }, + "repository": { + "type": "git", + "url": "http://github.com/garycourt/uri-js" + }, + "keywords": [ + "URI", + "IRI", + "IDN", + "URN", + "UUID", + "HTTP", + "HTTPS", + "WS", + "WSS", + "MAILTO", + "RFC3986", + "RFC3987", + "RFC5891", + "RFC2616", + "RFC2818", + "RFC2141", + "RFC4122", + "RFC4291", + "RFC5952", + "RFC6068", + "RFC6455", + "RFC6874" + ], + "author": "Gary Court ", + "license": "BSD-2-Clause", + "bugs": { + "url": "https://github.com/garycourt/uri-js/issues" + }, + "homepage": "https://github.com/garycourt/uri-js", + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-plugin-external-helpers": "^6.22.0", + "babel-preset-latest": "^6.24.1", + "mocha": "^8.2.1", + "mocha-qunit-ui": "^0.1.3", + "rollup": "^0.41.6", + "rollup-plugin-babel": "^2.7.1", + "rollup-plugin-node-resolve": "^2.0.0", + "sorcery": "^0.10.0", + "typescript": "^2.8.1", + "uglify-js": "^2.8.14" + }, + "dependencies": { + "punycode": "^2.1.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/uri-js/yarn.lock b/node_modules/mathjs/examples/node_modules/uri-js/yarn.lock new file mode 100644 index 0000000..3c42ded --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/uri-js/yarn.lock @@ -0,0 +1,2558 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@ungap/promise-all-settled@1.1.2": + version "1.1.2" + resolved "https://registry.yarnpkg.com/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz#aa58042711d6e3275dd37dc597e5d31e8c290a44" + integrity sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q== + +align-text@^0.1.1, align-text@^0.1.3: + version "0.1.4" + resolved "https://registry.yarnpkg.com/align-text/-/align-text-0.1.4.tgz#0cd90a561093f35d0a99256c22b7069433fad117" + dependencies: + kind-of "^3.0.2" + longest "^1.0.1" + repeat-string "^1.5.2" + +ansi-colors@4.1.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348" + integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== + +ansi-regex@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" + integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8= + +ansi-regex@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998" + integrity sha1-7QMXwyIGT3lGbAKWa922Bas32Zg= + +ansi-regex@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.0.tgz#8b9f8f08cf1acb843756a839ca8c7e3168c51997" + integrity sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg== + +ansi-styles@^2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" + integrity sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4= + +ansi-styles@^3.2.0: + version "3.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" + integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== + dependencies: + color-convert "^1.9.0" + +ansi-styles@^4.1.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" + integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== + dependencies: + color-convert "^2.0.1" + +anymatch@^1.3.0: + version "1.3.2" + resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-1.3.2.tgz#553dcb8f91e3c889845dfdba34c77721b90b9d7a" + integrity sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA== + dependencies: + micromatch "^2.1.5" + normalize-path "^2.0.0" + +anymatch@~3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.1.tgz#c55ecf02185e2469259399310c173ce31233b142" + integrity sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg== + dependencies: + normalize-path "^3.0.0" + picomatch "^2.0.4" + +argparse@^1.0.7: + version "1.0.10" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" + integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== + dependencies: + sprintf-js "~1.0.2" + +arr-diff@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-2.0.0.tgz#8f3b827f955a8bd669697e4a4256ac3ceae356cf" + integrity sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8= + dependencies: + arr-flatten "^1.0.1" + +arr-diff@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-4.0.0.tgz#d6461074febfec71e7e15235761a329a5dc7c520" + integrity sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA= + +arr-flatten@^1.0.1, arr-flatten@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1" + integrity sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg== + +arr-union@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-3.1.0.tgz#e39b09aea9def866a8f206e288af63919bae39c4" + integrity sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ= + +array-unique@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.2.1.tgz#a1d97ccafcbc2625cc70fadceb36a50c58b01a53" + integrity sha1-odl8yvy8JiXMcPrc6zalDFiwGlM= + +array-unique@^0.3.2: + version "0.3.2" + resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428" + integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg= + +assign-symbols@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367" + integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c= + +async-each@^1.0.0: + version "1.0.3" + resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.3.tgz#b727dbf87d7651602f06f4d4ac387f47d91b0cbf" + integrity sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ== + +atob@^2.1.2: + version "2.1.2" + resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9" + integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg== + +babel-cli@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-cli/-/babel-cli-6.26.0.tgz#502ab54874d7db88ad00b887a06383ce03d002f1" + integrity sha1-UCq1SHTX24itALiHoGODzgPQAvE= + dependencies: + babel-core "^6.26.0" + babel-polyfill "^6.26.0" + babel-register "^6.26.0" + babel-runtime "^6.26.0" + commander "^2.11.0" + convert-source-map "^1.5.0" + fs-readdir-recursive "^1.0.0" + glob "^7.1.2" + lodash "^4.17.4" + output-file-sync "^1.1.2" + path-is-absolute "^1.0.1" + slash "^1.0.0" + source-map "^0.5.6" + v8flags "^2.1.1" + optionalDependencies: + chokidar "^1.6.1" + +babel-code-frame@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b" + integrity sha1-Y/1D99weO7fONZR9uP42mj9Yx0s= + dependencies: + chalk "^1.1.3" + esutils "^2.0.2" + js-tokens "^3.0.2" + +babel-core@6: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-core/-/babel-core-6.26.0.tgz#af32f78b31a6fcef119c87b0fd8d9753f03a0bb8" + dependencies: + babel-code-frame "^6.26.0" + babel-generator "^6.26.0" + babel-helpers "^6.24.1" + babel-messages "^6.23.0" + babel-register "^6.26.0" + babel-runtime "^6.26.0" + babel-template "^6.26.0" + babel-traverse "^6.26.0" + babel-types "^6.26.0" + babylon "^6.18.0" + convert-source-map "^1.5.0" + debug "^2.6.8" + json5 "^0.5.1" + lodash "^4.17.4" + minimatch "^3.0.4" + path-is-absolute "^1.0.1" + private "^0.1.7" + slash "^1.0.0" + source-map "^0.5.6" + +babel-core@^6.26.0: + version "6.26.3" + resolved "https://registry.yarnpkg.com/babel-core/-/babel-core-6.26.3.tgz#b2e2f09e342d0f0c88e2f02e067794125e75c207" + integrity sha512-6jyFLuDmeidKmUEb3NM+/yawG0M2bDZ9Z1qbZP59cyHLz8kYGKYwpJP0UwUKKUiTRNvxfLesJnTedqczP7cTDA== + dependencies: + babel-code-frame "^6.26.0" + babel-generator "^6.26.0" + babel-helpers "^6.24.1" + babel-messages "^6.23.0" + babel-register "^6.26.0" + babel-runtime "^6.26.0" + babel-template "^6.26.0" + babel-traverse "^6.26.0" + babel-types "^6.26.0" + babylon "^6.18.0" + convert-source-map "^1.5.1" + debug "^2.6.9" + json5 "^0.5.1" + lodash "^4.17.4" + minimatch "^3.0.4" + path-is-absolute "^1.0.1" + private "^0.1.8" + slash "^1.0.0" + source-map "^0.5.7" + +babel-generator@^6.26.0: + version "6.26.1" + resolved "https://registry.yarnpkg.com/babel-generator/-/babel-generator-6.26.1.tgz#1844408d3b8f0d35a404ea7ac180f087a601bd90" + integrity sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA== + dependencies: + babel-messages "^6.23.0" + babel-runtime "^6.26.0" + babel-types "^6.26.0" + detect-indent "^4.0.0" + jsesc "^1.3.0" + lodash "^4.17.4" + source-map "^0.5.7" + trim-right "^1.0.1" + +babel-helper-builder-binary-assignment-operator-visitor@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-builder-binary-assignment-operator-visitor/-/babel-helper-builder-binary-assignment-operator-visitor-6.24.1.tgz#cce4517ada356f4220bcae8a02c2b346f9a56664" + dependencies: + babel-helper-explode-assignable-expression "^6.24.1" + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-helper-call-delegate@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-call-delegate/-/babel-helper-call-delegate-6.24.1.tgz#ece6aacddc76e41c3461f88bfc575bd0daa2df8d" + dependencies: + babel-helper-hoist-variables "^6.24.1" + babel-runtime "^6.22.0" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-helper-define-map@^6.24.1: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-helper-define-map/-/babel-helper-define-map-6.26.0.tgz#a5f56dab41a25f97ecb498c7ebaca9819f95be5f" + dependencies: + babel-helper-function-name "^6.24.1" + babel-runtime "^6.26.0" + babel-types "^6.26.0" + lodash "^4.17.4" + +babel-helper-explode-assignable-expression@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-explode-assignable-expression/-/babel-helper-explode-assignable-expression-6.24.1.tgz#f25b82cf7dc10433c55f70592d5746400ac22caa" + dependencies: + babel-runtime "^6.22.0" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-helper-function-name@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-function-name/-/babel-helper-function-name-6.24.1.tgz#d3475b8c03ed98242a25b48351ab18399d3580a9" + dependencies: + babel-helper-get-function-arity "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-helper-get-function-arity@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-get-function-arity/-/babel-helper-get-function-arity-6.24.1.tgz#8f7782aa93407c41d3aa50908f89b031b1b6853d" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-helper-hoist-variables@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-hoist-variables/-/babel-helper-hoist-variables-6.24.1.tgz#1ecb27689c9d25513eadbc9914a73f5408be7a76" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-helper-optimise-call-expression@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-optimise-call-expression/-/babel-helper-optimise-call-expression-6.24.1.tgz#f7a13427ba9f73f8f4fa993c54a97882d1244257" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-helper-regex@^6.24.1: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-helper-regex/-/babel-helper-regex-6.26.0.tgz#325c59f902f82f24b74faceed0363954f6495e72" + dependencies: + babel-runtime "^6.26.0" + babel-types "^6.26.0" + lodash "^4.17.4" + +babel-helper-remap-async-to-generator@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-remap-async-to-generator/-/babel-helper-remap-async-to-generator-6.24.1.tgz#5ec581827ad723fecdd381f1c928390676e4551b" + dependencies: + babel-helper-function-name "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-helper-replace-supers@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-replace-supers/-/babel-helper-replace-supers-6.24.1.tgz#bf6dbfe43938d17369a213ca8a8bf74b6a90ab1a" + dependencies: + babel-helper-optimise-call-expression "^6.24.1" + babel-messages "^6.23.0" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-helpers@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helpers/-/babel-helpers-6.24.1.tgz#3471de9caec388e5c850e597e58a26ddf37602b2" + integrity sha1-NHHenK7DiOXIUOWX5Yom3fN2ArI= + dependencies: + babel-runtime "^6.22.0" + babel-template "^6.24.1" + +babel-messages@^6.23.0: + version "6.23.0" + resolved "https://registry.yarnpkg.com/babel-messages/-/babel-messages-6.23.0.tgz#f3cdf4703858035b2a2951c6ec5edf6c62f2630e" + integrity sha1-8830cDhYA1sqKVHG7F7fbGLyYw4= + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-check-es2015-constants@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-check-es2015-constants/-/babel-plugin-check-es2015-constants-6.22.0.tgz#35157b101426fd2ffd3da3f75c7d1e91835bbf8a" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-external-helpers@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-external-helpers/-/babel-plugin-external-helpers-6.22.0.tgz#2285f48b02bd5dede85175caf8c62e86adccefa1" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-syntax-async-functions@^6.8.0: + version "6.13.0" + resolved "https://registry.yarnpkg.com/babel-plugin-syntax-async-functions/-/babel-plugin-syntax-async-functions-6.13.0.tgz#cad9cad1191b5ad634bf30ae0872391e0647be95" + +babel-plugin-syntax-exponentiation-operator@^6.8.0: + version "6.13.0" + resolved "https://registry.yarnpkg.com/babel-plugin-syntax-exponentiation-operator/-/babel-plugin-syntax-exponentiation-operator-6.13.0.tgz#9ee7e8337290da95288201a6a57f4170317830de" + +babel-plugin-syntax-trailing-function-commas@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-syntax-trailing-function-commas/-/babel-plugin-syntax-trailing-function-commas-6.22.0.tgz#ba0360937f8d06e40180a43fe0d5616fff532cf3" + +babel-plugin-transform-async-to-generator@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-async-to-generator/-/babel-plugin-transform-async-to-generator-6.24.1.tgz#6536e378aff6cb1d5517ac0e40eb3e9fc8d08761" + dependencies: + babel-helper-remap-async-to-generator "^6.24.1" + babel-plugin-syntax-async-functions "^6.8.0" + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-arrow-functions@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-arrow-functions/-/babel-plugin-transform-es2015-arrow-functions-6.22.0.tgz#452692cb711d5f79dc7f85e440ce41b9f244d221" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-block-scoped-functions@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-block-scoped-functions/-/babel-plugin-transform-es2015-block-scoped-functions-6.22.0.tgz#bbc51b49f964d70cb8d8e0b94e820246ce3a6141" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-block-scoping@^6.24.1: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-block-scoping/-/babel-plugin-transform-es2015-block-scoping-6.26.0.tgz#d70f5299c1308d05c12f463813b0a09e73b1895f" + dependencies: + babel-runtime "^6.26.0" + babel-template "^6.26.0" + babel-traverse "^6.26.0" + babel-types "^6.26.0" + lodash "^4.17.4" + +babel-plugin-transform-es2015-classes@^6.24.1, babel-plugin-transform-es2015-classes@^6.9.0: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-classes/-/babel-plugin-transform-es2015-classes-6.24.1.tgz#5a4c58a50c9c9461e564b4b2a3bfabc97a2584db" + dependencies: + babel-helper-define-map "^6.24.1" + babel-helper-function-name "^6.24.1" + babel-helper-optimise-call-expression "^6.24.1" + babel-helper-replace-supers "^6.24.1" + babel-messages "^6.23.0" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-computed-properties@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-computed-properties/-/babel-plugin-transform-es2015-computed-properties-6.24.1.tgz#6fe2a8d16895d5634f4cd999b6d3480a308159b3" + dependencies: + babel-runtime "^6.22.0" + babel-template "^6.24.1" + +babel-plugin-transform-es2015-destructuring@^6.22.0: + version "6.23.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-destructuring/-/babel-plugin-transform-es2015-destructuring-6.23.0.tgz#997bb1f1ab967f682d2b0876fe358d60e765c56d" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-duplicate-keys@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-duplicate-keys/-/babel-plugin-transform-es2015-duplicate-keys-6.24.1.tgz#73eb3d310ca969e3ef9ec91c53741a6f1576423e" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-for-of@^6.22.0: + version "6.23.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-for-of/-/babel-plugin-transform-es2015-for-of-6.23.0.tgz#f47c95b2b613df1d3ecc2fdb7573623c75248691" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-function-name@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-function-name/-/babel-plugin-transform-es2015-function-name-6.24.1.tgz#834c89853bc36b1af0f3a4c5dbaa94fd8eacaa8b" + dependencies: + babel-helper-function-name "^6.24.1" + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-literals@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-literals/-/babel-plugin-transform-es2015-literals-6.22.0.tgz#4f54a02d6cd66cf915280019a31d31925377ca2e" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-modules-amd@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-amd/-/babel-plugin-transform-es2015-modules-amd-6.24.1.tgz#3b3e54017239842d6d19c3011c4bd2f00a00d154" + dependencies: + babel-plugin-transform-es2015-modules-commonjs "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + +babel-plugin-transform-es2015-modules-commonjs@^6.24.1: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-commonjs/-/babel-plugin-transform-es2015-modules-commonjs-6.26.0.tgz#0d8394029b7dc6abe1a97ef181e00758dd2e5d8a" + dependencies: + babel-plugin-transform-strict-mode "^6.24.1" + babel-runtime "^6.26.0" + babel-template "^6.26.0" + babel-types "^6.26.0" + +babel-plugin-transform-es2015-modules-systemjs@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-systemjs/-/babel-plugin-transform-es2015-modules-systemjs-6.24.1.tgz#ff89a142b9119a906195f5f106ecf305d9407d23" + dependencies: + babel-helper-hoist-variables "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + +babel-plugin-transform-es2015-modules-umd@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-umd/-/babel-plugin-transform-es2015-modules-umd-6.24.1.tgz#ac997e6285cd18ed6176adb607d602344ad38468" + dependencies: + babel-plugin-transform-es2015-modules-amd "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + +babel-plugin-transform-es2015-object-super@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-object-super/-/babel-plugin-transform-es2015-object-super-6.24.1.tgz#24cef69ae21cb83a7f8603dad021f572eb278f8d" + dependencies: + babel-helper-replace-supers "^6.24.1" + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-parameters@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-parameters/-/babel-plugin-transform-es2015-parameters-6.24.1.tgz#57ac351ab49caf14a97cd13b09f66fdf0a625f2b" + dependencies: + babel-helper-call-delegate "^6.24.1" + babel-helper-get-function-arity "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-shorthand-properties@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-shorthand-properties/-/babel-plugin-transform-es2015-shorthand-properties-6.24.1.tgz#24f875d6721c87661bbd99a4622e51f14de38aa0" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-spread@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-spread/-/babel-plugin-transform-es2015-spread-6.22.0.tgz#d6d68a99f89aedc4536c81a542e8dd9f1746f8d1" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-sticky-regex@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-sticky-regex/-/babel-plugin-transform-es2015-sticky-regex-6.24.1.tgz#00c1cdb1aca71112cdf0cf6126c2ed6b457ccdbc" + dependencies: + babel-helper-regex "^6.24.1" + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-template-literals@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-template-literals/-/babel-plugin-transform-es2015-template-literals-6.22.0.tgz#a84b3450f7e9f8f1f6839d6d687da84bb1236d8d" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-typeof-symbol@^6.22.0: + version "6.23.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-typeof-symbol/-/babel-plugin-transform-es2015-typeof-symbol-6.23.0.tgz#dec09f1cddff94b52ac73d505c84df59dcceb372" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-unicode-regex@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-unicode-regex/-/babel-plugin-transform-es2015-unicode-regex-6.24.1.tgz#d38b12f42ea7323f729387f18a7c5ae1faeb35e9" + dependencies: + babel-helper-regex "^6.24.1" + babel-runtime "^6.22.0" + regexpu-core "^2.0.0" + +babel-plugin-transform-exponentiation-operator@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-exponentiation-operator/-/babel-plugin-transform-exponentiation-operator-6.24.1.tgz#2ab0c9c7f3098fa48907772bb813fe41e8de3a0e" + dependencies: + babel-helper-builder-binary-assignment-operator-visitor "^6.24.1" + babel-plugin-syntax-exponentiation-operator "^6.8.0" + babel-runtime "^6.22.0" + +babel-plugin-transform-regenerator@^6.24.1: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-regenerator/-/babel-plugin-transform-regenerator-6.26.0.tgz#e0703696fbde27f0a3efcacf8b4dca2f7b3a8f2f" + dependencies: + regenerator-transform "^0.10.0" + +babel-plugin-transform-strict-mode@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-strict-mode/-/babel-plugin-transform-strict-mode-6.24.1.tgz#d5faf7aa578a65bbe591cf5edae04a0c67020758" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-polyfill@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-polyfill/-/babel-polyfill-6.26.0.tgz#379937abc67d7895970adc621f284cd966cf2153" + integrity sha1-N5k3q8Z9eJWXCtxiHyhM2WbPIVM= + dependencies: + babel-runtime "^6.26.0" + core-js "^2.5.0" + regenerator-runtime "^0.10.5" + +babel-preset-es2015@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-preset-es2015/-/babel-preset-es2015-6.24.1.tgz#d44050d6bc2c9feea702aaf38d727a0210538939" + dependencies: + babel-plugin-check-es2015-constants "^6.22.0" + babel-plugin-transform-es2015-arrow-functions "^6.22.0" + babel-plugin-transform-es2015-block-scoped-functions "^6.22.0" + babel-plugin-transform-es2015-block-scoping "^6.24.1" + babel-plugin-transform-es2015-classes "^6.24.1" + babel-plugin-transform-es2015-computed-properties "^6.24.1" + babel-plugin-transform-es2015-destructuring "^6.22.0" + babel-plugin-transform-es2015-duplicate-keys "^6.24.1" + babel-plugin-transform-es2015-for-of "^6.22.0" + babel-plugin-transform-es2015-function-name "^6.24.1" + babel-plugin-transform-es2015-literals "^6.22.0" + babel-plugin-transform-es2015-modules-amd "^6.24.1" + babel-plugin-transform-es2015-modules-commonjs "^6.24.1" + babel-plugin-transform-es2015-modules-systemjs "^6.24.1" + babel-plugin-transform-es2015-modules-umd "^6.24.1" + babel-plugin-transform-es2015-object-super "^6.24.1" + babel-plugin-transform-es2015-parameters "^6.24.1" + babel-plugin-transform-es2015-shorthand-properties "^6.24.1" + babel-plugin-transform-es2015-spread "^6.22.0" + babel-plugin-transform-es2015-sticky-regex "^6.24.1" + babel-plugin-transform-es2015-template-literals "^6.22.0" + babel-plugin-transform-es2015-typeof-symbol "^6.22.0" + babel-plugin-transform-es2015-unicode-regex "^6.24.1" + babel-plugin-transform-regenerator "^6.24.1" + +babel-preset-es2016@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-preset-es2016/-/babel-preset-es2016-6.24.1.tgz#f900bf93e2ebc0d276df9b8ab59724ebfd959f8b" + dependencies: + babel-plugin-transform-exponentiation-operator "^6.24.1" + +babel-preset-es2017@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-preset-es2017/-/babel-preset-es2017-6.24.1.tgz#597beadfb9f7f208bcfd8a12e9b2b29b8b2f14d1" + dependencies: + babel-plugin-syntax-trailing-function-commas "^6.22.0" + babel-plugin-transform-async-to-generator "^6.24.1" + +babel-preset-latest@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-preset-latest/-/babel-preset-latest-6.24.1.tgz#677de069154a7485c2d25c577c02f624b85b85e8" + dependencies: + babel-preset-es2015 "^6.24.1" + babel-preset-es2016 "^6.24.1" + babel-preset-es2017 "^6.24.1" + +babel-register@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-register/-/babel-register-6.26.0.tgz#6ed021173e2fcb486d7acb45c6009a856f647071" + integrity sha1-btAhFz4vy0htestFxgCahW9kcHE= + dependencies: + babel-core "^6.26.0" + babel-runtime "^6.26.0" + core-js "^2.5.0" + home-or-tmp "^2.0.0" + lodash "^4.17.4" + mkdirp "^0.5.1" + source-map-support "^0.4.15" + +babel-runtime@^6.18.0, babel-runtime@^6.22.0, babel-runtime@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe" + integrity sha1-llxwWGaOgrVde/4E/yM3vItWR/4= + dependencies: + core-js "^2.4.0" + regenerator-runtime "^0.11.0" + +babel-template@^6.24.1, babel-template@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-template/-/babel-template-6.26.0.tgz#de03e2d16396b069f46dd9fff8521fb1a0e35e02" + integrity sha1-3gPi0WOWsGn0bdn/+FIfsaDjXgI= + dependencies: + babel-runtime "^6.26.0" + babel-traverse "^6.26.0" + babel-types "^6.26.0" + babylon "^6.18.0" + lodash "^4.17.4" + +babel-traverse@^6.24.1, babel-traverse@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-traverse/-/babel-traverse-6.26.0.tgz#46a9cbd7edcc62c8e5c064e2d2d8d0f4035766ee" + dependencies: + babel-code-frame "^6.26.0" + babel-messages "^6.23.0" + babel-runtime "^6.26.0" + babel-types "^6.26.0" + babylon "^6.18.0" + debug "^2.6.8" + globals "^9.18.0" + invariant "^2.2.2" + lodash "^4.17.4" + +babel-types@^6.19.0, babel-types@^6.24.1, babel-types@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-types/-/babel-types-6.26.0.tgz#a3b073f94ab49eb6fa55cd65227a334380632497" + dependencies: + babel-runtime "^6.26.0" + esutils "^2.0.2" + lodash "^4.17.4" + to-fast-properties "^1.0.3" + +babylon@^6.18.0: + version "6.18.0" + resolved "https://registry.yarnpkg.com/babylon/-/babylon-6.18.0.tgz#af2f3b88fa6f5c1e4c634d1a0f8eac4f55b395e3" + integrity sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ== + +balanced-match@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" + integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= + +base@^0.11.1: + version "0.11.2" + resolved "https://registry.yarnpkg.com/base/-/base-0.11.2.tgz#7bde5ced145b6d551a90db87f83c558b4eb48a8f" + integrity sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg== + dependencies: + cache-base "^1.0.1" + class-utils "^0.3.5" + component-emitter "^1.2.1" + define-property "^1.0.0" + isobject "^3.0.1" + mixin-deep "^1.2.0" + pascalcase "^0.1.1" + +binary-extensions@^1.0.0: + version "1.13.1" + resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.13.1.tgz#598afe54755b2868a5330d2aff9d4ebb53209b65" + integrity sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw== + +binary-extensions@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.1.0.tgz#30fa40c9e7fe07dbc895678cd287024dea241dd9" + integrity sha512-1Yj8h9Q+QDF5FzhMs/c9+6UntbD5MkRfRwac8DoEm9ZfUBZ7tZ55YcGVAzEe4bXsdQHEk+s9S5wsOKVdZrw0tQ== + +bindings@^1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz#10353c9e945334bc0511a6d90b38fbc7c9c504df" + integrity sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ== + dependencies: + file-uri-to-path "1.0.0" + +brace-expansion@^1.1.7: + version "1.1.11" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" + integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== + dependencies: + balanced-match "^1.0.0" + concat-map "0.0.1" + +braces@^1.8.2: + version "1.8.5" + resolved "https://registry.yarnpkg.com/braces/-/braces-1.8.5.tgz#ba77962e12dff969d6b76711e914b737857bf6a7" + integrity sha1-uneWLhLf+WnWt2cR6RS3N4V79qc= + dependencies: + expand-range "^1.8.1" + preserve "^0.2.0" + repeat-element "^1.1.2" + +braces@^2.3.1: + version "2.3.2" + resolved "https://registry.yarnpkg.com/braces/-/braces-2.3.2.tgz#5979fd3f14cd531565e5fa2df1abfff1dfaee729" + integrity sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w== + dependencies: + arr-flatten "^1.1.0" + array-unique "^0.3.2" + extend-shallow "^2.0.1" + fill-range "^4.0.0" + isobject "^3.0.1" + repeat-element "^1.1.2" + snapdragon "^0.8.1" + snapdragon-node "^2.0.1" + split-string "^3.0.2" + to-regex "^3.0.1" + +braces@~3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" + integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== + dependencies: + fill-range "^7.0.1" + +browser-resolve@^1.11.0: + version "1.11.2" + resolved "https://registry.yarnpkg.com/browser-resolve/-/browser-resolve-1.11.2.tgz#8ff09b0a2c421718a1051c260b32e48f442938ce" + dependencies: + resolve "1.1.7" + +browser-stdout@1.3.1: + version "1.3.1" + resolved "https://registry.yarnpkg.com/browser-stdout/-/browser-stdout-1.3.1.tgz#baa559ee14ced73452229bad7326467c61fabd60" + integrity sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw== + +buffer-crc32@^0.2.5: + version "0.2.13" + resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242" + +builtin-modules@^1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f" + +cache-base@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/cache-base/-/cache-base-1.0.1.tgz#0a7f46416831c8b662ee36fe4e7c59d76f666ab2" + integrity sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ== + dependencies: + collection-visit "^1.0.0" + component-emitter "^1.2.1" + get-value "^2.0.6" + has-value "^1.0.0" + isobject "^3.0.1" + set-value "^2.0.0" + to-object-path "^0.3.0" + union-value "^1.0.0" + unset-value "^1.0.0" + +camelcase@^1.0.2: + version "1.2.1" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39" + +camelcase@^5.0.0: + version "5.3.1" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" + integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== + +camelcase@^6.0.0: + version "6.2.0" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.2.0.tgz#924af881c9d525ac9d87f40d964e5cea982a1809" + integrity sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg== + +center-align@^0.1.1: + version "0.1.3" + resolved "https://registry.yarnpkg.com/center-align/-/center-align-0.1.3.tgz#aa0d32629b6ee972200411cbd4461c907bc2b7ad" + dependencies: + align-text "^0.1.3" + lazy-cache "^1.0.3" + +chalk@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" + integrity sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg= + dependencies: + ansi-styles "^2.2.1" + escape-string-regexp "^1.0.2" + has-ansi "^2.0.0" + strip-ansi "^3.0.0" + supports-color "^2.0.0" + +chalk@^4.0.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.0.tgz#4e14870a618d9e2edd97dd8345fd9d9dc315646a" + integrity sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A== + dependencies: + ansi-styles "^4.1.0" + supports-color "^7.1.0" + +chokidar@3.4.3: + version "3.4.3" + resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.4.3.tgz#c1df38231448e45ca4ac588e6c79573ba6a57d5b" + integrity sha512-DtM3g7juCXQxFVSNPNByEC2+NImtBuxQQvWlHunpJIS5Ocr0lG306cC7FCi7cEA0fzmybPUIl4txBIobk1gGOQ== + dependencies: + anymatch "~3.1.1" + braces "~3.0.2" + glob-parent "~5.1.0" + is-binary-path "~2.1.0" + is-glob "~4.0.1" + normalize-path "~3.0.0" + readdirp "~3.5.0" + optionalDependencies: + fsevents "~2.1.2" + +chokidar@^1.6.1: + version "1.7.0" + resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-1.7.0.tgz#798e689778151c8076b4b360e5edd28cda2bb468" + integrity sha1-eY5ol3gVHIB2tLNg5e3SjNortGg= + dependencies: + anymatch "^1.3.0" + async-each "^1.0.0" + glob-parent "^2.0.0" + inherits "^2.0.1" + is-binary-path "^1.0.0" + is-glob "^2.0.0" + path-is-absolute "^1.0.0" + readdirp "^2.0.0" + optionalDependencies: + fsevents "^1.0.0" + +class-utils@^0.3.5: + version "0.3.6" + resolved "https://registry.yarnpkg.com/class-utils/-/class-utils-0.3.6.tgz#f93369ae8b9a7ce02fd41faad0ca83033190c463" + integrity sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg== + dependencies: + arr-union "^3.1.0" + define-property "^0.2.5" + isobject "^3.0.0" + static-extend "^0.1.1" + +cliui@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-2.1.0.tgz#4b475760ff80264c762c3a1719032e91c7fea0d1" + dependencies: + center-align "^0.1.1" + right-align "^0.1.1" + wordwrap "0.0.2" + +cliui@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-5.0.0.tgz#deefcfdb2e800784aa34f46fa08e06851c7bbbc5" + integrity sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA== + dependencies: + string-width "^3.1.0" + strip-ansi "^5.2.0" + wrap-ansi "^5.1.0" + +collection-visit@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/collection-visit/-/collection-visit-1.0.0.tgz#4bc0373c164bc3291b4d368c829cf1a80a59dca0" + integrity sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA= + dependencies: + map-visit "^1.0.0" + object-visit "^1.0.0" + +color-convert@^1.9.0: + version "1.9.3" + resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" + integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== + dependencies: + color-name "1.1.3" + +color-convert@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" + integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== + dependencies: + color-name "~1.1.4" + +color-name@1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" + integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= + +color-name@~1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" + integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== + +commander@^2.11.0: + version "2.20.3" + resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" + integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== + +component-emitter@^1.2.1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz#16e4070fba8ae29b679f2215853ee181ab2eabc0" + integrity sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg== + +concat-map@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" + integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= + +convert-source-map@^1.5.0, convert-source-map@^1.5.1: + version "1.7.0" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.7.0.tgz#17a2cb882d7f77d3490585e2ce6c524424a3a442" + integrity sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA== + dependencies: + safe-buffer "~5.1.1" + +copy-descriptor@^0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/copy-descriptor/-/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d" + integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40= + +core-js@^2.4.0, core-js@^2.5.0: + version "2.6.12" + resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.6.12.tgz#d9333dfa7b065e347cc5682219d6f690859cc2ec" + integrity sha512-Kb2wC0fvsWfQrgk8HU5lW6U/Lcs8+9aaYcy4ZFc6DDlo4nZ7n70dEgE5rtR0oG6ufKDUnrwfWL1mXR5ljDatrQ== + +core-util-is@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" + integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= + +debug@4.2.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.2.0.tgz#7f150f93920e94c58f5574c2fd01a3110effe7f1" + integrity sha512-IX2ncY78vDTjZMFUdmsvIRFY2Cf4FnD0wRs+nQwJU8Lu99/tPFdb0VybiiMTPe3I6rQmwsqQqRBvxU+bZ/I8sg== + dependencies: + ms "2.1.2" + +debug@^2.2.0, debug@^2.3.3, debug@^2.6.8, debug@^2.6.9: + version "2.6.9" + resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" + integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== + dependencies: + ms "2.0.0" + +decamelize@^1.0.0, decamelize@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" + +decamelize@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-4.0.0.tgz#aa472d7bf660eb15f3494efd531cab7f2a709837" + integrity sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ== + +decode-uri-component@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545" + integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU= + +define-property@^0.2.5: + version "0.2.5" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-0.2.5.tgz#c35b1ef918ec3c990f9a5bc57be04aacec5c8116" + integrity sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY= + dependencies: + is-descriptor "^0.1.0" + +define-property@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-1.0.0.tgz#769ebaaf3f4a63aad3af9e8d304c9bbe79bfb0e6" + integrity sha1-dp66rz9KY6rTr56NMEybvnm/sOY= + dependencies: + is-descriptor "^1.0.0" + +define-property@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-2.0.2.tgz#d459689e8d654ba77e02a817f8710d702cb16e9d" + integrity sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ== + dependencies: + is-descriptor "^1.0.2" + isobject "^3.0.1" + +detect-indent@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/detect-indent/-/detect-indent-4.0.0.tgz#f76d064352cdf43a1cb6ce619c4ee3a9475de208" + integrity sha1-920GQ1LN9Docts5hnE7jqUdd4gg= + dependencies: + repeating "^2.0.0" + +diff@4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d" + integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== + +emoji-regex@^7.0.1: + version "7.0.3" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156" + integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA== + +es6-promise@^3.1.2: + version "3.3.1" + resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-3.3.1.tgz#a08cdde84ccdbf34d027a1451bc91d4bcd28a613" + +escape-string-regexp@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" + integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== + +escape-string-regexp@^1.0.2: + version "1.0.5" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" + integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= + +esprima@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" + integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== + +estree-walker@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/estree-walker/-/estree-walker-0.2.1.tgz#bdafe8095383d8414d5dc2ecf4c9173b6db9412e" + +esutils@^2.0.2: + version "2.0.3" + resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" + integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== + +expand-brackets@^0.1.4: + version "0.1.5" + resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-0.1.5.tgz#df07284e342a807cd733ac5af72411e581d1177b" + integrity sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s= + dependencies: + is-posix-bracket "^0.1.0" + +expand-brackets@^2.1.4: + version "2.1.4" + resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-2.1.4.tgz#b77735e315ce30f6b6eff0f83b04151a22449622" + integrity sha1-t3c14xXOMPa27/D4OwQVGiJEliI= + dependencies: + debug "^2.3.3" + define-property "^0.2.5" + extend-shallow "^2.0.1" + posix-character-classes "^0.1.0" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.1" + +expand-range@^1.8.1: + version "1.8.2" + resolved "https://registry.yarnpkg.com/expand-range/-/expand-range-1.8.2.tgz#a299effd335fe2721ebae8e257ec79644fc85337" + integrity sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc= + dependencies: + fill-range "^2.1.0" + +extend-shallow@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f" + integrity sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8= + dependencies: + is-extendable "^0.1.0" + +extend-shallow@^3.0.0, extend-shallow@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-3.0.2.tgz#26a71aaf073b39fb2127172746131c2704028db8" + integrity sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg= + dependencies: + assign-symbols "^1.0.0" + is-extendable "^1.0.1" + +extglob@^0.3.1: + version "0.3.2" + resolved "https://registry.yarnpkg.com/extglob/-/extglob-0.3.2.tgz#2e18ff3d2f49ab2765cec9023f011daa8d8349a1" + integrity sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE= + dependencies: + is-extglob "^1.0.0" + +extglob@^2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/extglob/-/extglob-2.0.4.tgz#ad00fe4dc612a9232e8718711dc5cb5ab0285543" + integrity sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw== + dependencies: + array-unique "^0.3.2" + define-property "^1.0.0" + expand-brackets "^2.1.4" + extend-shallow "^2.0.1" + fragment-cache "^0.2.1" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.1" + +file-uri-to-path@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz#553a7b8446ff6f684359c445f1e37a05dacc33dd" + integrity sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw== + +filename-regex@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/filename-regex/-/filename-regex-2.0.1.tgz#c1c4b9bee3e09725ddb106b75c1e301fe2f18b26" + integrity sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY= + +fill-range@^2.1.0: + version "2.2.4" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-2.2.4.tgz#eb1e773abb056dcd8df2bfdf6af59b8b3a936565" + integrity sha512-cnrcCbj01+j2gTG921VZPnHbjmdAf8oQV/iGeV2kZxGSyfYjjTyY79ErsK1WJWMpw6DaApEX72binqJE+/d+5Q== + dependencies: + is-number "^2.1.0" + isobject "^2.0.0" + randomatic "^3.0.0" + repeat-element "^1.1.2" + repeat-string "^1.5.2" + +fill-range@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7" + integrity sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc= + dependencies: + extend-shallow "^2.0.1" + is-number "^3.0.0" + repeat-string "^1.6.1" + to-regex-range "^2.1.0" + +fill-range@^7.0.1: + version "7.0.1" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" + integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== + dependencies: + to-regex-range "^5.0.1" + +find-up@5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-5.0.0.tgz#4c92819ecb7083561e4f4a240a86be5198f536fc" + integrity sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng== + dependencies: + locate-path "^6.0.0" + path-exists "^4.0.0" + +find-up@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73" + integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg== + dependencies: + locate-path "^3.0.0" + +flat@^5.0.2: + version "5.0.2" + resolved "https://registry.yarnpkg.com/flat/-/flat-5.0.2.tgz#8ca6fe332069ffa9d324c327198c598259ceb241" + integrity sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ== + +for-in@^1.0.1, for-in@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80" + integrity sha1-gQaNKVqBQuwKxybG4iAMMPttXoA= + +for-own@^0.1.4: + version "0.1.5" + resolved "https://registry.yarnpkg.com/for-own/-/for-own-0.1.5.tgz#5265c681a4f294dabbf17c9509b6763aa84510ce" + integrity sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4= + dependencies: + for-in "^1.0.1" + +fragment-cache@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19" + integrity sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk= + dependencies: + map-cache "^0.2.2" + +fs-readdir-recursive@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/fs-readdir-recursive/-/fs-readdir-recursive-1.1.0.tgz#e32fc030a2ccee44a6b5371308da54be0b397d27" + integrity sha512-GNanXlVr2pf02+sPN40XN8HG+ePaNcvM0q5mZBd668Obwb0yD5GiUbZOFgwn8kGMY6I3mdyDJzieUy3PTYyTRA== + +fs.realpath@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" + integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= + +fsevents@^1.0.0: + version "1.2.13" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.13.tgz#f325cb0455592428bcf11b383370ef70e3bfcc38" + integrity sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw== + dependencies: + bindings "^1.5.0" + nan "^2.12.1" + +fsevents@~2.1.2: + version "2.1.3" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.1.3.tgz#fb738703ae8d2f9fe900c33836ddebee8b97f23e" + integrity sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ== + +get-caller-file@^2.0.1: + version "2.0.5" + resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" + integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== + +get-value@^2.0.3, get-value@^2.0.6: + version "2.0.6" + resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28" + integrity sha1-3BXKHGcjh8p2vTesCjlbogQqLCg= + +glob-base@^0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/glob-base/-/glob-base-0.3.0.tgz#dbb164f6221b1c0b1ccf82aea328b497df0ea3c4" + integrity sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q= + dependencies: + glob-parent "^2.0.0" + is-glob "^2.0.0" + +glob-parent@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-2.0.0.tgz#81383d72db054fcccf5336daa902f182f6edbb28" + integrity sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg= + dependencies: + is-glob "^2.0.0" + +glob-parent@~5.1.0: + version "5.1.1" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.1.tgz#b6c1ef417c4e5663ea498f1c45afac6916bbc229" + integrity sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ== + dependencies: + is-glob "^4.0.1" + +glob@7.1.6, glob@^7.1.2, glob@^7.1.3: + version "7.1.6" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" + integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^3.0.4" + once "^1.3.0" + path-is-absolute "^1.0.0" + +globals@^9.18.0: + version "9.18.0" + resolved "https://registry.yarnpkg.com/globals/-/globals-9.18.0.tgz#aa3896b3e69b487f17e31ed2143d69a8e30c2d8a" + integrity sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ== + +graceful-fs@^4.1.11, graceful-fs@^4.1.4: + version "4.2.4" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb" + integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw== + +graceful-fs@^4.1.3: + version "4.2.3" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.3.tgz#4a12ff1b60376ef09862c2093edd908328be8423" + +growl@1.10.5: + version "1.10.5" + resolved "https://registry.yarnpkg.com/growl/-/growl-1.10.5.tgz#f2735dc2283674fa67478b10181059355c369e5e" + integrity sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA== + +has-ansi@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" + integrity sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE= + dependencies: + ansi-regex "^2.0.0" + +has-flag@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" + integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== + +has-value@^0.3.1: + version "0.3.1" + resolved "https://registry.yarnpkg.com/has-value/-/has-value-0.3.1.tgz#7b1f58bada62ca827ec0a2078025654845995e1f" + integrity sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8= + dependencies: + get-value "^2.0.3" + has-values "^0.1.4" + isobject "^2.0.0" + +has-value@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/has-value/-/has-value-1.0.0.tgz#18b281da585b1c5c51def24c930ed29a0be6b177" + integrity sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc= + dependencies: + get-value "^2.0.6" + has-values "^1.0.0" + isobject "^3.0.0" + +has-values@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/has-values/-/has-values-0.1.4.tgz#6d61de95d91dfca9b9a02089ad384bff8f62b771" + integrity sha1-bWHeldkd/Km5oCCJrThL/49it3E= + +has-values@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/has-values/-/has-values-1.0.0.tgz#95b0b63fec2146619a6fe57fe75628d5a39efe4f" + integrity sha1-lbC2P+whRmGab+V/51Yo1aOe/k8= + dependencies: + is-number "^3.0.0" + kind-of "^4.0.0" + +he@1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f" + integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw== + +home-or-tmp@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/home-or-tmp/-/home-or-tmp-2.0.0.tgz#e36c3f2d2cae7d746a857e38d18d5f32a7882db8" + integrity sha1-42w/LSyufXRqhX440Y1fMqeILbg= + dependencies: + os-homedir "^1.0.0" + os-tmpdir "^1.0.1" + +inflight@^1.0.4: + version "1.0.6" + resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= + dependencies: + once "^1.3.0" + wrappy "1" + +inherits@2, inherits@^2.0.1, inherits@~2.0.3: + version "2.0.4" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" + integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== + +invariant@^2.2.2: + version "2.2.4" + resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.4.tgz#610f3c92c9359ce1db616e538008d23ff35158e6" + integrity sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA== + dependencies: + loose-envify "^1.0.0" + +is-accessor-descriptor@^0.1.6: + version "0.1.6" + resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6" + integrity sha1-qeEss66Nh2cn7u84Q/igiXtcmNY= + dependencies: + kind-of "^3.0.2" + +is-accessor-descriptor@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz#169c2f6d3df1f992618072365c9b0ea1f6878656" + integrity sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ== + dependencies: + kind-of "^6.0.0" + +is-binary-path@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898" + integrity sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg= + dependencies: + binary-extensions "^1.0.0" + +is-binary-path@~2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09" + integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw== + dependencies: + binary-extensions "^2.0.0" + +is-buffer@^1.1.5: + version "1.1.6" + resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" + integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== + +is-data-descriptor@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz#0b5ee648388e2c860282e793f1856fec3f301b56" + integrity sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y= + dependencies: + kind-of "^3.0.2" + +is-data-descriptor@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz#d84876321d0e7add03990406abbbbd36ba9268c7" + integrity sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ== + dependencies: + kind-of "^6.0.0" + +is-descriptor@^0.1.0: + version "0.1.6" + resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca" + integrity sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg== + dependencies: + is-accessor-descriptor "^0.1.6" + is-data-descriptor "^0.1.4" + kind-of "^5.0.0" + +is-descriptor@^1.0.0, is-descriptor@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.2.tgz#3b159746a66604b04f8c81524ba365c5f14d86ec" + integrity sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg== + dependencies: + is-accessor-descriptor "^1.0.0" + is-data-descriptor "^1.0.0" + kind-of "^6.0.2" + +is-dotfile@^1.0.0: + version "1.0.3" + resolved "https://registry.yarnpkg.com/is-dotfile/-/is-dotfile-1.0.3.tgz#a6a2f32ffd2dfb04f5ca25ecd0f6b83cf798a1e1" + integrity sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE= + +is-equal-shallow@^0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz#2238098fc221de0bcfa5d9eac4c45d638aa1c534" + integrity sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ= + dependencies: + is-primitive "^2.0.0" + +is-extendable@^0.1.0, is-extendable@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89" + integrity sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik= + +is-extendable@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-1.0.1.tgz#a7470f9e426733d81bd81e1155264e3a3507cab4" + integrity sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA== + dependencies: + is-plain-object "^2.0.4" + +is-extglob@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-1.0.0.tgz#ac468177c4943405a092fc8f29760c6ffc6206c0" + integrity sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA= + +is-extglob@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" + integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= + +is-finite@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/is-finite/-/is-finite-1.1.0.tgz#904135c77fb42c0641d6aa1bcdbc4daa8da082f3" + integrity sha512-cdyMtqX/BOqqNBBiKlIVkytNHm49MtMlYyn1zxzvJKWmFMlGzm+ry5BBfYyeY9YmNKbRSo/o7OX9w9ale0wg3w== + +is-fullwidth-code-point@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" + integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8= + +is-glob@^2.0.0, is-glob@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-2.0.1.tgz#d096f926a3ded5600f3fdfd91198cb0888c2d863" + integrity sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM= + dependencies: + is-extglob "^1.0.0" + +is-glob@^4.0.1, is-glob@~4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" + integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== + dependencies: + is-extglob "^2.1.1" + +is-number@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-2.1.0.tgz#01fcbbb393463a548f2f466cce16dece49db908f" + integrity sha1-Afy7s5NGOlSPL0ZszhbezknbkI8= + dependencies: + kind-of "^3.0.2" + +is-number@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195" + integrity sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU= + dependencies: + kind-of "^3.0.2" + +is-number@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-4.0.0.tgz#0026e37f5454d73e356dfe6564699867c6a7f0ff" + integrity sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ== + +is-number@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" + integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== + +is-plain-obj@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-2.1.0.tgz#45e42e37fccf1f40da8e5f76ee21515840c09287" + integrity sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA== + +is-plain-object@^2.0.3, is-plain-object@^2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" + integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== + dependencies: + isobject "^3.0.1" + +is-posix-bracket@^0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz#3334dc79774368e92f016e6fbc0a88f5cd6e6bc4" + integrity sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q= + +is-primitive@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/is-primitive/-/is-primitive-2.0.0.tgz#207bab91638499c07b2adf240a41a87210034575" + integrity sha1-IHurkWOEmcB7Kt8kCkGochADRXU= + +is-windows@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d" + integrity sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA== + +isarray@1.0.0, isarray@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" + integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= + +isexe@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" + integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= + +isobject@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89" + integrity sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk= + dependencies: + isarray "1.0.0" + +isobject@^3.0.0, isobject@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" + integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= + +"js-tokens@^3.0.0 || ^4.0.0": + version "4.0.0" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" + integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== + +js-tokens@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b" + integrity sha1-mGbfOVECEw449/mWvOtlRDIJwls= + +js-yaml@3.14.0: + version "3.14.0" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.0.tgz#a7a34170f26a21bb162424d8adacb4113a69e482" + integrity sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A== + dependencies: + argparse "^1.0.7" + esprima "^4.0.0" + +jsesc@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-1.3.0.tgz#46c3fec8c1892b12b0833db9bc7622176dbab34b" + integrity sha1-RsP+yMGJKxKwgz25vHYiF226s0s= + +jsesc@~0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-0.5.0.tgz#e7dee66e35d6fc16f710fe91d5cf69f70f08911d" + +json5@^0.5.1: + version "0.5.1" + resolved "https://registry.yarnpkg.com/json5/-/json5-0.5.1.tgz#1eade7acc012034ad84e2396767ead9fa5495821" + integrity sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE= + +kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0: + version "3.2.2" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" + integrity sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ= + dependencies: + is-buffer "^1.1.5" + +kind-of@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57" + integrity sha1-IIE989cSkosgc3hpGkUGb65y3Vc= + dependencies: + is-buffer "^1.1.5" + +kind-of@^5.0.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d" + integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw== + +kind-of@^6.0.0, kind-of@^6.0.2: + version "6.0.3" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" + integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== + +lazy-cache@^1.0.3: + version "1.0.4" + resolved "https://registry.yarnpkg.com/lazy-cache/-/lazy-cache-1.0.4.tgz#a1d78fc3a50474cb80845d3b3b6e1da49a446e8e" + +locate-path@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-3.0.0.tgz#dbec3b3ab759758071b58fe59fc41871af21400e" + integrity sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A== + dependencies: + p-locate "^3.0.0" + path-exists "^3.0.0" + +locate-path@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-6.0.0.tgz#55321eb309febbc59c4801d931a72452a681d286" + integrity sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw== + dependencies: + p-locate "^5.0.0" + +lodash@^4.17.4: + version "4.17.20" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.20.tgz#b44a9b6297bcb698f1c51a3545a2b3b368d59c52" + integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA== + +log-symbols@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.0.0.tgz#69b3cc46d20f448eccdb75ea1fa733d9e821c920" + integrity sha512-FN8JBzLx6CzeMrB0tg6pqlGU1wCrXW+ZXGH481kfsBqer0hToTIiHdjH4Mq8xJUbvATujKCvaREGWpGUionraA== + dependencies: + chalk "^4.0.0" + +longest@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097" + +loose-envify@^1.0.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" + integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q== + dependencies: + js-tokens "^3.0.0 || ^4.0.0" + +map-cache@^0.2.2: + version "0.2.2" + resolved "https://registry.yarnpkg.com/map-cache/-/map-cache-0.2.2.tgz#c32abd0bd6525d9b051645bb4f26ac5dc98a0dbf" + integrity sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8= + +map-visit@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/map-visit/-/map-visit-1.0.0.tgz#ecdca8f13144e660f1b5bd41f12f3479d98dfb8f" + integrity sha1-7Nyo8TFE5mDxtb1B8S80edmN+48= + dependencies: + object-visit "^1.0.0" + +math-random@^1.0.1: + version "1.0.4" + resolved "https://registry.yarnpkg.com/math-random/-/math-random-1.0.4.tgz#5dd6943c938548267016d4e34f057583080c514c" + integrity sha512-rUxjysqif/BZQH2yhd5Aaq7vXMSx9NdEsQcyA07uEzIvxgI7zIr33gGsh+RU0/XjmQpCW7RsVof1vlkvQVCK5A== + +micromatch@^2.1.5: + version "2.3.11" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-2.3.11.tgz#86677c97d1720b363431d04d0d15293bd38c1565" + integrity sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU= + dependencies: + arr-diff "^2.0.0" + array-unique "^0.2.1" + braces "^1.8.2" + expand-brackets "^0.1.4" + extglob "^0.3.1" + filename-regex "^2.0.0" + is-extglob "^1.0.0" + is-glob "^2.0.1" + kind-of "^3.0.2" + normalize-path "^2.0.1" + object.omit "^2.0.0" + parse-glob "^3.0.4" + regex-cache "^0.4.2" + +micromatch@^3.1.10: + version "3.1.10" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23" + integrity sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg== + dependencies: + arr-diff "^4.0.0" + array-unique "^0.3.2" + braces "^2.3.1" + define-property "^2.0.2" + extend-shallow "^3.0.2" + extglob "^2.0.4" + fragment-cache "^0.2.1" + kind-of "^6.0.2" + nanomatch "^1.2.9" + object.pick "^1.3.0" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.2" + +minimatch@3.0.4, minimatch@^3.0.2, minimatch@^3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" + dependencies: + brace-expansion "^1.1.7" + +minimist@^1.2.0, minimist@^1.2.5: + version "1.2.5" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602" + integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw== + +mixin-deep@^1.2.0: + version "1.3.2" + resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566" + integrity sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA== + dependencies: + for-in "^1.0.2" + is-extendable "^1.0.1" + +mkdirp@^0.5.1: + version "0.5.5" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def" + integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ== + dependencies: + minimist "^1.2.5" + +mocha-qunit-ui@^0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/mocha-qunit-ui/-/mocha-qunit-ui-0.1.3.tgz#e3e1ff1dac33222b10cef681efd7f82664141ea9" + +mocha@^8.2.1: + version "8.2.1" + resolved "https://registry.yarnpkg.com/mocha/-/mocha-8.2.1.tgz#f2fa68817ed0e53343d989df65ccd358bc3a4b39" + integrity sha512-cuLBVfyFfFqbNR0uUKbDGXKGk+UDFe6aR4os78XIrMQpZl/nv7JYHcvP5MFIAb374b2zFXsdgEGwmzMtP0Xg8w== + dependencies: + "@ungap/promise-all-settled" "1.1.2" + ansi-colors "4.1.1" + browser-stdout "1.3.1" + chokidar "3.4.3" + debug "4.2.0" + diff "4.0.2" + escape-string-regexp "4.0.0" + find-up "5.0.0" + glob "7.1.6" + growl "1.10.5" + he "1.2.0" + js-yaml "3.14.0" + log-symbols "4.0.0" + minimatch "3.0.4" + ms "2.1.2" + nanoid "3.1.12" + serialize-javascript "5.0.1" + strip-json-comments "3.1.1" + supports-color "7.2.0" + which "2.0.2" + wide-align "1.1.3" + workerpool "6.0.2" + yargs "13.3.2" + yargs-parser "13.1.2" + yargs-unparser "2.0.0" + +ms@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" + integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= + +ms@2.1.2: + version "2.1.2" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" + integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== + +nan@^2.12.1: + version "2.14.2" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.2.tgz#f5376400695168f4cc694ac9393d0c9585eeea19" + integrity sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ== + +nanoid@3.1.12: + version "3.1.12" + resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.1.12.tgz#6f7736c62e8d39421601e4a0c77623a97ea69654" + integrity sha512-1qstj9z5+x491jfiC4Nelk+f8XBad7LN20PmyWINJEMRSf3wcAjAWysw1qaA8z6NSKe2sjq1hRSDpBH5paCb6A== + +nanomatch@^1.2.9: + version "1.2.13" + resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119" + integrity sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA== + dependencies: + arr-diff "^4.0.0" + array-unique "^0.3.2" + define-property "^2.0.2" + extend-shallow "^3.0.2" + fragment-cache "^0.2.1" + is-windows "^1.0.2" + kind-of "^6.0.2" + object.pick "^1.3.0" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.1" + +normalize-path@^2.0.0, normalize-path@^2.0.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9" + integrity sha1-GrKLVW4Zg2Oowab35vogE3/mrtk= + dependencies: + remove-trailing-separator "^1.0.1" + +normalize-path@^3.0.0, normalize-path@~3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" + integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== + +object-assign@^4.1.0: + version "4.1.1" + resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" + integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= + +object-copy@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c" + integrity sha1-fn2Fi3gb18mRpBupde04EnVOmYw= + dependencies: + copy-descriptor "^0.1.0" + define-property "^0.2.5" + kind-of "^3.0.3" + +object-visit@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/object-visit/-/object-visit-1.0.1.tgz#f79c4493af0c5377b59fe39d395e41042dd045bb" + integrity sha1-95xEk68MU3e1n+OdOV5BBC3QRbs= + dependencies: + isobject "^3.0.0" + +object.omit@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/object.omit/-/object.omit-2.0.1.tgz#1a9c744829f39dbb858c76ca3579ae2a54ebd1fa" + integrity sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo= + dependencies: + for-own "^0.1.4" + is-extendable "^0.1.1" + +object.pick@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747" + integrity sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c= + dependencies: + isobject "^3.0.1" + +once@^1.3.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= + dependencies: + wrappy "1" + +os-homedir@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" + integrity sha1-/7xJiDNuDoM94MFox+8VISGqf7M= + +os-tmpdir@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" + integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= + +output-file-sync@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/output-file-sync/-/output-file-sync-1.1.2.tgz#d0a33eefe61a205facb90092e826598d5245ce76" + integrity sha1-0KM+7+YaIF+suQCS6CZZjVJFznY= + dependencies: + graceful-fs "^4.1.4" + mkdirp "^0.5.1" + object-assign "^4.1.0" + +p-limit@^2.0.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" + integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== + dependencies: + p-try "^2.0.0" + +p-limit@^3.0.2: + version "3.1.0" + resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-3.1.0.tgz#e1daccbe78d0d1388ca18c64fea38e3e57e3706b" + integrity sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ== + dependencies: + yocto-queue "^0.1.0" + +p-locate@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-3.0.0.tgz#322d69a05c0264b25997d9f40cd8a891ab0064a4" + integrity sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ== + dependencies: + p-limit "^2.0.0" + +p-locate@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-5.0.0.tgz#83c8315c6785005e3bd021839411c9e110e6d834" + integrity sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw== + dependencies: + p-limit "^3.0.2" + +p-try@^2.0.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" + integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== + +parse-glob@^3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/parse-glob/-/parse-glob-3.0.4.tgz#b2c376cfb11f35513badd173ef0bb6e3a388391c" + integrity sha1-ssN2z7EfNVE7rdFz7wu246OIORw= + dependencies: + glob-base "^0.3.0" + is-dotfile "^1.0.0" + is-extglob "^1.0.0" + is-glob "^2.0.0" + +pascalcase@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14" + integrity sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ= + +path-exists@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515" + integrity sha1-zg6+ql94yxiSXqfYENe1mwEP1RU= + +path-exists@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" + integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== + +path-is-absolute@^1.0.0, path-is-absolute@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" + integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= + +path-parse@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.5.tgz#3c1adf871ea9cd6c9431b6ea2bd74a0ff055c4c1" + +picomatch@^2.0.4, picomatch@^2.2.1: + version "2.2.2" + resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad" + integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg== + +posix-character-classes@^0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab" + integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs= + +preserve@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" + integrity sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks= + +private@^0.1.6, private@^0.1.7, private@^0.1.8: + version "0.1.8" + resolved "https://registry.yarnpkg.com/private/-/private-0.1.8.tgz#2381edb3689f7a53d653190060fcf822d2f368ff" + +process-nextick-args@~2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" + integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== + +punycode@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.0.tgz#5f863edc89b96db09074bad7947bf09056ca4e7d" + +randomatic@^3.0.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/randomatic/-/randomatic-3.1.1.tgz#b776efc59375984e36c537b2f51a1f0aff0da1ed" + integrity sha512-TuDE5KxZ0J461RVjrJZCJc+J+zCkTb1MbH9AQUq68sMhOMcy9jLcb3BrZKgp9q9Ncltdg4QVqWrH02W2EFFVYw== + dependencies: + is-number "^4.0.0" + kind-of "^6.0.0" + math-random "^1.0.1" + +randombytes@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a" + integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ== + dependencies: + safe-buffer "^5.1.0" + +readable-stream@^2.0.2: + version "2.3.7" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.7.tgz#1eca1cf711aef814c04f62252a36a62f6cb23b57" + integrity sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw== + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.3" + isarray "~1.0.0" + process-nextick-args "~2.0.0" + safe-buffer "~5.1.1" + string_decoder "~1.1.1" + util-deprecate "~1.0.1" + +readdirp@^2.0.0: + version "2.2.1" + resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-2.2.1.tgz#0e87622a3325aa33e892285caf8b4e846529a525" + integrity sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ== + dependencies: + graceful-fs "^4.1.11" + micromatch "^3.1.10" + readable-stream "^2.0.2" + +readdirp@~3.5.0: + version "3.5.0" + resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.5.0.tgz#9ba74c019b15d365278d2e91bb8c48d7b4d42c9e" + integrity sha512-cMhu7c/8rdhkHXWsY+osBhfSy0JikwpHK/5+imo+LpeasTF8ouErHrlYkwT0++njiyuDvc7OFY5T3ukvZ8qmFQ== + dependencies: + picomatch "^2.2.1" + +regenerate@^1.2.1: + version "1.3.3" + resolved "https://registry.yarnpkg.com/regenerate/-/regenerate-1.3.3.tgz#0c336d3980553d755c39b586ae3b20aa49c82b7f" + +regenerator-runtime@^0.10.5: + version "0.10.5" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.10.5.tgz#336c3efc1220adcedda2c9fab67b5a7955a33658" + integrity sha1-M2w+/BIgrc7dosn6tntaeVWjNlg= + +regenerator-runtime@^0.11.0: + version "0.11.1" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz#be05ad7f9bf7d22e056f9726cee5017fbf19e2e9" + integrity sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg== + +regenerator-transform@^0.10.0: + version "0.10.1" + resolved "https://registry.yarnpkg.com/regenerator-transform/-/regenerator-transform-0.10.1.tgz#1e4996837231da8b7f3cf4114d71b5691a0680dd" + dependencies: + babel-runtime "^6.18.0" + babel-types "^6.19.0" + private "^0.1.6" + +regex-cache@^0.4.2: + version "0.4.4" + resolved "https://registry.yarnpkg.com/regex-cache/-/regex-cache-0.4.4.tgz#75bdc58a2a1496cec48a12835bc54c8d562336dd" + integrity sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ== + dependencies: + is-equal-shallow "^0.1.3" + +regex-not@^1.0.0, regex-not@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/regex-not/-/regex-not-1.0.2.tgz#1f4ece27e00b0b65e0247a6810e6a85d83a5752c" + integrity sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A== + dependencies: + extend-shallow "^3.0.2" + safe-regex "^1.1.0" + +regexpu-core@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-2.0.0.tgz#49d038837b8dcf8bfa5b9a42139938e6ea2ae240" + dependencies: + regenerate "^1.2.1" + regjsgen "^0.2.0" + regjsparser "^0.1.4" + +regjsgen@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/regjsgen/-/regjsgen-0.2.0.tgz#6c016adeac554f75823fe37ac05b92d5a4edb1f7" + +regjsparser@^0.1.4: + version "0.1.5" + resolved "https://registry.yarnpkg.com/regjsparser/-/regjsparser-0.1.5.tgz#7ee8f84dc6fa792d3fd0ae228d24bd949ead205c" + dependencies: + jsesc "~0.5.0" + +remove-trailing-separator@^1.0.1: + version "1.1.0" + resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef" + integrity sha1-wkvOKig62tW8P1jg1IJJuSN52O8= + +repeat-element@^1.1.2: + version "1.1.3" + resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.3.tgz#782e0d825c0c5a3bb39731f84efee6b742e6b1ce" + integrity sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g== + +repeat-string@^1.5.2, repeat-string@^1.6.1: + version "1.6.1" + resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" + integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= + +repeating@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/repeating/-/repeating-2.0.1.tgz#5214c53a926d3552707527fbab415dbc08d06dda" + integrity sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo= + dependencies: + is-finite "^1.0.0" + +require-directory@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" + integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= + +require-main-filename@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-2.0.0.tgz#d0b329ecc7cc0f61649f62215be69af54aa8989b" + integrity sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg== + +resolve-url@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a" + integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= + +resolve@1.1.7: + version "1.1.7" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" + +resolve@^1.1.6: + version "1.6.0" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.6.0.tgz#0fbd21278b27b4004481c395349e7aba60a9ff5c" + dependencies: + path-parse "^1.0.5" + +ret@~0.1.10: + version "0.1.15" + resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc" + integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg== + +right-align@^0.1.1: + version "0.1.3" + resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef" + dependencies: + align-text "^0.1.1" + +rimraf@^2.5.2: + version "2.7.1" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" + dependencies: + glob "^7.1.3" + +rollup-plugin-babel@^2.7.1: + version "2.7.1" + resolved "https://registry.yarnpkg.com/rollup-plugin-babel/-/rollup-plugin-babel-2.7.1.tgz#16528197b0f938a1536f44683c7a93d573182f57" + dependencies: + babel-core "6" + babel-plugin-transform-es2015-classes "^6.9.0" + object-assign "^4.1.0" + rollup-pluginutils "^1.5.0" + +rollup-plugin-node-resolve@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/rollup-plugin-node-resolve/-/rollup-plugin-node-resolve-2.1.1.tgz#cbb783b0d15b02794d58915350b2f0d902b8ddc8" + dependencies: + browser-resolve "^1.11.0" + builtin-modules "^1.1.0" + resolve "^1.1.6" + +rollup-pluginutils@^1.5.0: + version "1.5.2" + resolved "https://registry.yarnpkg.com/rollup-pluginutils/-/rollup-pluginutils-1.5.2.tgz#1e156e778f94b7255bfa1b3d0178be8f5c552408" + dependencies: + estree-walker "^0.2.1" + minimatch "^3.0.2" + +rollup@^0.41.6: + version "0.41.6" + resolved "https://registry.yarnpkg.com/rollup/-/rollup-0.41.6.tgz#e0d05497877a398c104d816d2733a718a7a94e2a" + dependencies: + source-map-support "^0.4.0" + +safe-buffer@^5.1.0: + version "5.2.1" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" + integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== + +safe-buffer@~5.1.0, safe-buffer@~5.1.1: + version "5.1.2" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" + integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== + +safe-regex@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/safe-regex/-/safe-regex-1.1.0.tgz#40a3669f3b077d1e943d44629e157dd48023bf2e" + integrity sha1-QKNmnzsHfR6UPURinhV91IAjvy4= + dependencies: + ret "~0.1.10" + +sander@^0.5.0: + version "0.5.1" + resolved "https://registry.yarnpkg.com/sander/-/sander-0.5.1.tgz#741e245e231f07cafb6fdf0f133adfa216a502ad" + dependencies: + es6-promise "^3.1.2" + graceful-fs "^4.1.3" + mkdirp "^0.5.1" + rimraf "^2.5.2" + +serialize-javascript@5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-5.0.1.tgz#7886ec848049a462467a97d3d918ebb2aaf934f4" + integrity sha512-SaaNal9imEO737H2c05Og0/8LUXG7EnsZyMa8MzkmuHoELfT6txuj0cMqRj6zfPKnmQ1yasR4PCJc8x+M4JSPA== + dependencies: + randombytes "^2.1.0" + +set-blocking@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" + +set-value@^2.0.0, set-value@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/set-value/-/set-value-2.0.1.tgz#a18d40530e6f07de4228c7defe4227af8cad005b" + integrity sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw== + dependencies: + extend-shallow "^2.0.1" + is-extendable "^0.1.1" + is-plain-object "^2.0.3" + split-string "^3.0.1" + +slash@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/slash/-/slash-1.0.0.tgz#c41f2f6c39fc16d1cd17ad4b5d896114ae470d55" + integrity sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU= + +snapdragon-node@^2.0.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/snapdragon-node/-/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b" + integrity sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw== + dependencies: + define-property "^1.0.0" + isobject "^3.0.0" + snapdragon-util "^3.0.1" + +snapdragon-util@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/snapdragon-util/-/snapdragon-util-3.0.1.tgz#f956479486f2acd79700693f6f7b805e45ab56e2" + integrity sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ== + dependencies: + kind-of "^3.2.0" + +snapdragon@^0.8.1: + version "0.8.2" + resolved "https://registry.yarnpkg.com/snapdragon/-/snapdragon-0.8.2.tgz#64922e7c565b0e14204ba1aa7d6964278d25182d" + integrity sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg== + dependencies: + base "^0.11.1" + debug "^2.2.0" + define-property "^0.2.5" + extend-shallow "^2.0.1" + map-cache "^0.2.2" + source-map "^0.5.6" + source-map-resolve "^0.5.0" + use "^3.1.0" + +sorcery@^0.10.0: + version "0.10.0" + resolved "https://registry.yarnpkg.com/sorcery/-/sorcery-0.10.0.tgz#8ae90ad7d7cb05fc59f1ab0c637845d5c15a52b7" + dependencies: + buffer-crc32 "^0.2.5" + minimist "^1.2.0" + sander "^0.5.0" + sourcemap-codec "^1.3.0" + +source-map-resolve@^0.5.0: + version "0.5.3" + resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.3.tgz#190866bece7553e1f8f267a2ee82c606b5509a1a" + integrity sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw== + dependencies: + atob "^2.1.2" + decode-uri-component "^0.2.0" + resolve-url "^0.2.1" + source-map-url "^0.4.0" + urix "^0.1.0" + +source-map-support@^0.4.0, source-map-support@^0.4.15: + version "0.4.18" + resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.4.18.tgz#0286a6de8be42641338594e97ccea75f0a2c585f" + dependencies: + source-map "^0.5.6" + +source-map-url@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.0.tgz#3e935d7ddd73631b97659956d55128e87b5084a3" + integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM= + +source-map@^0.5.6, source-map@^0.5.7, source-map@~0.5.1: + version "0.5.7" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" + integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w= + +sourcemap-codec@^1.3.0: + version "1.4.1" + resolved "https://registry.yarnpkg.com/sourcemap-codec/-/sourcemap-codec-1.4.1.tgz#c8fd92d91889e902a07aee392bdd2c5863958ba2" + +split-string@^3.0.1, split-string@^3.0.2: + version "3.1.0" + resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2" + integrity sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw== + dependencies: + extend-shallow "^3.0.0" + +sprintf-js@~1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= + +static-extend@^0.1.1: + version "0.1.2" + resolved "https://registry.yarnpkg.com/static-extend/-/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6" + integrity sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY= + dependencies: + define-property "^0.2.5" + object-copy "^0.1.0" + +"string-width@^1.0.2 || 2": + version "2.1.1" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" + integrity sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw== + dependencies: + is-fullwidth-code-point "^2.0.0" + strip-ansi "^4.0.0" + +string-width@^3.0.0, string-width@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-3.1.0.tgz#22767be21b62af1081574306f69ac51b62203961" + integrity sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w== + dependencies: + emoji-regex "^7.0.1" + is-fullwidth-code-point "^2.0.0" + strip-ansi "^5.1.0" + +string_decoder@~1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" + integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== + dependencies: + safe-buffer "~5.1.0" + +strip-ansi@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" + integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8= + dependencies: + ansi-regex "^2.0.0" + +strip-ansi@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" + integrity sha1-qEeQIusaw2iocTibY1JixQXuNo8= + dependencies: + ansi-regex "^3.0.0" + +strip-ansi@^5.0.0, strip-ansi@^5.1.0, strip-ansi@^5.2.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-5.2.0.tgz#8c9a536feb6afc962bdfa5b104a5091c1ad9c0ae" + integrity sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA== + dependencies: + ansi-regex "^4.1.0" + +strip-json-comments@3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" + integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== + +supports-color@7.2.0, supports-color@^7.1.0: + version "7.2.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da" + integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw== + dependencies: + has-flag "^4.0.0" + +supports-color@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" + integrity sha1-U10EXOa2Nj+kARcIRimZXp3zJMc= + +to-fast-properties@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.3.tgz#b83571fa4d8c25b82e231b06e3a3055de4ca1a47" + integrity sha1-uDVx+k2MJbguIxsG46MFXeTKGkc= + +to-object-path@^0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/to-object-path/-/to-object-path-0.3.0.tgz#297588b7b0e7e0ac08e04e672f85c1f4999e17af" + integrity sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68= + dependencies: + kind-of "^3.0.2" + +to-regex-range@^2.1.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-2.1.1.tgz#7c80c17b9dfebe599e27367e0d4dd5590141db38" + integrity sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg= + dependencies: + is-number "^3.0.0" + repeat-string "^1.6.1" + +to-regex-range@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" + integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== + dependencies: + is-number "^7.0.0" + +to-regex@^3.0.1, to-regex@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/to-regex/-/to-regex-3.0.2.tgz#13cfdd9b336552f30b51f33a8ae1b42a7a7599ce" + integrity sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw== + dependencies: + define-property "^2.0.2" + extend-shallow "^3.0.2" + regex-not "^1.0.2" + safe-regex "^1.1.0" + +trim-right@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/trim-right/-/trim-right-1.0.1.tgz#cb2e1203067e0c8de1f614094b9fe45704ea6003" + integrity sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM= + +typescript@^2.8.1: + version "2.8.1" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.8.1.tgz#6160e4f8f195d5ba81d4876f9c0cc1fbc0820624" + +uglify-js@^2.8.14: + version "2.8.29" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.8.29.tgz#29c5733148057bb4e1f75df35b7a9cb72e6a59dd" + dependencies: + source-map "~0.5.1" + yargs "~3.10.0" + optionalDependencies: + uglify-to-browserify "~1.0.0" + +uglify-to-browserify@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7" + +union-value@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz#0b6fe7b835aecda61c6ea4d4f02c14221e109847" + integrity sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg== + dependencies: + arr-union "^3.1.0" + get-value "^2.0.6" + is-extendable "^0.1.1" + set-value "^2.0.1" + +unset-value@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/unset-value/-/unset-value-1.0.0.tgz#8376873f7d2335179ffb1e6fc3a8ed0dfc8ab559" + integrity sha1-g3aHP30jNRef+x5vw6jtDfyKtVk= + dependencies: + has-value "^0.3.1" + isobject "^3.0.0" + +urix@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72" + integrity sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI= + +use@^3.1.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f" + integrity sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ== + +user-home@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/user-home/-/user-home-1.1.1.tgz#2b5be23a32b63a7c9deb8d0f28d485724a3df190" + integrity sha1-K1viOjK2Onyd640PKNSFcko98ZA= + +util-deprecate@~1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= + +v8flags@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/v8flags/-/v8flags-2.1.1.tgz#aab1a1fa30d45f88dd321148875ac02c0b55e5b4" + integrity sha1-qrGh+jDUX4jdMhFIh1rALAtV5bQ= + dependencies: + user-home "^1.1.1" + +which-module@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.0.tgz#d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a" + integrity sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho= + +which@2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" + integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== + dependencies: + isexe "^2.0.0" + +wide-align@1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.3.tgz#ae074e6bdc0c14a431e804e624549c633b000457" + integrity sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA== + dependencies: + string-width "^1.0.2 || 2" + +window-size@0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" + +wordwrap@0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f" + +workerpool@6.0.2: + version "6.0.2" + resolved "https://registry.yarnpkg.com/workerpool/-/workerpool-6.0.2.tgz#e241b43d8d033f1beb52c7851069456039d1d438" + integrity sha512-DSNyvOpFKrNusaaUwk+ej6cBj1bmhLcBfj80elGk+ZIo5JSkq+unB1dLKEOcNfJDZgjGICfhQ0Q5TbP0PvF4+Q== + +wrap-ansi@^5.1.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-5.1.0.tgz#1fd1f67235d5b6d0fee781056001bfb694c03b09" + integrity sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q== + dependencies: + ansi-styles "^3.2.0" + string-width "^3.0.0" + strip-ansi "^5.0.0" + +wrappy@1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= + +y18n@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.1.tgz#8db2b83c31c5d75099bb890b23f3094891e247d4" + integrity sha512-wNcy4NvjMYL8gogWWYAO7ZFWFfHcbdbE57tZO8e4cbpj8tfUcwrwqSl3ad8HxpYWCdXcJUCeKKZS62Av1affwQ== + +yargs-parser@13.1.2, yargs-parser@^13.1.2: + version "13.1.2" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-13.1.2.tgz#130f09702ebaeef2650d54ce6e3e5706f7a4fb38" + integrity sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg== + dependencies: + camelcase "^5.0.0" + decamelize "^1.2.0" + +yargs-unparser@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/yargs-unparser/-/yargs-unparser-2.0.0.tgz#f131f9226911ae5d9ad38c432fe809366c2325eb" + integrity sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA== + dependencies: + camelcase "^6.0.0" + decamelize "^4.0.0" + flat "^5.0.2" + is-plain-obj "^2.1.0" + +yargs@13.3.2: + version "13.3.2" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-13.3.2.tgz#ad7ffefec1aa59565ac915f82dccb38a9c31a2dd" + integrity sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw== + dependencies: + cliui "^5.0.0" + find-up "^3.0.0" + get-caller-file "^2.0.1" + require-directory "^2.1.1" + require-main-filename "^2.0.0" + set-blocking "^2.0.0" + string-width "^3.0.0" + which-module "^2.0.0" + y18n "^4.0.0" + yargs-parser "^13.1.2" + +yargs@~3.10.0: + version "3.10.0" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.10.0.tgz#f7ee7bd857dd7c1d2d38c0e74efbd681d1431fd1" + dependencies: + camelcase "^1.0.2" + cliui "^2.1.0" + decamelize "^1.0.0" + window-size "0.1.0" + +yocto-queue@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b" + integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== diff --git a/node_modules/mathjs/examples/node_modules/watchpack/LICENSE b/node_modules/mathjs/examples/node_modules/watchpack/LICENSE new file mode 100644 index 0000000..8c11fc7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/watchpack/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +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. diff --git a/node_modules/mathjs/examples/node_modules/watchpack/README.md b/node_modules/mathjs/examples/node_modules/watchpack/README.md new file mode 100644 index 0000000..2924722 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/watchpack/README.md @@ -0,0 +1,149 @@ +# watchpack + +Wrapper library for directory and file watching. + +[![Build Status][build-status]][build-status-url] +[![Build status][build-status-veyor]][build-status-veyor-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![codecov][codecov]][codecov-url] +[![downloads][downloads]][downloads-url] +[![Github contributors][contributors]][contributors-url] + +## Concept + +watchpack high level API doesn't map directly to watchers. Instead a three level architecture ensures that for each directory only a single watcher exists. + +- The high level API requests `DirectoryWatchers` from a `WatcherManager`, which ensures that only a single `DirectoryWatcher` per directory is created. +- A user-faced `Watcher` can be obtained from a `DirectoryWatcher` and provides a filtered view on the `DirectoryWatcher`. +- Reference-counting is used on the `DirectoryWatcher` and `Watcher` to decide when to close them. +- The real watchers are created by the `DirectoryWatcher`. +- Files are never watched directly. This should keep the watcher count low. +- Watching can be started in the past. This way watching can start after file reading. +- Symlinks are not followed, instead the symlink is watched. + +## API + +```javascript +var Watchpack = require("watchpack"); + +var wp = new Watchpack({ + // options: + aggregateTimeout: 1000, + // fire "aggregated" event when after a change for 1000ms no additional change occurred + // aggregated defaults to undefined, which doesn't fire an "aggregated" event + + poll: true, + // poll: true - use polling with the default interval + // poll: 10000 - use polling with an interval of 10s + // poll defaults to undefined, which prefer native watching methods + // Note: enable polling when watching on a network path + // When WATCHPACK_POLLING environment variable is set it will override this option + + followSymlinks: true, + // true: follows symlinks and watches symlinks and real files + // (This makes sense when symlinks has not been resolved yet, comes with a performance hit) + // false (default): watches only specified item they may be real files or symlinks + // (This makes sense when symlinks has already been resolved) + + ignored: "**/.git" + // ignored: "string" - a glob pattern for files or folders that should not be watched + // ignored: ["string", "string"] - multiple glob patterns that should be ignored + // ignored: /regexp/ - a regular expression for files or folders that should not be watched + // ignored: (entry) => boolean - an arbitrary function which must return truthy to ignore an entry + // For all cases expect the arbitrary function the path will have path separator normalized to '/'. + // All subdirectories are ignored too +}); + +// Watchpack.prototype.watch({ +// files: Iterable, +// directories: Iterable, +// missing: Iterable, +// startTime?: number +// }) +wp.watch({ + files: listOfFiles, + directories: listOfDirectories, + missing: listOfNotExistingItems, + startTime: Date.now() - 10000 +}); +// starts watching these files and directories +// calling this again will override the files and directories +// files: can be files or directories, for files: content and existence changes are tracked +// for directories: only existence and timestamp changes are tracked +// directories: only directories, directory content (and content of children, ...) and +// existence changes are tracked. +// assumed to exist, when directory is not found without further information a remove event is emitted +// missing: can be files or directorees, +// only existence changes are tracked +// expected to not exist, no remove event is emitted when not found initially +// files and directories are assumed to exist, when they are not found without further information a remove event is emitted +// missing is assumed to not exist and no remove event is emitted + +wp.on("change", function(filePath, mtime, explanation) { + // filePath: the changed file + // mtime: last modified time for the changed file + // explanation: textual information how this change was detected +}); + +wp.on("remove", function(filePath, explanation) { + // filePath: the removed file or directory + // explanation: textual information how this change was detected +}); + +wp.on("aggregated", function(changes, removals) { + // changes: a Set of all changed files + // removals: a Set of all removed files + // watchpack gives up ownership on these Sets. +}); + +// Watchpack.prototype.pause() +wp.pause(); +// stops emitting events, but keeps watchers open +// next "watch" call can reuse the watchers +// The watcher will keep aggregating events +// which can be received with getAggregated() + +// Watchpack.prototype.close() +wp.close(); +// stops emitting events and closes all watchers + +// Watchpack.prototype.getAggregated(): { changes: Set, removals: Set } +const { changes, removals } = wp.getAggregated(); +// returns the current aggregated info and removes that from the watcher +// The next aggregated event won't include that info and will only emitted +// when futher changes happen +// Can also be used when paused. + +// Watchpack.prototype.collectTimeInfoEntries(fileInfoEntries: Map, directoryInfoEntries: Map) +wp.collectTimeInfoEntries(fileInfoEntries, directoryInfoEntries); +// collects time info objects for all known files and directories +// this include info from files not directly watched +// key: absolute path, value: object with { safeTime, timestamp } +// safeTime: a point in time at which it is safe to say all changes happened before that +// timestamp: only for files, the mtime timestamp of the file + +// Watchpack.prototype.getTimeInfoEntries() +var fileTimes = wp.getTimeInfoEntries(); +// returns a Map with all known time info objects for files and directories +// similar to collectTimeInfoEntries but returns a single map with all entries + +// (deprecated) +// Watchpack.prototype.getTimes() +var fileTimes = wp.getTimes(); +// returns an object with all known change times for files +// this include timestamps from files not directly watched +// key: absolute path, value: timestamp as number +``` + +[build-status]: https://travis-ci.org/webpack/watchpack.svg?branch=main +[build-status-url]: https://travis-ci.org/webpack/watchpack +[build-status-veyor]: https://ci.appveyor.com/api/projects/status/e5u2qvmugtv0r647/branch/main?svg=true +[build-status-veyor-url]: https://ci.appveyor.com/project/sokra/watchpack/branch/main +[coveralls-url]: https://coveralls.io/r/webpack/watchpack/ +[coveralls-image]: https://img.shields.io/coveralls/webpack/watchpack.svg +[codecov]: https://codecov.io/gh/webpack/watchpack/branch/main/graph/badge.svg +[codecov-url]: https://codecov.io/gh/webpack/watchpack +[downloads]: https://img.shields.io/npm/dm/watchpack.svg +[downloads-url]: https://www.npmjs.com/package/watchpack +[contributors]: https://img.shields.io/github/contributors/webpack/watchpack.svg +[contributors-url]: https://github.com/webpack/watchpack/graphs/contributors diff --git a/node_modules/mathjs/examples/node_modules/watchpack/lib/DirectoryWatcher.js b/node_modules/mathjs/examples/node_modules/watchpack/lib/DirectoryWatcher.js new file mode 100644 index 0000000..5cf3a47 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/watchpack/lib/DirectoryWatcher.js @@ -0,0 +1,785 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const EventEmitter = require("events").EventEmitter; +const fs = require("graceful-fs"); +const path = require("path"); + +const watchEventSource = require("./watchEventSource"); + +const EXISTANCE_ONLY_TIME_ENTRY = Object.freeze({}); + +let FS_ACCURACY = 1000; + +const IS_OSX = require("os").platform() === "darwin"; +const WATCHPACK_POLLING = process.env.WATCHPACK_POLLING; +const FORCE_POLLING = + `${+WATCHPACK_POLLING}` === WATCHPACK_POLLING + ? +WATCHPACK_POLLING + : !!WATCHPACK_POLLING && WATCHPACK_POLLING !== "false"; + +function withoutCase(str) { + return str.toLowerCase(); +} + +function needCalls(times, callback) { + return function() { + if (--times === 0) { + return callback(); + } + }; +} + +class Watcher extends EventEmitter { + constructor(directoryWatcher, filePath, startTime) { + super(); + this.directoryWatcher = directoryWatcher; + this.path = filePath; + this.startTime = startTime && +startTime; + } + + checkStartTime(mtime, initial) { + const startTime = this.startTime; + if (typeof startTime !== "number") return !initial; + return startTime <= mtime; + } + + close() { + this.emit("closed"); + } +} + +class DirectoryWatcher extends EventEmitter { + constructor(watcherManager, directoryPath, options) { + super(); + if (FORCE_POLLING) { + options.poll = FORCE_POLLING; + } + this.watcherManager = watcherManager; + this.options = options; + this.path = directoryPath; + // safeTime is the point in time after which reading is safe to be unchanged + // timestamp is a value that should be compared with another timestamp (mtime) + /** @type {Map} */ + this.filesWithoutCase = new Map(); + this.directories = new Map(); + this.lastWatchEvent = 0; + this.initialScan = true; + this.ignored = options.ignored || (() => false); + this.nestedWatching = false; + this.polledWatching = + typeof options.poll === "number" + ? options.poll + : options.poll + ? 5007 + : false; + this.timeout = undefined; + this.initialScanRemoved = new Set(); + this.initialScanFinished = undefined; + /** @type {Map>} */ + this.watchers = new Map(); + this.parentWatcher = null; + this.refs = 0; + this._activeEvents = new Map(); + this.closed = false; + this.scanning = false; + this.scanAgain = false; + this.scanAgainInitial = false; + + this.createWatcher(); + this.doScan(true); + } + + createWatcher() { + try { + if (this.polledWatching) { + this.watcher = { + close: () => { + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = undefined; + } + } + }; + } else { + if (IS_OSX) { + this.watchInParentDirectory(); + } + this.watcher = watchEventSource.watch(this.path); + this.watcher.on("change", this.onWatchEvent.bind(this)); + this.watcher.on("error", this.onWatcherError.bind(this)); + } + } catch (err) { + this.onWatcherError(err); + } + } + + forEachWatcher(path, fn) { + const watchers = this.watchers.get(withoutCase(path)); + if (watchers !== undefined) { + for (const w of watchers) { + fn(w); + } + } + } + + setMissing(itemPath, initial, type) { + if (this.initialScan) { + this.initialScanRemoved.add(itemPath); + } + + const oldDirectory = this.directories.get(itemPath); + if (oldDirectory) { + if (this.nestedWatching) oldDirectory.close(); + this.directories.delete(itemPath); + + this.forEachWatcher(itemPath, w => w.emit("remove", type)); + if (!initial) { + this.forEachWatcher(this.path, w => + w.emit("change", itemPath, null, type, initial) + ); + } + } + + const oldFile = this.files.get(itemPath); + if (oldFile) { + this.files.delete(itemPath); + const key = withoutCase(itemPath); + const count = this.filesWithoutCase.get(key) - 1; + if (count <= 0) { + this.filesWithoutCase.delete(key); + this.forEachWatcher(itemPath, w => w.emit("remove", type)); + } else { + this.filesWithoutCase.set(key, count); + } + + if (!initial) { + this.forEachWatcher(this.path, w => + w.emit("change", itemPath, null, type, initial) + ); + } + } + } + + setFileTime(filePath, mtime, initial, ignoreWhenEqual, type) { + const now = Date.now(); + + if (this.ignored(filePath)) return; + + const old = this.files.get(filePath); + + let safeTime, accuracy; + if (initial) { + safeTime = Math.min(now, mtime) + FS_ACCURACY; + accuracy = FS_ACCURACY; + } else { + safeTime = now; + accuracy = 0; + + if (old && old.timestamp === mtime && mtime + FS_ACCURACY < now - 1000) { + // We are sure that mtime is untouched + // This can be caused by some file attribute change + // e. g. when access time has been changed + // but the file content is untouched + return; + } + } + + if (ignoreWhenEqual && old && old.timestamp === mtime) return; + + this.files.set(filePath, { + safeTime, + accuracy, + timestamp: mtime + }); + + if (!old) { + const key = withoutCase(filePath); + const count = this.filesWithoutCase.get(key); + this.filesWithoutCase.set(key, (count || 0) + 1); + if (count !== undefined) { + // There is already a file with case-insensitive-equal name + // On a case-insensitive filesystem we may miss the renaming + // when only casing is changed. + // To be sure that our information is correct + // we trigger a rescan here + this.doScan(false); + } + + this.forEachWatcher(filePath, w => { + if (!initial || w.checkStartTime(safeTime, initial)) { + w.emit("change", mtime, type); + } + }); + } else if (!initial) { + this.forEachWatcher(filePath, w => w.emit("change", mtime, type)); + } + this.forEachWatcher(this.path, w => { + if (!initial || w.checkStartTime(safeTime, initial)) { + w.emit("change", filePath, safeTime, type, initial); + } + }); + } + + setDirectory(directoryPath, birthtime, initial, type) { + if (this.ignored(directoryPath)) return; + if (directoryPath === this.path) { + if (!initial) { + this.forEachWatcher(this.path, w => + w.emit("change", directoryPath, birthtime, type, initial) + ); + } + } else { + const old = this.directories.get(directoryPath); + if (!old) { + const now = Date.now(); + + if (this.nestedWatching) { + this.createNestedWatcher(directoryPath); + } else { + this.directories.set(directoryPath, true); + } + + let safeTime; + if (initial) { + safeTime = Math.min(now, birthtime) + FS_ACCURACY; + } else { + safeTime = now; + } + + this.forEachWatcher(directoryPath, w => { + if (!initial || w.checkStartTime(safeTime, false)) { + w.emit("change", birthtime, type); + } + }); + this.forEachWatcher(this.path, w => { + if (!initial || w.checkStartTime(safeTime, initial)) { + w.emit("change", directoryPath, safeTime, type, initial); + } + }); + } + } + } + + createNestedWatcher(directoryPath) { + const watcher = this.watcherManager.watchDirectory(directoryPath, 1); + watcher.on("change", (filePath, mtime, type, initial) => { + this.forEachWatcher(this.path, w => { + if (!initial || w.checkStartTime(mtime, initial)) { + w.emit("change", filePath, mtime, type, initial); + } + }); + }); + this.directories.set(directoryPath, watcher); + } + + setNestedWatching(flag) { + if (this.nestedWatching !== !!flag) { + this.nestedWatching = !!flag; + if (this.nestedWatching) { + for (const directory of this.directories.keys()) { + this.createNestedWatcher(directory); + } + } else { + for (const [directory, watcher] of this.directories) { + watcher.close(); + this.directories.set(directory, true); + } + } + } + } + + watch(filePath, startTime) { + const key = withoutCase(filePath); + let watchers = this.watchers.get(key); + if (watchers === undefined) { + watchers = new Set(); + this.watchers.set(key, watchers); + } + this.refs++; + const watcher = new Watcher(this, filePath, startTime); + watcher.on("closed", () => { + if (--this.refs <= 0) { + this.close(); + return; + } + watchers.delete(watcher); + if (watchers.size === 0) { + this.watchers.delete(key); + if (this.path === filePath) this.setNestedWatching(false); + } + }); + watchers.add(watcher); + let safeTime; + if (filePath === this.path) { + this.setNestedWatching(true); + safeTime = this.lastWatchEvent; + for (const entry of this.files.values()) { + fixupEntryAccuracy(entry); + safeTime = Math.max(safeTime, entry.safeTime); + } + } else { + const entry = this.files.get(filePath); + if (entry) { + fixupEntryAccuracy(entry); + safeTime = entry.safeTime; + } else { + safeTime = 0; + } + } + if (safeTime) { + if (safeTime >= startTime) { + process.nextTick(() => { + if (this.closed) return; + if (filePath === this.path) { + watcher.emit( + "change", + filePath, + safeTime, + "watch (outdated on attach)", + true + ); + } else { + watcher.emit( + "change", + safeTime, + "watch (outdated on attach)", + true + ); + } + }); + } + } else if (this.initialScan) { + if (this.initialScanRemoved.has(filePath)) { + process.nextTick(() => { + if (this.closed) return; + watcher.emit("remove"); + }); + } + } else if ( + !this.directories.has(filePath) && + watcher.checkStartTime(this.initialScanFinished, false) + ) { + process.nextTick(() => { + if (this.closed) return; + watcher.emit("initial-missing", "watch (missing on attach)"); + }); + } + return watcher; + } + + onWatchEvent(eventType, filename) { + if (this.closed) return; + if (!filename) { + // In some cases no filename is provided + // This seem to happen on windows + // So some event happened but we don't know which file is affected + // We have to do a full scan of the directory + this.doScan(false); + return; + } + + const filePath = path.join(this.path, filename); + if (this.ignored(filePath)) return; + + if (this._activeEvents.get(filename) === undefined) { + this._activeEvents.set(filename, false); + const checkStats = () => { + if (this.closed) return; + this._activeEvents.set(filename, false); + fs.lstat(filePath, (err, stats) => { + if (this.closed) return; + if (this._activeEvents.get(filename) === true) { + process.nextTick(checkStats); + return; + } + this._activeEvents.delete(filename); + // ENOENT happens when the file/directory doesn't exist + // EPERM happens when the containing directory doesn't exist + if (err) { + if ( + err.code !== "ENOENT" && + err.code !== "EPERM" && + err.code !== "EBUSY" + ) { + this.onStatsError(err); + } else { + if (filename === path.basename(this.path)) { + // This may indicate that the directory itself was removed + if (!fs.existsSync(this.path)) { + this.onDirectoryRemoved("stat failed"); + } + } + } + } + this.lastWatchEvent = Date.now(); + if (!stats) { + this.setMissing(filePath, false, eventType); + } else if (stats.isDirectory()) { + this.setDirectory( + filePath, + +stats.birthtime || 1, + false, + eventType + ); + } else if (stats.isFile() || stats.isSymbolicLink()) { + if (stats.mtime) { + ensureFsAccuracy(stats.mtime); + } + this.setFileTime( + filePath, + +stats.mtime || +stats.ctime || 1, + false, + false, + eventType + ); + } + }); + }; + process.nextTick(checkStats); + } else { + this._activeEvents.set(filename, true); + } + } + + onWatcherError(err) { + if (this.closed) return; + if (err) { + if (err.code !== "EPERM" && err.code !== "ENOENT") { + console.error("Watchpack Error (watcher): " + err); + } + this.onDirectoryRemoved("watch error"); + } + } + + onStatsError(err) { + if (err) { + console.error("Watchpack Error (stats): " + err); + } + } + + onScanError(err) { + if (err) { + console.error("Watchpack Error (initial scan): " + err); + } + this.onScanFinished(); + } + + onScanFinished() { + if (this.polledWatching) { + this.timeout = setTimeout(() => { + if (this.closed) return; + this.doScan(false); + }, this.polledWatching); + } + } + + onDirectoryRemoved(reason) { + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + this.watchInParentDirectory(); + const type = `directory-removed (${reason})`; + for (const directory of this.directories.keys()) { + this.setMissing(directory, null, type); + } + for (const file of this.files.keys()) { + this.setMissing(file, null, type); + } + } + + watchInParentDirectory() { + if (!this.parentWatcher) { + const parentDir = path.dirname(this.path); + // avoid watching in the root directory + // removing directories in the root directory is not supported + if (path.dirname(parentDir) === parentDir) return; + + this.parentWatcher = this.watcherManager.watchFile(this.path, 1); + this.parentWatcher.on("change", (mtime, type) => { + if (this.closed) return; + + // On non-osx platforms we don't need this watcher to detect + // directory removal, as an EPERM error indicates that + if ((!IS_OSX || this.polledWatching) && this.parentWatcher) { + this.parentWatcher.close(); + this.parentWatcher = null; + } + // Try to create the watcher when parent directory is found + if (!this.watcher) { + this.createWatcher(); + this.doScan(false); + + // directory was created so we emit an event + this.forEachWatcher(this.path, w => + w.emit("change", this.path, mtime, type, false) + ); + } + }); + this.parentWatcher.on("remove", () => { + this.onDirectoryRemoved("parent directory removed"); + }); + } + } + + doScan(initial) { + if (this.scanning) { + if (this.scanAgain) { + if (!initial) this.scanAgainInitial = false; + } else { + this.scanAgain = true; + this.scanAgainInitial = initial; + } + return; + } + this.scanning = true; + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = undefined; + } + process.nextTick(() => { + if (this.closed) return; + fs.readdir(this.path, (err, items) => { + if (this.closed) return; + if (err) { + if (err.code === "ENOENT" || err.code === "EPERM") { + this.onDirectoryRemoved("scan readdir failed"); + } else { + this.onScanError(err); + } + this.initialScan = false; + this.initialScanFinished = Date.now(); + if (initial) { + for (const watchers of this.watchers.values()) { + for (const watcher of watchers) { + if (watcher.checkStartTime(this.initialScanFinished, false)) { + watcher.emit( + "initial-missing", + "scan (parent directory missing in initial scan)" + ); + } + } + } + } + if (this.scanAgain) { + this.scanAgain = false; + this.doScan(this.scanAgainInitial); + } else { + this.scanning = false; + } + return; + } + const itemPaths = new Set( + items.map(item => path.join(this.path, item.normalize("NFC"))) + ); + for (const file of this.files.keys()) { + if (!itemPaths.has(file)) { + this.setMissing(file, initial, "scan (missing)"); + } + } + for (const directory of this.directories.keys()) { + if (!itemPaths.has(directory)) { + this.setMissing(directory, initial, "scan (missing)"); + } + } + if (this.scanAgain) { + // Early repeat of scan + this.scanAgain = false; + this.doScan(initial); + return; + } + const itemFinished = needCalls(itemPaths.size + 1, () => { + if (this.closed) return; + this.initialScan = false; + this.initialScanRemoved = null; + this.initialScanFinished = Date.now(); + if (initial) { + const missingWatchers = new Map(this.watchers); + missingWatchers.delete(withoutCase(this.path)); + for (const item of itemPaths) { + missingWatchers.delete(withoutCase(item)); + } + for (const watchers of missingWatchers.values()) { + for (const watcher of watchers) { + if (watcher.checkStartTime(this.initialScanFinished, false)) { + watcher.emit( + "initial-missing", + "scan (missing in initial scan)" + ); + } + } + } + } + if (this.scanAgain) { + this.scanAgain = false; + this.doScan(this.scanAgainInitial); + } else { + this.scanning = false; + this.onScanFinished(); + } + }); + for (const itemPath of itemPaths) { + fs.lstat(itemPath, (err2, stats) => { + if (this.closed) return; + if (err2) { + if ( + err2.code === "ENOENT" || + err2.code === "EPERM" || + err2.code === "EACCES" || + err2.code === "EBUSY" + ) { + this.setMissing(itemPath, initial, "scan (" + err2.code + ")"); + } else { + this.onScanError(err2); + } + itemFinished(); + return; + } + if (stats.isFile() || stats.isSymbolicLink()) { + if (stats.mtime) { + ensureFsAccuracy(stats.mtime); + } + this.setFileTime( + itemPath, + +stats.mtime || +stats.ctime || 1, + initial, + true, + "scan (file)" + ); + } else if (stats.isDirectory()) { + if (!initial || !this.directories.has(itemPath)) + this.setDirectory( + itemPath, + +stats.birthtime || 1, + initial, + "scan (dir)" + ); + } + itemFinished(); + }); + } + itemFinished(); + }); + }); + } + + getTimes() { + const obj = Object.create(null); + let safeTime = this.lastWatchEvent; + for (const [file, entry] of this.files) { + fixupEntryAccuracy(entry); + safeTime = Math.max(safeTime, entry.safeTime); + obj[file] = Math.max(entry.safeTime, entry.timestamp); + } + if (this.nestedWatching) { + for (const w of this.directories.values()) { + const times = w.directoryWatcher.getTimes(); + for (const file of Object.keys(times)) { + const time = times[file]; + safeTime = Math.max(safeTime, time); + obj[file] = time; + } + } + obj[this.path] = safeTime; + } + if (!this.initialScan) { + for (const watchers of this.watchers.values()) { + for (const watcher of watchers) { + const path = watcher.path; + if (!Object.prototype.hasOwnProperty.call(obj, path)) { + obj[path] = null; + } + } + } + } + return obj; + } + + collectTimeInfoEntries(fileTimestamps, directoryTimestamps) { + let safeTime = this.lastWatchEvent; + for (const [file, entry] of this.files) { + fixupEntryAccuracy(entry); + safeTime = Math.max(safeTime, entry.safeTime); + fileTimestamps.set(file, entry); + } + if (this.nestedWatching) { + for (const w of this.directories.values()) { + safeTime = Math.max( + safeTime, + w.directoryWatcher.collectTimeInfoEntries( + fileTimestamps, + directoryTimestamps + ) + ); + } + fileTimestamps.set(this.path, EXISTANCE_ONLY_TIME_ENTRY); + directoryTimestamps.set(this.path, { + safeTime + }); + } else { + for (const dir of this.directories.keys()) { + // No additional info about this directory + // but maybe another DirectoryWatcher has info + fileTimestamps.set(dir, EXISTANCE_ONLY_TIME_ENTRY); + if (!directoryTimestamps.has(dir)) + directoryTimestamps.set(dir, EXISTANCE_ONLY_TIME_ENTRY); + } + fileTimestamps.set(this.path, EXISTANCE_ONLY_TIME_ENTRY); + directoryTimestamps.set(this.path, EXISTANCE_ONLY_TIME_ENTRY); + } + if (!this.initialScan) { + for (const watchers of this.watchers.values()) { + for (const watcher of watchers) { + const path = watcher.path; + if (!fileTimestamps.has(path)) { + fileTimestamps.set(path, null); + } + } + } + } + return safeTime; + } + + close() { + this.closed = true; + this.initialScan = false; + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + if (this.nestedWatching) { + for (const w of this.directories.values()) { + w.close(); + } + this.directories.clear(); + } + if (this.parentWatcher) { + this.parentWatcher.close(); + this.parentWatcher = null; + } + this.emit("closed"); + } +} + +module.exports = DirectoryWatcher; +module.exports.EXISTANCE_ONLY_TIME_ENTRY = EXISTANCE_ONLY_TIME_ENTRY; + +function fixupEntryAccuracy(entry) { + if (entry.accuracy > FS_ACCURACY) { + entry.safeTime = entry.safeTime - entry.accuracy + FS_ACCURACY; + entry.accuracy = FS_ACCURACY; + } +} + +function ensureFsAccuracy(mtime) { + if (!mtime) return; + if (FS_ACCURACY > 1 && mtime % 1 !== 0) FS_ACCURACY = 1; + else if (FS_ACCURACY > 10 && mtime % 10 !== 0) FS_ACCURACY = 10; + else if (FS_ACCURACY > 100 && mtime % 100 !== 0) FS_ACCURACY = 100; +} diff --git a/node_modules/mathjs/examples/node_modules/watchpack/lib/LinkResolver.js b/node_modules/mathjs/examples/node_modules/watchpack/lib/LinkResolver.js new file mode 100644 index 0000000..daea90b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/watchpack/lib/LinkResolver.js @@ -0,0 +1,107 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const fs = require("fs"); +const path = require("path"); + +// macOS, Linux, and Windows all rely on these errors +const EXPECTED_ERRORS = new Set(["EINVAL", "ENOENT"]); + +// On Windows there is also this error in some cases +if (process.platform === "win32") EXPECTED_ERRORS.add("UNKNOWN"); + +class LinkResolver { + constructor() { + this.cache = new Map(); + } + + /** + * @param {string} file path to file or directory + * @returns {string[]} array of file and all symlinks contributed in the resolving process (first item is the resolved file) + */ + resolve(file) { + const cacheEntry = this.cache.get(file); + if (cacheEntry !== undefined) { + return cacheEntry; + } + const parent = path.dirname(file); + if (parent === file) { + // At root of filesystem there can't be a link + const result = Object.freeze([file]); + this.cache.set(file, result); + return result; + } + // resolve the parent directory to find links there and get the real path + const parentResolved = this.resolve(parent); + let realFile = file; + + // is the parent directory really somewhere else? + if (parentResolved[0] !== parent) { + // get the real location of file + const basename = path.basename(file); + realFile = path.resolve(parentResolved[0], basename); + } + // try to read the link content + try { + const linkContent = fs.readlinkSync(realFile); + + // resolve the link content relative to the parent directory + const resolvedLink = path.resolve(parentResolved[0], linkContent); + + // recursive resolve the link content for more links in the structure + const linkResolved = this.resolve(resolvedLink); + + // merge parent and link resolve results + let result; + if (linkResolved.length > 1 && parentResolved.length > 1) { + // when both contain links we need to duplicate them with a Set + const resultSet = new Set(linkResolved); + // add the link + resultSet.add(realFile); + // add all symlinks of the parent + for (let i = 1; i < parentResolved.length; i++) { + resultSet.add(parentResolved[i]); + } + result = Object.freeze(Array.from(resultSet)); + } else if (parentResolved.length > 1) { + // we have links in the parent but not for the link content location + result = parentResolved.slice(); + result[0] = linkResolved[0]; + // add the link + result.push(realFile); + Object.freeze(result); + } else if (linkResolved.length > 1) { + // we can return the link content location result + result = linkResolved.slice(); + // add the link + result.push(realFile); + Object.freeze(result); + } else { + // neither link content location nor parent have links + // this link is the only link here + result = Object.freeze([ + // the resolve real location + linkResolved[0], + // add the link + realFile + ]); + } + this.cache.set(file, result); + return result; + } catch (e) { + if (!EXPECTED_ERRORS.has(e.code)) { + throw e; + } + // no link + const result = parentResolved.slice(); + result[0] = realFile; + Object.freeze(result); + this.cache.set(file, result); + return result; + } + } +} +module.exports = LinkResolver; diff --git a/node_modules/mathjs/examples/node_modules/watchpack/lib/getWatcherManager.js b/node_modules/mathjs/examples/node_modules/watchpack/lib/getWatcherManager.js new file mode 100644 index 0000000..e0dcd6a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/watchpack/lib/getWatcherManager.js @@ -0,0 +1,52 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); +const DirectoryWatcher = require("./DirectoryWatcher"); + +class WatcherManager { + constructor(options) { + this.options = options; + this.directoryWatchers = new Map(); + } + + getDirectoryWatcher(directory) { + const watcher = this.directoryWatchers.get(directory); + if (watcher === undefined) { + const newWatcher = new DirectoryWatcher(this, directory, this.options); + this.directoryWatchers.set(directory, newWatcher); + newWatcher.on("closed", () => { + this.directoryWatchers.delete(directory); + }); + return newWatcher; + } + return watcher; + } + + watchFile(p, startTime) { + const directory = path.dirname(p); + if (directory === p) return null; + return this.getDirectoryWatcher(directory).watch(p, startTime); + } + + watchDirectory(directory, startTime) { + return this.getDirectoryWatcher(directory).watch(directory, startTime); + } +} + +const watcherManagers = new WeakMap(); +/** + * @param {object} options options + * @returns {WatcherManager} the watcher manager + */ +module.exports = options => { + const watcherManager = watcherManagers.get(options); + if (watcherManager !== undefined) return watcherManager; + const newWatcherManager = new WatcherManager(options); + watcherManagers.set(options, newWatcherManager); + return newWatcherManager; +}; +module.exports.WatcherManager = WatcherManager; diff --git a/node_modules/mathjs/examples/node_modules/watchpack/lib/reducePlan.js b/node_modules/mathjs/examples/node_modules/watchpack/lib/reducePlan.js new file mode 100644 index 0000000..b281ed6 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/watchpack/lib/reducePlan.js @@ -0,0 +1,138 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); + +/** + * @template T + * @typedef {Object} TreeNode + * @property {string} filePath + * @property {TreeNode} parent + * @property {TreeNode[]} children + * @property {number} entries + * @property {boolean} active + * @property {T[] | T | undefined} value + */ + +/** + * @template T + * @param {Map>} the new plan + */ +module.exports = (plan, limit) => { + const treeMap = new Map(); + // Convert to tree + for (const [filePath, value] of plan) { + treeMap.set(filePath, { + filePath, + parent: undefined, + children: undefined, + entries: 1, + active: true, + value + }); + } + let currentCount = treeMap.size; + // Create parents and calculate sum of entries + for (const node of treeMap.values()) { + const parentPath = path.dirname(node.filePath); + if (parentPath !== node.filePath) { + let parent = treeMap.get(parentPath); + if (parent === undefined) { + parent = { + filePath: parentPath, + parent: undefined, + children: [node], + entries: node.entries, + active: false, + value: undefined + }; + treeMap.set(parentPath, parent); + node.parent = parent; + } else { + node.parent = parent; + if (parent.children === undefined) { + parent.children = [node]; + } else { + parent.children.push(node); + } + do { + parent.entries += node.entries; + parent = parent.parent; + } while (parent); + } + } + } + // Reduce until limit reached + while (currentCount > limit) { + // Select node that helps reaching the limit most effectively without overmerging + const overLimit = currentCount - limit; + let bestNode = undefined; + let bestCost = Infinity; + for (const node of treeMap.values()) { + if (node.entries <= 1 || !node.children || !node.parent) continue; + if (node.children.length === 0) continue; + if (node.children.length === 1 && !node.value) continue; + // Try to select the node with has just a bit more entries than we need to reduce + // When just a bit more is over 30% over the limit, + // also consider just a bit less entries then we need to reduce + const cost = + node.entries - 1 >= overLimit + ? node.entries - 1 - overLimit + : overLimit - node.entries + 1 + limit * 0.3; + if (cost < bestCost) { + bestNode = node; + bestCost = cost; + } + } + if (!bestNode) break; + // Merge all children + const reduction = bestNode.entries - 1; + bestNode.active = true; + bestNode.entries = 1; + currentCount -= reduction; + let parent = bestNode.parent; + while (parent) { + parent.entries -= reduction; + parent = parent.parent; + } + const queue = new Set(bestNode.children); + for (const node of queue) { + node.active = false; + node.entries = 0; + if (node.children) { + for (const child of node.children) queue.add(child); + } + } + } + // Write down new plan + const newPlan = new Map(); + for (const rootNode of treeMap.values()) { + if (!rootNode.active) continue; + const map = new Map(); + const queue = new Set([rootNode]); + for (const node of queue) { + if (node.active && node !== rootNode) continue; + if (node.value) { + if (Array.isArray(node.value)) { + for (const item of node.value) { + map.set(item, node.filePath); + } + } else { + map.set(node.value, node.filePath); + } + } + if (node.children) { + for (const child of node.children) { + queue.add(child); + } + } + } + newPlan.set(rootNode.filePath, map); + } + return newPlan; +}; diff --git a/node_modules/mathjs/examples/node_modules/watchpack/lib/watchEventSource.js b/node_modules/mathjs/examples/node_modules/watchpack/lib/watchEventSource.js new file mode 100644 index 0000000..3583c2e --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/watchpack/lib/watchEventSource.js @@ -0,0 +1,335 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const { EventEmitter } = require("events"); +const reducePlan = require("./reducePlan"); + +const IS_OSX = require("os").platform() === "darwin"; +const IS_WIN = require("os").platform() === "win32"; +const SUPPORTS_RECURSIVE_WATCHING = IS_OSX || IS_WIN; + +const watcherLimit = + +process.env.WATCHPACK_WATCHER_LIMIT || (IS_OSX ? 2000 : 10000); + +const recursiveWatcherLogging = !!process.env + .WATCHPACK_RECURSIVE_WATCHER_LOGGING; + +let isBatch = false; +let watcherCount = 0; + +/** @type {Map} */ +const pendingWatchers = new Map(); + +/** @type {Map} */ +const recursiveWatchers = new Map(); + +/** @type {Map} */ +const directWatchers = new Map(); + +/** @type {Map} */ +const underlyingWatcher = new Map(); + +class DirectWatcher { + constructor(filePath) { + this.filePath = filePath; + this.watchers = new Set(); + this.watcher = undefined; + try { + const watcher = fs.watch(filePath); + this.watcher = watcher; + watcher.on("change", (type, filename) => { + for (const w of this.watchers) { + w.emit("change", type, filename); + } + }); + watcher.on("error", error => { + for (const w of this.watchers) { + w.emit("error", error); + } + }); + } catch (err) { + process.nextTick(() => { + for (const w of this.watchers) { + w.emit("error", err); + } + }); + } + watcherCount++; + } + + add(watcher) { + underlyingWatcher.set(watcher, this); + this.watchers.add(watcher); + } + + remove(watcher) { + this.watchers.delete(watcher); + if (this.watchers.size === 0) { + directWatchers.delete(this.filePath); + watcherCount--; + if (this.watcher) this.watcher.close(); + } + } + + getWatchers() { + return this.watchers; + } +} + +class RecursiveWatcher { + constructor(rootPath) { + this.rootPath = rootPath; + /** @type {Map} */ + this.mapWatcherToPath = new Map(); + /** @type {Map>} */ + this.mapPathToWatchers = new Map(); + this.watcher = undefined; + try { + const watcher = fs.watch(rootPath, { + recursive: true + }); + this.watcher = watcher; + watcher.on("change", (type, filename) => { + if (!filename) { + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] dispatch ${type} event in recursive watcher (${ + this.rootPath + }) to all watchers\n` + ); + } + for (const w of this.mapWatcherToPath.keys()) { + w.emit("change", type); + } + } else { + const dir = path.dirname(filename); + const watchers = this.mapPathToWatchers.get(dir); + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] dispatch ${type} event in recursive watcher (${ + this.rootPath + }) for '${filename}' to ${ + watchers ? watchers.size : 0 + } watchers\n` + ); + } + if (watchers === undefined) return; + for (const w of watchers) { + w.emit("change", type, path.basename(filename)); + } + } + }); + watcher.on("error", error => { + for (const w of this.mapWatcherToPath.keys()) { + w.emit("error", error); + } + }); + } catch (err) { + process.nextTick(() => { + for (const w of this.mapWatcherToPath.keys()) { + w.emit("error", err); + } + }); + } + watcherCount++; + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] created recursive watcher at ${rootPath}\n` + ); + } + } + + add(filePath, watcher) { + underlyingWatcher.set(watcher, this); + const subpath = filePath.slice(this.rootPath.length + 1) || "."; + this.mapWatcherToPath.set(watcher, subpath); + const set = this.mapPathToWatchers.get(subpath); + if (set === undefined) { + const newSet = new Set(); + newSet.add(watcher); + this.mapPathToWatchers.set(subpath, newSet); + } else { + set.add(watcher); + } + } + + remove(watcher) { + const subpath = this.mapWatcherToPath.get(watcher); + if (!subpath) return; + this.mapWatcherToPath.delete(watcher); + const set = this.mapPathToWatchers.get(subpath); + set.delete(watcher); + if (set.size === 0) { + this.mapPathToWatchers.delete(subpath); + } + if (this.mapWatcherToPath.size === 0) { + recursiveWatchers.delete(this.rootPath); + watcherCount--; + if (this.watcher) this.watcher.close(); + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] closed recursive watcher at ${this.rootPath}\n` + ); + } + } + } + + getWatchers() { + return this.mapWatcherToPath; + } +} + +class Watcher extends EventEmitter { + close() { + if (pendingWatchers.has(this)) { + pendingWatchers.delete(this); + return; + } + const watcher = underlyingWatcher.get(this); + watcher.remove(this); + underlyingWatcher.delete(this); + } +} + +const createDirectWatcher = filePath => { + const existing = directWatchers.get(filePath); + if (existing !== undefined) return existing; + const w = new DirectWatcher(filePath); + directWatchers.set(filePath, w); + return w; +}; + +const createRecursiveWatcher = rootPath => { + const existing = recursiveWatchers.get(rootPath); + if (existing !== undefined) return existing; + const w = new RecursiveWatcher(rootPath); + recursiveWatchers.set(rootPath, w); + return w; +}; + +const execute = () => { + /** @type {Map} */ + const map = new Map(); + const addWatcher = (watcher, filePath) => { + const entry = map.get(filePath); + if (entry === undefined) { + map.set(filePath, watcher); + } else if (Array.isArray(entry)) { + entry.push(watcher); + } else { + map.set(filePath, [entry, watcher]); + } + }; + for (const [watcher, filePath] of pendingWatchers) { + addWatcher(watcher, filePath); + } + pendingWatchers.clear(); + + // Fast case when we are not reaching the limit + if (!SUPPORTS_RECURSIVE_WATCHING || watcherLimit - watcherCount >= map.size) { + // Create watchers for all entries in the map + for (const [filePath, entry] of map) { + const w = createDirectWatcher(filePath); + if (Array.isArray(entry)) { + for (const item of entry) w.add(item); + } else { + w.add(entry); + } + } + return; + } + + // Reconsider existing watchers to improving watch plan + for (const watcher of recursiveWatchers.values()) { + for (const [w, subpath] of watcher.getWatchers()) { + addWatcher(w, path.join(watcher.rootPath, subpath)); + } + } + for (const watcher of directWatchers.values()) { + for (const w of watcher.getWatchers()) { + addWatcher(w, watcher.filePath); + } + } + + // Merge map entries to keep watcher limit + // Create a 10% buffer to be able to enter fast case more often + const plan = reducePlan(map, watcherLimit * 0.9); + + // Update watchers for all entries in the map + for (const [filePath, entry] of plan) { + if (entry.size === 1) { + for (const [watcher, filePath] of entry) { + const w = createDirectWatcher(filePath); + const old = underlyingWatcher.get(watcher); + if (old === w) continue; + w.add(watcher); + if (old !== undefined) old.remove(watcher); + } + } else { + const filePaths = new Set(entry.values()); + if (filePaths.size > 1) { + const w = createRecursiveWatcher(filePath); + for (const [watcher, watcherPath] of entry) { + const old = underlyingWatcher.get(watcher); + if (old === w) continue; + w.add(watcherPath, watcher); + if (old !== undefined) old.remove(watcher); + } + } else { + for (const filePath of filePaths) { + const w = createDirectWatcher(filePath); + for (const watcher of entry.keys()) { + const old = underlyingWatcher.get(watcher); + if (old === w) continue; + w.add(watcher); + if (old !== undefined) old.remove(watcher); + } + } + } + } + } +}; + +exports.watch = filePath => { + const watcher = new Watcher(); + // Find an existing watcher + const directWatcher = directWatchers.get(filePath); + if (directWatcher !== undefined) { + directWatcher.add(watcher); + return watcher; + } + let current = filePath; + for (;;) { + const recursiveWatcher = recursiveWatchers.get(current); + if (recursiveWatcher !== undefined) { + recursiveWatcher.add(filePath, watcher); + return watcher; + } + const parent = path.dirname(current); + if (parent === current) break; + current = parent; + } + // Queue up watcher for creation + pendingWatchers.set(watcher, filePath); + if (!isBatch) execute(); + return watcher; +}; + +exports.batch = fn => { + isBatch = true; + try { + fn(); + } finally { + isBatch = false; + execute(); + } +}; + +exports.getNumberOfWatchers = () => { + return watcherCount; +}; diff --git a/node_modules/mathjs/examples/node_modules/watchpack/lib/watchpack.js b/node_modules/mathjs/examples/node_modules/watchpack/lib/watchpack.js new file mode 100644 index 0000000..ddc9138 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/watchpack/lib/watchpack.js @@ -0,0 +1,383 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const getWatcherManager = require("./getWatcherManager"); +const LinkResolver = require("./LinkResolver"); +const EventEmitter = require("events").EventEmitter; +const globToRegExp = require("glob-to-regexp"); +const watchEventSource = require("./watchEventSource"); + +const EMPTY_ARRAY = []; +const EMPTY_OPTIONS = {}; + +function addWatchersToSet(watchers, set) { + for (const ww of watchers) { + const w = ww.watcher; + if (!set.has(w.directoryWatcher)) { + set.add(w.directoryWatcher); + } + } +} + +const stringToRegexp = ignored => { + const source = globToRegExp(ignored, { globstar: true, extended: true }) + .source; + const matchingStart = source.slice(0, source.length - 1) + "(?:$|\\/)"; + return matchingStart; +}; + +const ignoredToFunction = ignored => { + if (Array.isArray(ignored)) { + const regexp = new RegExp(ignored.map(i => stringToRegexp(i)).join("|")); + return x => regexp.test(x.replace(/\\/g, "/")); + } else if (typeof ignored === "string") { + const regexp = new RegExp(stringToRegexp(ignored)); + return x => regexp.test(x.replace(/\\/g, "/")); + } else if (ignored instanceof RegExp) { + return x => ignored.test(x.replace(/\\/g, "/")); + } else if (ignored instanceof Function) { + return ignored; + } else if (ignored) { + throw new Error(`Invalid option for 'ignored': ${ignored}`); + } else { + return () => false; + } +}; + +const normalizeOptions = options => { + return { + followSymlinks: !!options.followSymlinks, + ignored: ignoredToFunction(options.ignored), + poll: options.poll + }; +}; + +const normalizeCache = new WeakMap(); +const cachedNormalizeOptions = options => { + const cacheEntry = normalizeCache.get(options); + if (cacheEntry !== undefined) return cacheEntry; + const normalized = normalizeOptions(options); + normalizeCache.set(options, normalized); + return normalized; +}; + +class WatchpackFileWatcher { + constructor(watchpack, watcher, files) { + this.files = Array.isArray(files) ? files : [files]; + this.watcher = watcher; + watcher.on("initial-missing", type => { + for (const file of this.files) { + if (!watchpack._missing.has(file)) + watchpack._onRemove(file, file, type); + } + }); + watcher.on("change", (mtime, type) => { + for (const file of this.files) { + watchpack._onChange(file, mtime, file, type); + } + }); + watcher.on("remove", type => { + for (const file of this.files) { + watchpack._onRemove(file, file, type); + } + }); + } + + update(files) { + if (!Array.isArray(files)) { + if (this.files.length !== 1) { + this.files = [files]; + } else if (this.files[0] !== files) { + this.files[0] = files; + } + } else { + this.files = files; + } + } + + close() { + this.watcher.close(); + } +} + +class WatchpackDirectoryWatcher { + constructor(watchpack, watcher, directories) { + this.directories = Array.isArray(directories) ? directories : [directories]; + this.watcher = watcher; + watcher.on("initial-missing", type => { + for (const item of this.directories) { + watchpack._onRemove(item, item, type); + } + }); + watcher.on("change", (file, mtime, type) => { + for (const item of this.directories) { + watchpack._onChange(item, mtime, file, type); + } + }); + watcher.on("remove", type => { + for (const item of this.directories) { + watchpack._onRemove(item, item, type); + } + }); + } + + update(directories) { + if (!Array.isArray(directories)) { + if (this.directories.length !== 1) { + this.directories = [directories]; + } else if (this.directories[0] !== directories) { + this.directories[0] = directories; + } + } else { + this.directories = directories; + } + } + + close() { + this.watcher.close(); + } +} + +class Watchpack extends EventEmitter { + constructor(options) { + super(); + if (!options) options = EMPTY_OPTIONS; + this.options = options; + this.aggregateTimeout = + typeof options.aggregateTimeout === "number" + ? options.aggregateTimeout + : 200; + this.watcherOptions = cachedNormalizeOptions(options); + this.watcherManager = getWatcherManager(this.watcherOptions); + this.fileWatchers = new Map(); + this.directoryWatchers = new Map(); + this._missing = new Set(); + this.startTime = undefined; + this.paused = false; + this.aggregatedChanges = new Set(); + this.aggregatedRemovals = new Set(); + this.aggregateTimer = undefined; + this._onTimeout = this._onTimeout.bind(this); + } + + watch(arg1, arg2, arg3) { + let files, directories, missing, startTime; + if (!arg2) { + ({ + files = EMPTY_ARRAY, + directories = EMPTY_ARRAY, + missing = EMPTY_ARRAY, + startTime + } = arg1); + } else { + files = arg1; + directories = arg2; + missing = EMPTY_ARRAY; + startTime = arg3; + } + this.paused = false; + const fileWatchers = this.fileWatchers; + const directoryWatchers = this.directoryWatchers; + const ignored = this.watcherOptions.ignored; + const filter = path => !ignored(path); + const addToMap = (map, key, item) => { + const list = map.get(key); + if (list === undefined) { + map.set(key, item); + } else if (Array.isArray(list)) { + list.push(item); + } else { + map.set(key, [list, item]); + } + }; + const fileWatchersNeeded = new Map(); + const directoryWatchersNeeded = new Map(); + const missingFiles = new Set(); + if (this.watcherOptions.followSymlinks) { + const resolver = new LinkResolver(); + for (const file of files) { + if (filter(file)) { + for (const innerFile of resolver.resolve(file)) { + if (file === innerFile || filter(innerFile)) { + addToMap(fileWatchersNeeded, innerFile, file); + } + } + } + } + for (const file of missing) { + if (filter(file)) { + for (const innerFile of resolver.resolve(file)) { + if (file === innerFile || filter(innerFile)) { + missingFiles.add(file); + addToMap(fileWatchersNeeded, innerFile, file); + } + } + } + } + for (const dir of directories) { + if (filter(dir)) { + let first = true; + for (const innerItem of resolver.resolve(dir)) { + if (filter(innerItem)) { + addToMap( + first ? directoryWatchersNeeded : fileWatchersNeeded, + innerItem, + dir + ); + } + first = false; + } + } + } + } else { + for (const file of files) { + if (filter(file)) { + addToMap(fileWatchersNeeded, file, file); + } + } + for (const file of missing) { + if (filter(file)) { + missingFiles.add(file); + addToMap(fileWatchersNeeded, file, file); + } + } + for (const dir of directories) { + if (filter(dir)) { + addToMap(directoryWatchersNeeded, dir, dir); + } + } + } + // Close unneeded old watchers + // and update existing watchers + for (const [key, w] of fileWatchers) { + const needed = fileWatchersNeeded.get(key); + if (needed === undefined) { + w.close(); + fileWatchers.delete(key); + } else { + w.update(needed); + fileWatchersNeeded.delete(key); + } + } + for (const [key, w] of directoryWatchers) { + const needed = directoryWatchersNeeded.get(key); + if (needed === undefined) { + w.close(); + directoryWatchers.delete(key); + } else { + w.update(needed); + directoryWatchersNeeded.delete(key); + } + } + // Create new watchers and install handlers on these watchers + watchEventSource.batch(() => { + for (const [key, files] of fileWatchersNeeded) { + const watcher = this.watcherManager.watchFile(key, startTime); + if (watcher) { + fileWatchers.set(key, new WatchpackFileWatcher(this, watcher, files)); + } + } + for (const [key, directories] of directoryWatchersNeeded) { + const watcher = this.watcherManager.watchDirectory(key, startTime); + if (watcher) { + directoryWatchers.set( + key, + new WatchpackDirectoryWatcher(this, watcher, directories) + ); + } + } + }); + this._missing = missingFiles; + this.startTime = startTime; + } + + close() { + this.paused = true; + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + for (const w of this.fileWatchers.values()) w.close(); + for (const w of this.directoryWatchers.values()) w.close(); + this.fileWatchers.clear(); + this.directoryWatchers.clear(); + } + + pause() { + this.paused = true; + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + } + + getTimes() { + const directoryWatchers = new Set(); + addWatchersToSet(this.fileWatchers.values(), directoryWatchers); + addWatchersToSet(this.directoryWatchers.values(), directoryWatchers); + const obj = Object.create(null); + for (const w of directoryWatchers) { + const times = w.getTimes(); + for (const file of Object.keys(times)) obj[file] = times[file]; + } + return obj; + } + + getTimeInfoEntries() { + const map = new Map(); + this.collectTimeInfoEntries(map, map); + return map; + } + + collectTimeInfoEntries(fileTimestamps, directoryTimestamps) { + const allWatchers = new Set(); + addWatchersToSet(this.fileWatchers.values(), allWatchers); + addWatchersToSet(this.directoryWatchers.values(), allWatchers); + const safeTime = { value: 0 }; + for (const w of allWatchers) { + w.collectTimeInfoEntries(fileTimestamps, directoryTimestamps, safeTime); + } + } + + getAggregated() { + if (this.aggregateTimer) { + clearTimeout(this.aggregateTimer); + this.aggregateTimer = undefined; + } + const changes = this.aggregatedChanges; + const removals = this.aggregatedRemovals; + this.aggregatedChanges = new Set(); + this.aggregatedRemovals = new Set(); + return { changes, removals }; + } + + _onChange(item, mtime, file, type) { + file = file || item; + if (!this.paused) { + this.emit("change", file, mtime, type); + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + this.aggregateTimer = setTimeout(this._onTimeout, this.aggregateTimeout); + } + this.aggregatedRemovals.delete(item); + this.aggregatedChanges.add(item); + } + + _onRemove(item, file, type) { + file = file || item; + if (!this.paused) { + this.emit("remove", file, type); + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + this.aggregateTimer = setTimeout(this._onTimeout, this.aggregateTimeout); + } + this.aggregatedChanges.delete(item); + this.aggregatedRemovals.add(item); + } + + _onTimeout() { + this.aggregateTimer = undefined; + const changes = this.aggregatedChanges; + const removals = this.aggregatedRemovals; + this.aggregatedChanges = new Set(); + this.aggregatedRemovals = new Set(); + this.emit("aggregated", changes, removals); + } +} + +module.exports = Watchpack; diff --git a/node_modules/mathjs/examples/node_modules/watchpack/package.json b/node_modules/mathjs/examples/node_modules/watchpack/package.json new file mode 100644 index 0000000..c0befc5 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/watchpack/package.json @@ -0,0 +1,49 @@ +{ + "name": "watchpack", + "version": "2.3.1", + "description": "", + "main": "./lib/watchpack.js", + "directories": { + "test": "test" + }, + "files": [ + "lib/" + ], + "scripts": { + "pretest": "yarn lint", + "test": "mocha", + "lint": "eslint lib", + "precover": "yarn lint", + "pretty-files": "prettier \"lib/**.*\" \"test/**/*.js\" --write", + "cover": "istanbul cover node_modules/mocha/bin/_mocha" + }, + "repository": { + "type": "git", + "url": "https://github.com/webpack/watchpack.git" + }, + "author": "Tobias Koppers @sokra", + "license": "MIT", + "bugs": { + "url": "https://github.com/webpack/watchpack/issues" + }, + "homepage": "https://github.com/webpack/watchpack", + "devDependencies": { + "coveralls": "^3.0.0", + "eslint": "^5.11.1", + "eslint-config-prettier": "^4.3.0", + "eslint-plugin-prettier": "^3.1.0", + "istanbul": "^0.4.3", + "mocha": "^5.0.1", + "prettier": "^1.11.0", + "rimraf": "^2.6.2", + "should": "^8.3.1", + "write-file-atomic": "^3.0.1" + }, + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } +} diff --git a/node_modules/mathjs/examples/node_modules/webpack-cli/README.md b/node_modules/mathjs/examples/node_modules/webpack-cli/README.md new file mode 100644 index 0000000..063b299 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/webpack-cli/README.md @@ -0,0 +1,147 @@ + + +# webpack CLI + +The official CLI of webpack + +## About + +webpack CLI provides a flexible set of commands for developers to increase speed when setting up a custom webpack project. As of webpack v4, webpack is not expecting a configuration file, but often developers want to create a more custom webpack configuration based on their use-cases and needs. webpack CLI addresses these needs by providing a set of tools to improve the setup of custom webpack configuration. + +## How to install + +When you have followed the [Getting Started](https://webpack.js.org/guides/getting-started/) guide of webpack then webpack CLI is already installed! + +Otherwise + +```bash +npm install --save-dev webpack-cli +``` + +or + +```bash +yarn add webpack-cli --dev +``` + +## Supported arguments and commands + +### Usage + +All interactions with webpack-cli are of the form + +```bash +npx webpack-cli [command] [options] +``` + +If no command is specified then `bundle` command is used by default + +### Help Usage + +To display basic commands and arguments - + +```bash +npx webpack-cli --help +``` + +To display all supported commands and arguments - + +```bash +npx webpack-cli --help=verbose +``` + +or + +```bash +npx webpack-cli --help verbose +``` + +### Available Commands + +``` + build|bundle|b [entries...] [options] Run webpack (default command, can be omitted). + configtest|t [config-path] Validate a webpack configuration. + help|h [command] [option] Display help for commands and options. + info|i [options] Outputs information about your system. + init|create|new|c|n [generation-path] [options] Initialize a new webpack project. + loader|l [output-path] [options] Scaffold a loader. + migrate|m [new-config-path] Migrate a configuration to a new version. + plugin|p [output-path] [options] Scaffold a plugin. + serve|server|s [entries...] [options] Run the webpack dev server. + version|v [commands...] Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and commands. + watch|w [entries...] [options] Run webpack and watch for files changes. +``` + +### webpack 4 + +``` + Options: + --analyze It invokes webpack-bundle-analyzer plugin to get bundle information + -c, --config Provide path to a webpack configuration file e.g. ./webpack.config.js. + --config-name Name of the configuration to use. + -m, --merge Merge two or more configurations using 'webpack-merge'. + --env Environment passed to the configuration when it is a function. + --node-env Sets process.env.NODE_ENV to the specified value. + --progress [value] Print compilation progress during build. + -j, --json [value] Prints result as JSON or store it in a file. + -d, --devtool Determine source maps to use. + --no-devtool Do not generate source maps. + --entry The entry point(s) of your application e.g. ./src/main.js. + -h, --hot [value] Enables Hot Module Replacement + --no-hot Disables Hot Module Replacement + --mode Defines the mode to pass to webpack. + --name Name of the configuration. Used when loading multiple configurations. + -o, --output-path Output location of the file generated by webpack e.g. ./dist/. + --prefetch Prefetch this request + --stats [value] It instructs webpack on how to treat the stats e.g. verbose. + --no-stats Disable stats output. + -t, --target Sets the build target e.g. node. + -w, --watch Watch for files changes. + --no-watch Do not watch for file changes. + --watch-options-stdin Stop watching when stdin stream has ended. + --no-watch-options-stdin Do not stop watching when stdin stream has ended. + +Global options: + --color Enable colors on console. + --no-color Disable colors on console. + -v, --version Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and commands. + -h, --help [verbose] Display help for commands and options. +``` + +### webpack 5 + +Checkout [`OPTIONS.md`](https://github.com/webpack/webpack-cli/blob/master/OPTIONS.md) to see list of all available options. + +## Exit codes and their meanings + +| Exit Code | Description | +| --------- | -------------------------------------------------- | +| `0` | Success | +| `1` | Errors from webpack | +| `2` | Configuration/options problem or an internal error | + +## CLI Environment Variables + +| Environment Variable | Description | +| ----------------------------------- | ------------------------------------------------------------------- | +| `WEBPACK_CLI_SKIP_IMPORT_LOCAL` | when `true` it will skip using the local instance of `webpack-cli`. | +| `WEBPACK_CLI_FORCE_LOAD_ESM_CONFIG` | when `true` it will force load the ESM config. | +| `WEBPACK_PACKAGE` | Use a custom webpack version in CLI. | +| `WEBPACK_DEV_SERVER_PACKAGE` | Use a custom webpack-dev-server version in CLI. | +| `WEBPACK_CLI_HELP_WIDTH` | Use custom width for help output. | + +## Configuration Environment Variables + +You can use the following environment variables inside your webpack configuration: + +| Environment Variable | Description | +| -------------------- | -------------------------------------------- | +| `WEBPACK_SERVE` | `true` if `serve\|s` is being used. | +| `WEBPACK_BUILD` | `true` if `build\|bundle\|b` is being used. | +| `WEBPACK_WATCH` | `true` if `--watch\|watch\|w` is being used. | + +Checkout [webpack.js.org](https://webpack.js.org/api/cli/) for more detailed documentation of `webpack-cli`. diff --git a/node_modules/mathjs/examples/node_modules/webpack-cli/bin/cli.js b/node_modules/mathjs/examples/node_modules/webpack-cli/bin/cli.js new file mode 100644 index 0000000..5305a83 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/webpack-cli/bin/cli.js @@ -0,0 +1,17 @@ +#!/usr/bin/env node + +"use strict"; + +const importLocal = require("import-local"); +const runCLI = require("../lib/bootstrap"); + +if (!process.env.WEBPACK_CLI_SKIP_IMPORT_LOCAL) { + // Prefer the local installation of `webpack-cli` + if (importLocal(__filename)) { + return; + } +} + +process.title = "webpack"; + +runCLI(process.argv); diff --git a/node_modules/mathjs/examples/node_modules/webpack-cli/lib/bootstrap.js b/node_modules/mathjs/examples/node_modules/webpack-cli/lib/bootstrap.js new file mode 100644 index 0000000..ef63a0b --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/webpack-cli/lib/bootstrap.js @@ -0,0 +1,15 @@ +const WebpackCLI = require("./webpack-cli"); + +const runCLI = async (args) => { + // Create a new instance of the CLI object + const cli = new WebpackCLI(); + + try { + await cli.run(args); + } catch (error) { + cli.logger.error(error); + process.exit(2); + } +}; + +module.exports = runCLI; diff --git a/node_modules/mathjs/examples/node_modules/webpack-cli/lib/index.js b/node_modules/mathjs/examples/node_modules/webpack-cli/lib/index.js new file mode 100644 index 0000000..4dfb248 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/webpack-cli/lib/index.js @@ -0,0 +1,5 @@ +const CLI = require("./webpack-cli"); + +module.exports = CLI; +// TODO remove after drop `@webpack-cli/migrate` +module.exports.utils = { logger: console }; diff --git a/node_modules/mathjs/examples/node_modules/webpack-cli/lib/plugins/CLIPlugin.js b/node_modules/mathjs/examples/node_modules/webpack-cli/lib/plugins/CLIPlugin.js new file mode 100644 index 0000000..2b1c083 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/webpack-cli/lib/plugins/CLIPlugin.js @@ -0,0 +1,132 @@ +class CLIPlugin { + constructor(options) { + this.options = options; + } + + setupHotPlugin(compiler) { + const { HotModuleReplacementPlugin } = compiler.webpack || require("webpack"); + const hotModuleReplacementPlugin = Boolean( + compiler.options.plugins.find((plugin) => plugin instanceof HotModuleReplacementPlugin), + ); + + if (!hotModuleReplacementPlugin) { + new HotModuleReplacementPlugin().apply(compiler); + } + } + + setupPrefetchPlugin(compiler) { + const { PrefetchPlugin } = compiler.webpack || require("webpack"); + + new PrefetchPlugin(null, this.options.prefetch).apply(compiler); + } + + async setupBundleAnalyzerPlugin(compiler) { + // eslint-disable-next-line node/no-extraneous-require + const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer"); + const bundleAnalyzerPlugin = Boolean( + compiler.options.plugins.find((plugin) => plugin instanceof BundleAnalyzerPlugin), + ); + + if (!bundleAnalyzerPlugin) { + new BundleAnalyzerPlugin().apply(compiler); + } + } + + setupProgressPlugin(compiler) { + const { ProgressPlugin } = compiler.webpack || require("webpack"); + const progressPlugin = Boolean( + compiler.options.plugins.find((plugin) => plugin instanceof ProgressPlugin), + ); + + if (!progressPlugin) { + new ProgressPlugin({ + profile: this.options.progress === "profile", + }).apply(compiler); + } + } + + setupHelpfulOutput(compiler) { + const pluginName = "webpack-cli"; + const getCompilationName = () => (compiler.name ? `'${compiler.name}'` : ""); + const logCompilation = (message) => { + if (process.env.WEBPACK_CLI_START_FINISH_FORCE_LOG) { + process.stderr.write(message); + } else { + this.logger.log(message); + } + }; + + const { configPath } = this.options; + + compiler.hooks.run.tap(pluginName, () => { + const name = getCompilationName(); + + logCompilation(`Compiler${name ? ` ${name}` : ""} starting... `); + + if (configPath) { + this.logger.log(`Compiler${name ? ` ${name}` : ""} is using config: '${configPath}'`); + } + }); + + compiler.hooks.watchRun.tap(pluginName, (compiler) => { + const { bail, watch } = compiler.options; + + if (bail && watch) { + this.logger.warn( + 'You are using "bail" with "watch". "bail" will still exit webpack when the first error is found.', + ); + } + + const name = getCompilationName(); + + logCompilation(`Compiler${name ? ` ${name}` : ""} starting... `); + + if (configPath) { + this.logger.log(`Compiler${name ? ` ${name}` : ""} is using config: '${configPath}'`); + } + }); + + compiler.hooks.invalid.tap(pluginName, (filename, changeTime) => { + const date = new Date(changeTime * 1000); + + this.logger.log(`File '${filename}' was modified`); + this.logger.log(`Changed time is ${date} (timestamp is ${changeTime})`); + }); + + (compiler.webpack ? compiler.hooks.afterDone : compiler.hooks.done).tap(pluginName, () => { + const name = getCompilationName(); + + logCompilation(`Compiler${name ? ` ${name}` : ""} finished`); + + process.nextTick(() => { + if (compiler.watchMode) { + this.logger.log(`Compiler${name ? `${name}` : ""} is watching files for updates...`); + } + }); + }); + } + + apply(compiler) { + this.logger = compiler.getInfrastructureLogger("webpack-cli"); + + if (this.options.progress) { + this.setupProgressPlugin(compiler); + } + + if (this.options.hot) { + this.setupHotPlugin(compiler); + } + + if (this.options.prefetch) { + this.setupPrefetchPlugin(compiler); + } + + if (this.options.analyze) { + this.setupBundleAnalyzerPlugin(compiler); + } + + this.setupHelpfulOutput(compiler); + } +} + +module.exports = CLIPlugin; diff --git a/node_modules/mathjs/examples/node_modules/webpack-cli/lib/utils/dynamic-import-loader.js b/node_modules/mathjs/examples/node_modules/webpack-cli/lib/utils/dynamic-import-loader.js new file mode 100644 index 0000000..c1221bc --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/webpack-cli/lib/utils/dynamic-import-loader.js @@ -0,0 +1,13 @@ +function dynamicImportLoader() { + let importESM; + + try { + importESM = new Function("id", "return import(id);"); + } catch (e) { + importESM = null; + } + + return importESM; +} + +module.exports = dynamicImportLoader; diff --git a/node_modules/mathjs/examples/node_modules/webpack-cli/lib/webpack-cli.js b/node_modules/mathjs/examples/node_modules/webpack-cli/lib/webpack-cli.js new file mode 100644 index 0000000..b28ba64 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/webpack-cli/lib/webpack-cli.js @@ -0,0 +1,2343 @@ +const fs = require("fs"); +const path = require("path"); +const { pathToFileURL } = require("url"); +const util = require("util"); + +const { program, Option } = require("commander"); + +const WEBPACK_PACKAGE = process.env.WEBPACK_PACKAGE || "webpack"; +const WEBPACK_DEV_SERVER_PACKAGE = process.env.WEBPACK_DEV_SERVER_PACKAGE || "webpack-dev-server"; + +class WebpackCLI { + constructor() { + this.colors = this.createColors(); + this.logger = this.getLogger(); + + // Initialize program + this.program = program; + this.program.name("webpack"); + this.program.configureOutput({ + writeErr: this.logger.error, + outputError: (str, write) => + write(`Error: ${this.capitalizeFirstLetter(str.replace(/^error:/, "").trim())}`), + }); + } + + capitalizeFirstLetter(str) { + if (typeof str !== "string") { + return ""; + } + + return str.charAt(0).toUpperCase() + str.slice(1); + } + + toKebabCase(str) { + return str.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(); + } + + createColors(useColor) { + const { createColors, isColorSupported } = require("colorette"); + + let shouldUseColor; + + if (useColor) { + shouldUseColor = useColor; + } else { + shouldUseColor = isColorSupported; + } + + return { ...createColors({ useColor: shouldUseColor }), isColorSupported: shouldUseColor }; + } + + getLogger() { + return { + error: (val) => console.error(`[webpack-cli] ${this.colors.red(util.format(val))}`), + warn: (val) => console.warn(`[webpack-cli] ${this.colors.yellow(val)}`), + info: (val) => console.info(`[webpack-cli] ${this.colors.cyan(val)}`), + success: (val) => console.log(`[webpack-cli] ${this.colors.green(val)}`), + log: (val) => console.log(`[webpack-cli] ${val}`), + raw: (val) => console.log(val), + }; + } + + checkPackageExists(packageName) { + if (process.versions.pnp) { + return true; + } + + let dir = __dirname; + + do { + try { + if (fs.statSync(path.join(dir, "node_modules", packageName)).isDirectory()) { + return true; + } + } catch (_error) { + // Nothing + } + } while (dir !== (dir = path.dirname(dir))); + + return false; + } + + getAvailablePackageManagers() { + const { sync } = require("execa"); + const installers = ["npm", "yarn", "pnpm"]; + const hasPackageManagerInstalled = (packageManager) => { + try { + sync(packageManager, ["--version"]); + + return packageManager; + } catch (err) { + return false; + } + }; + const availableInstallers = installers.filter((installer) => + hasPackageManagerInstalled(installer), + ); + + if (!availableInstallers.length) { + this.logger.error("No package manager found."); + + process.exit(2); + } + + return availableInstallers; + } + + getDefaultPackageManager() { + const { sync } = require("execa"); + const hasLocalNpm = fs.existsSync(path.resolve(process.cwd(), "package-lock.json")); + + if (hasLocalNpm) { + return "npm"; + } + + const hasLocalYarn = fs.existsSync(path.resolve(process.cwd(), "yarn.lock")); + + if (hasLocalYarn) { + return "yarn"; + } + + const hasLocalPnpm = fs.existsSync(path.resolve(process.cwd(), "pnpm-lock.yaml")); + + if (hasLocalPnpm) { + return "pnpm"; + } + + try { + // the sync function below will fail if npm is not installed, + // an error will be thrown + if (sync("npm", ["--version"])) { + return "npm"; + } + } catch (e) { + // Nothing + } + + try { + // the sync function below will fail if yarn is not installed, + // an error will be thrown + if (sync("yarn", ["--version"])) { + return "yarn"; + } + } catch (e) { + // Nothing + } + + try { + // the sync function below will fail if pnpm is not installed, + // an error will be thrown + if (sync("pnpm", ["--version"])) { + return "pnpm"; + } + } catch (e) { + this.logger.error("No package manager found."); + + process.exit(2); + } + } + + async doInstall(packageName, options = {}) { + const packageManager = this.getDefaultPackageManager(); + + if (!packageManager) { + this.logger.error("Can't find package manager"); + + process.exit(2); + } + + if (options.preMessage) { + options.preMessage(); + } + + // yarn uses 'add' command, rest npm and pnpm both use 'install' + const commandToBeRun = `${packageManager} ${[ + packageManager === "yarn" ? "add" : "install", + "-D", + packageName, + ].join(" ")}`; + + const prompt = ({ message, defaultResponse, stream }) => { + const readline = require("readline"); + const rl = readline.createInterface({ + input: process.stdin, + output: stream, + }); + + return new Promise((resolve) => { + rl.question(`${message} `, (answer) => { + // Close the stream + rl.close(); + + const response = (answer || defaultResponse).toLowerCase(); + + // Resolve with the input response + if (response === "y" || response === "yes") { + resolve(true); + } else { + resolve(false); + } + }); + }); + }; + + let needInstall; + + try { + needInstall = await prompt({ + message: `[webpack-cli] Would you like to install '${this.colors.green( + packageName, + )}' package? (That will run '${this.colors.green(commandToBeRun)}') (${this.colors.yellow( + "Y/n", + )})`, + defaultResponse: "Y", + stream: process.stderr, + }); + } catch (error) { + this.logger.error(error); + + process.exit(error); + } + + if (needInstall) { + const execa = require("execa"); + + try { + await execa(commandToBeRun, [], { stdio: "inherit", shell: true }); + } catch (error) { + this.logger.error(error); + + process.exit(2); + } + + return packageName; + } + + process.exit(2); + } + + async tryRequireThenImport(module, handleError = true) { + let result; + + try { + result = require(module); + } catch (error) { + const dynamicImportLoader = require("./utils/dynamic-import-loader")(); + if ( + (error.code === "ERR_REQUIRE_ESM" || process.env.WEBPACK_CLI_FORCE_LOAD_ESM_CONFIG) && + pathToFileURL && + dynamicImportLoader + ) { + const urlForConfig = pathToFileURL(module); + + result = await dynamicImportLoader(urlForConfig); + result = result.default; + + return result; + } + + if (handleError) { + this.logger.error(error); + process.exit(2); + } else { + throw error; + } + } + + // For babel/typescript + if (result && typeof result === "object" && "default" in result) { + result = result.default || {}; + } + + return result || {}; + } + + loadJSONFile(pathToFile, handleError = true) { + let result; + + try { + result = require(pathToFile); + } catch (error) { + if (handleError) { + this.logger.error(error); + process.exit(2); + } else { + throw error; + } + } + + return result; + } + + async makeCommand(commandOptions, options, action) { + const alreadyLoaded = this.program.commands.find( + (command) => + command.name() === commandOptions.name.split(" ")[0] || + command.aliases().includes(commandOptions.alias), + ); + + if (alreadyLoaded) { + return; + } + + const command = this.program.command(commandOptions.name, { + noHelp: commandOptions.noHelp, + hidden: commandOptions.hidden, + isDefault: commandOptions.isDefault, + }); + + if (commandOptions.description) { + command.description(commandOptions.description, commandOptions.argsDescription); + } + + if (commandOptions.usage) { + command.usage(commandOptions.usage); + } + + if (Array.isArray(commandOptions.alias)) { + command.aliases(commandOptions.alias); + } else { + command.alias(commandOptions.alias); + } + + if (commandOptions.pkg) { + command.pkg = commandOptions.pkg; + } else { + command.pkg = "webpack-cli"; + } + + const { forHelp } = this.program; + + let allDependenciesInstalled = true; + + if (commandOptions.dependencies && commandOptions.dependencies.length > 0) { + for (const dependency of commandOptions.dependencies) { + const isPkgExist = this.checkPackageExists(dependency); + + if (isPkgExist) { + continue; + } else if (!isPkgExist && forHelp) { + allDependenciesInstalled = false; + continue; + } + + let skipInstallation = false; + + // Allow to use `./path/to/webpack.js` outside `node_modules` + if (dependency === WEBPACK_PACKAGE && fs.existsSync(WEBPACK_PACKAGE)) { + skipInstallation = true; + } + + // Allow to use `./path/to/webpack-dev-server.js` outside `node_modules` + if (dependency === WEBPACK_DEV_SERVER_PACKAGE && fs.existsSync(WEBPACK_PACKAGE)) { + skipInstallation = true; + } + + if (skipInstallation) { + continue; + } + + await this.doInstall(dependency, { + preMessage: () => { + this.logger.error( + `For using '${this.colors.green( + commandOptions.name.split(" ")[0], + )}' command you need to install: '${this.colors.green(dependency)}' package.`, + ); + }, + }); + } + } + + if (options) { + if (typeof options === "function") { + if (forHelp && !allDependenciesInstalled) { + command.description( + `${ + commandOptions.description + } To see all available options you need to install ${commandOptions.dependencies + .map((dependency) => `'${dependency}'`) + .join(", ")}.`, + ); + options = []; + } else { + options = await options(); + } + } + + options.forEach((optionForCommand) => { + this.makeOption(command, optionForCommand); + }); + } + + command.action(action); + + return command; + } + + makeOption(command, option) { + let mainOption; + let negativeOption; + + if (option.configs) { + let needNegativeOption = false; + let negatedDescription; + const mainOptionType = new Set(); + + option.configs.forEach((config) => { + // Possible value: "enum" | "string" | "path" | "number" | "boolean" | "RegExp" | "reset" + switch (config.type) { + case "reset": + mainOptionType.add(Boolean); + break; + case "boolean": + if (!needNegativeOption) { + needNegativeOption = true; + negatedDescription = config.negatedDescription; + } + + mainOptionType.add(Boolean); + break; + case "number": + mainOptionType.add(Number); + break; + case "string": + case "path": + case "RegExp": + mainOptionType.add(String); + break; + case "enum": { + let hasFalseEnum = false; + + const enumTypes = config.values.map((value) => { + switch (typeof value) { + case "string": + mainOptionType.add(String); + break; + case "number": + mainOptionType.add(Number); + break; + case "boolean": + if (!hasFalseEnum && value === false) { + hasFalseEnum = true; + break; + } + + mainOptionType.add(Boolean); + break; + } + }); + + if (!needNegativeOption) { + needNegativeOption = hasFalseEnum; + negatedDescription = config.negatedDescription; + } + + return enumTypes; + } + } + }); + + mainOption = { + flags: option.alias ? `-${option.alias}, --${option.name}` : `--${option.name}`, + description: option.description || "", + type: mainOptionType, + multiple: option.multiple, + defaultValue: option.defaultValue, + }; + + if (needNegativeOption) { + negativeOption = { + flags: `--no-${option.name}`, + description: + negatedDescription || option.negatedDescription || `Negative '${option.name}' option.`, + }; + } + } else { + mainOption = { + flags: option.alias ? `-${option.alias}, --${option.name}` : `--${option.name}`, + // TODO `describe` used by `webpack-dev-server@3` + description: option.description || option.describe || "", + type: option.type + ? new Set(Array.isArray(option.type) ? option.type : [option.type]) + : new Set([Boolean]), + multiple: option.multiple, + defaultValue: option.defaultValue, + }; + + if (option.negative) { + negativeOption = { + flags: `--no-${option.name}`, + description: option.negatedDescription + ? option.negatedDescription + : `Negative '${option.name}' option.`, + }; + } + } + + if (mainOption.type.size > 1 && mainOption.type.has(Boolean)) { + mainOption.flags = `${mainOption.flags} [value${mainOption.multiple ? "..." : ""}]`; + } else if (mainOption.type.size > 0 && !mainOption.type.has(Boolean)) { + mainOption.flags = `${mainOption.flags} `; + } + + if (mainOption.type.size === 1) { + if (mainOption.type.has(Number)) { + let skipDefault = true; + + const optionForCommand = new Option(mainOption.flags, mainOption.description) + .argParser((value, prev = []) => { + if (mainOption.defaultValue && mainOption.multiple && skipDefault) { + prev = []; + skipDefault = false; + } + + return mainOption.multiple ? [].concat(prev).concat(Number(value)) : Number(value); + }) + .default(mainOption.defaultValue); + + optionForCommand.helpLevel = option.helpLevel; + + command.addOption(optionForCommand); + } else if (mainOption.type.has(String)) { + let skipDefault = true; + + const optionForCommand = new Option(mainOption.flags, mainOption.description) + .argParser((value, prev = []) => { + if (mainOption.defaultValue && mainOption.multiple && skipDefault) { + prev = []; + skipDefault = false; + } + + return mainOption.multiple ? [].concat(prev).concat(value) : value; + }) + .default(mainOption.defaultValue); + + optionForCommand.helpLevel = option.helpLevel; + + command.addOption(optionForCommand); + } else if (mainOption.type.has(Boolean)) { + const optionForCommand = new Option(mainOption.flags, mainOption.description).default( + mainOption.defaultValue, + ); + + optionForCommand.helpLevel = option.helpLevel; + + command.addOption(optionForCommand); + } else { + const optionForCommand = new Option(mainOption.flags, mainOption.description) + .argParser(Array.from(mainOption.type)[0]) + .default(mainOption.defaultValue); + + optionForCommand.helpLevel = option.helpLevel; + + command.addOption(optionForCommand); + } + } else if (mainOption.type.size > 1) { + let skipDefault = true; + + const optionForCommand = new Option( + mainOption.flags, + mainOption.description, + mainOption.defaultValue, + ) + .argParser((value, prev = []) => { + if (mainOption.defaultValue && mainOption.multiple && skipDefault) { + prev = []; + skipDefault = false; + } + + if (mainOption.type.has(Number)) { + const numberValue = Number(value); + + if (!isNaN(numberValue)) { + return mainOption.multiple ? [].concat(prev).concat(numberValue) : numberValue; + } + } + + if (mainOption.type.has(String)) { + return mainOption.multiple ? [].concat(prev).concat(value) : value; + } + + return value; + }) + .default(mainOption.defaultValue); + + optionForCommand.helpLevel = option.helpLevel; + + command.addOption(optionForCommand); + } else if (mainOption.type.size === 0 && negativeOption) { + const optionForCommand = new Option(mainOption.flags, mainOption.description); + + // Hide stub option + optionForCommand.hideHelp(); + optionForCommand.helpLevel = option.helpLevel; + + command.addOption(optionForCommand); + } + + if (negativeOption) { + const optionForCommand = new Option(negativeOption.flags, negativeOption.description); + + optionForCommand.helpLevel = option.helpLevel; + + command.addOption(optionForCommand); + } + } + + getBuiltInOptions() { + if (this.builtInOptionsCache) { + return this.builtInOptionsCache; + } + + const minimumHelpFlags = [ + "config", + "config-name", + "merge", + "env", + "mode", + "watch", + "watch-options-stdin", + "stats", + "devtool", + "entry", + "target", + "progress", + "json", + "name", + "output-path", + "node-env", + ]; + + const builtInFlags = [ + // For configs + { + name: "config", + alias: "c", + configs: [ + { + type: "string", + }, + ], + multiple: true, + description: "Provide path to a webpack configuration file e.g. ./webpack.config.js.", + }, + { + name: "config-name", + configs: [ + { + type: "string", + }, + ], + multiple: true, + description: "Name of the configuration to use.", + }, + { + name: "merge", + alias: "m", + configs: [ + { + type: "enum", + values: [true], + }, + ], + description: "Merge two or more configurations using 'webpack-merge'.", + }, + // Complex configs + { + name: "env", + type: (value, previous = {}) => { + // for https://github.com/webpack/webpack-cli/issues/2642 + if (value.endsWith("=")) { + value.concat('""'); + } + + // This ensures we're only splitting by the first `=` + const [allKeys, val] = value.split(/=(.+)/, 2); + const splitKeys = allKeys.split(/\.(?!$)/); + + let prevRef = previous; + + splitKeys.forEach((someKey, index) => { + if (!prevRef[someKey]) { + prevRef[someKey] = {}; + } + + if (typeof prevRef[someKey] === "string") { + prevRef[someKey] = {}; + } + + if (index === splitKeys.length - 1) { + if (typeof val === "string") { + prevRef[someKey] = val; + } else { + prevRef[someKey] = true; + } + } + + prevRef = prevRef[someKey]; + }); + + return previous; + }, + multiple: true, + description: "Environment passed to the configuration when it is a function.", + }, + { + name: "node-env", + configs: [ + { + type: "string", + }, + ], + multiple: false, + description: "Sets process.env.NODE_ENV to the specified value.", + }, + + // Adding more plugins + { + name: "hot", + alias: "h", + configs: [ + { + type: "string", + }, + { + type: "boolean", + }, + ], + negative: true, + description: "Enables Hot Module Replacement", + negatedDescription: "Disables Hot Module Replacement.", + }, + { + name: "analyze", + configs: [ + { + type: "enum", + values: [true], + }, + ], + multiple: false, + description: "It invokes webpack-bundle-analyzer plugin to get bundle information.", + }, + { + name: "progress", + configs: [ + { + type: "string", + }, + { + type: "enum", + values: [true], + }, + ], + description: "Print compilation progress during build.", + }, + { + name: "prefetch", + configs: [ + { + type: "string", + }, + ], + description: "Prefetch this request.", + }, + + // Output options + { + name: "json", + configs: [ + { + type: "string", + }, + { + type: "enum", + values: [true], + }, + ], + alias: "j", + description: "Prints result as JSON or store it in a file.", + }, + + // For webpack@4 + { + name: "entry", + configs: [ + { + type: "string", + }, + ], + multiple: true, + description: "The entry point(s) of your application e.g. ./src/main.js.", + }, + { + name: "output-path", + alias: "o", + configs: [ + { + type: "string", + }, + ], + description: "Output location of the file generated by webpack e.g. ./dist/.", + }, + { + name: "target", + alias: "t", + configs: [ + { + type: "string", + }, + ], + multiple: this.webpack.cli !== undefined, + description: "Sets the build target e.g. node.", + }, + { + name: "devtool", + configs: [ + { + type: "string", + }, + { + type: "enum", + values: [false], + }, + ], + negative: true, + alias: "d", + description: "Determine source maps to use.", + negatedDescription: "Do not generate source maps.", + }, + { + name: "mode", + configs: [ + { + type: "string", + }, + ], + description: "Defines the mode to pass to webpack.", + }, + { + name: "name", + configs: [ + { + type: "string", + }, + ], + description: "Name of the configuration. Used when loading multiple configurations.", + }, + { + name: "stats", + configs: [ + { + type: "string", + }, + { + type: "boolean", + }, + ], + negative: true, + description: "It instructs webpack on how to treat the stats e.g. verbose.", + negatedDescription: "Disable stats output.", + }, + { + name: "watch", + configs: [ + { + type: "boolean", + }, + ], + negative: true, + alias: "w", + description: "Watch for files changes.", + negatedDescription: "Do not watch for file changes.", + }, + { + name: "watch-options-stdin", + configs: [ + { + type: "boolean", + }, + ], + negative: true, + description: "Stop watching when stdin stream has ended.", + negatedDescription: "Do not stop watching when stdin stream has ended.", + }, + ]; + + // Extract all the flags being exported from core. + // A list of cli flags generated by core can be found here https://github.com/webpack/webpack/blob/master/test/__snapshots__/Cli.test.js.snap + const coreFlags = this.webpack.cli + ? Object.entries(this.webpack.cli.getArguments()).map(([flag, meta]) => { + const inBuiltIn = builtInFlags.find((builtInFlag) => builtInFlag.name === flag); + + if (inBuiltIn) { + return { + ...meta, + name: flag, + group: "core", + ...inBuiltIn, + configs: meta.configs || [], + }; + } + + return { ...meta, name: flag, group: "core" }; + }) + : []; + + const options = [] + .concat( + builtInFlags.filter( + (builtInFlag) => !coreFlags.find((coreFlag) => builtInFlag.name === coreFlag.name), + ), + ) + .concat(coreFlags) + .map((option) => { + option.helpLevel = minimumHelpFlags.includes(option.name) ? "minimum" : "verbose"; + + return option; + }); + + this.builtInOptionsCache = options; + + return options; + } + + async loadWebpack(handleError = true) { + return this.tryRequireThenImport(WEBPACK_PACKAGE, handleError); + } + + async run(args, parseOptions) { + // Built-in internal commands + const buildCommandOptions = { + name: "build [entries...]", + alias: ["bundle", "b"], + description: "Run webpack (default command, can be omitted).", + usage: "[entries...] [options]", + dependencies: [WEBPACK_PACKAGE], + }; + const watchCommandOptions = { + name: "watch [entries...]", + alias: "w", + description: "Run webpack and watch for files changes.", + usage: "[entries...] [options]", + dependencies: [WEBPACK_PACKAGE], + }; + const versionCommandOptions = { + name: "version [commands...]", + alias: "v", + description: + "Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and commands.", + }; + const helpCommandOptions = { + name: "help [command] [option]", + alias: "h", + description: "Display help for commands and options.", + }; + // Built-in external commands + const externalBuiltInCommandsInfo = [ + { + name: "serve [entries...]", + alias: ["server", "s"], + pkg: "@webpack-cli/serve", + }, + { + name: "info", + alias: "i", + pkg: "@webpack-cli/info", + }, + { + name: "init", + alias: ["create", "new", "c", "n"], + pkg: "@webpack-cli/generators", + }, + { + name: "loader", + alias: "l", + pkg: "@webpack-cli/generators", + }, + { + name: "plugin", + alias: "p", + pkg: "@webpack-cli/generators", + }, + { + name: "migrate", + alias: "m", + pkg: "@webpack-cli/migrate", + }, + { + name: "configtest [config-path]", + alias: "t", + pkg: "@webpack-cli/configtest", + }, + ]; + + const knownCommands = [ + buildCommandOptions, + watchCommandOptions, + versionCommandOptions, + helpCommandOptions, + ...externalBuiltInCommandsInfo, + ]; + const getCommandName = (name) => name.split(" ")[0]; + const isKnownCommand = (name) => + knownCommands.find( + (command) => + getCommandName(command.name) === name || + (Array.isArray(command.alias) ? command.alias.includes(name) : command.alias === name), + ); + const isCommand = (input, commandOptions) => { + const longName = getCommandName(commandOptions.name); + + if (input === longName) { + return true; + } + + if (commandOptions.alias) { + if (Array.isArray(commandOptions.alias)) { + return commandOptions.alias.includes(input); + } else { + return commandOptions.alias === input; + } + } + + return false; + }; + const findCommandByName = (name) => + this.program.commands.find( + (command) => name === command.name() || command.aliases().includes(name), + ); + const isOption = (value) => value.startsWith("-"); + const isGlobalOption = (value) => + value === "--color" || + value === "--no-color" || + value === "-v" || + value === "--version" || + value === "-h" || + value === "--help"; + + const loadCommandByName = async (commandName, allowToInstall = false) => { + const isBuildCommandUsed = isCommand(commandName, buildCommandOptions); + const isWatchCommandUsed = isCommand(commandName, watchCommandOptions); + + if (isBuildCommandUsed || isWatchCommandUsed) { + await this.makeCommand( + isBuildCommandUsed ? buildCommandOptions : watchCommandOptions, + async () => { + this.webpack = await this.loadWebpack(); + + return isWatchCommandUsed + ? this.getBuiltInOptions().filter((option) => option.name !== "watch") + : this.getBuiltInOptions(); + }, + async (entries, options) => { + if (entries.length > 0) { + options.entry = [...entries, ...(options.entry || [])]; + } + + await this.runWebpack(options, isWatchCommandUsed); + }, + ); + } else if (isCommand(commandName, helpCommandOptions)) { + // Stub for the `help` command + this.makeCommand(helpCommandOptions, [], () => {}); + } else if (isCommand(commandName, versionCommandOptions)) { + // Stub for the `version` command + this.makeCommand(versionCommandOptions, [], () => {}); + } else { + const builtInExternalCommandInfo = externalBuiltInCommandsInfo.find( + (externalBuiltInCommandInfo) => + getCommandName(externalBuiltInCommandInfo.name) === commandName || + (Array.isArray(externalBuiltInCommandInfo.alias) + ? externalBuiltInCommandInfo.alias.includes(commandName) + : externalBuiltInCommandInfo.alias === commandName), + ); + + let pkg; + + if (builtInExternalCommandInfo) { + ({ pkg } = builtInExternalCommandInfo); + } else { + pkg = commandName; + } + + if (pkg !== "webpack-cli" && !this.checkPackageExists(pkg)) { + if (!allowToInstall) { + return; + } + + pkg = await this.doInstall(pkg, { + preMessage: () => { + this.logger.error( + `For using this command you need to install: '${this.colors.green(pkg)}' package.`, + ); + }, + }); + } + + let loadedCommand; + + try { + loadedCommand = await this.tryRequireThenImport(pkg, false); + } catch (error) { + // Ignore, command is not installed + + return; + } + + let command; + + try { + command = new loadedCommand(); + + await command.apply(this); + } catch (error) { + this.logger.error(`Unable to load '${pkg}' command`); + this.logger.error(error); + process.exit(2); + } + } + }; + + // Register own exit + this.program.exitOverride(async (error) => { + if (error.exitCode === 0) { + process.exit(0); + } + + if (error.code === "executeSubCommandAsync") { + process.exit(2); + } + + if (error.code === "commander.help") { + process.exit(0); + } + + if (error.code === "commander.unknownOption") { + let name = error.message.match(/'(.+)'/); + + if (name) { + name = name[1].substr(2); + + if (name.includes("=")) { + name = name.split("=")[0]; + } + + const { operands } = this.program.parseOptions(this.program.args); + const operand = + typeof operands[0] !== "undefined" + ? operands[0] + : getCommandName(buildCommandOptions.name); + + if (operand) { + const command = findCommandByName(operand); + + if (!command) { + this.logger.error(`Can't find and load command '${operand}'`); + this.logger.error("Run 'webpack --help' to see available commands and options"); + process.exit(2); + } + + const levenshtein = require("fastest-levenshtein"); + + command.options.forEach((option) => { + if (!option.hidden && levenshtein.distance(name, option.long.slice(2)) < 3) { + this.logger.error(`Did you mean '--${option.name()}'?`); + } + }); + } + } + } + + // Codes: + // - commander.unknownCommand + // - commander.missingArgument + // - commander.missingMandatoryOptionValue + // - commander.optionMissingArgument + + this.logger.error("Run 'webpack --help' to see available commands and options"); + process.exit(2); + }); + + // Default `--color` and `--no-color` options + const cli = this; + this.program.option("--color", "Enable colors on console."); + this.program.on("option:color", function () { + const { color } = this.opts(); + + cli.isColorSupportChanged = color; + cli.colors = cli.createColors(color); + }); + this.program.option("--no-color", "Disable colors on console."); + this.program.on("option:no-color", function () { + const { color } = this.opts(); + + cli.isColorSupportChanged = color; + cli.colors = cli.createColors(color); + }); + + // Make `-v, --version` options + // Make `version|v [commands...]` command + const outputVersion = async (options) => { + // Filter `bundle`, `watch`, `version` and `help` commands + const possibleCommandNames = options.filter( + (option) => + !isCommand(option, buildCommandOptions) && + !isCommand(option, watchCommandOptions) && + !isCommand(option, versionCommandOptions) && + !isCommand(option, helpCommandOptions), + ); + + possibleCommandNames.forEach((possibleCommandName) => { + if (!isOption(possibleCommandName)) { + return; + } + + this.logger.error(`Unknown option '${possibleCommandName}'`); + this.logger.error("Run 'webpack --help' to see available commands and options"); + process.exit(2); + }); + + if (possibleCommandNames.length > 0) { + await Promise.all( + possibleCommandNames.map((possibleCommand) => loadCommandByName(possibleCommand)), + ); + + for (const possibleCommandName of possibleCommandNames) { + const foundCommand = findCommandByName(possibleCommandName); + + if (!foundCommand) { + this.logger.error(`Unknown command '${possibleCommandName}'`); + this.logger.error("Run 'webpack --help' to see available commands and options"); + process.exit(2); + } + + try { + const { name, version } = this.loadJSONFile(`${foundCommand.pkg}/package.json`); + + this.logger.raw(`${name} ${version}`); + } catch (e) { + this.logger.error(`Error: External package '${foundCommand.pkg}' not found`); + process.exit(2); + } + } + } + + let webpack; + + try { + webpack = await this.loadWebpack(false); + } catch (_error) { + // Nothing + } + + this.logger.raw(`webpack: ${webpack ? webpack.version : "not installed"}`); + + const pkgJSON = this.loadJSONFile("../package.json"); + + this.logger.raw(`webpack-cli: ${pkgJSON.version}`); + + let devServer; + + try { + devServer = await this.loadJSONFile("webpack-dev-server/package.json", false); + } catch (_error) { + // Nothing + } + + this.logger.raw(`webpack-dev-server ${devServer ? devServer.version : "not installed"}`); + + process.exit(0); + }; + this.program.option( + "-v, --version", + "Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and commands.", + ); + + const outputHelp = async (options, isVerbose, isHelpCommandSyntax, program) => { + const { bold } = this.colors; + const outputIncorrectUsageOfHelp = () => { + this.logger.error("Incorrect use of help"); + this.logger.error( + "Please use: 'webpack help [command] [option]' | 'webpack [command] --help'", + ); + this.logger.error("Run 'webpack --help' to see available commands and options"); + process.exit(2); + }; + + const isGlobalHelp = options.length === 0; + const isCommandHelp = options.length === 1 && !isOption(options[0]); + + if (isGlobalHelp || isCommandHelp) { + program.configureHelp({ + sortSubcommands: true, + // Support multiple aliases + commandUsage: (command) => { + let parentCmdNames = ""; + + for (let parentCmd = command.parent; parentCmd; parentCmd = parentCmd.parent) { + parentCmdNames = `${parentCmd.name()} ${parentCmdNames}`; + } + + if (isGlobalHelp) { + return `${parentCmdNames}${command.usage()}\n${bold( + "Alternative usage to run commands:", + )} ${parentCmdNames}[command] [options]`; + } + + return `${parentCmdNames}${command.name()}|${command + .aliases() + .join("|")} ${command.usage()}`; + }, + // Support multiple aliases + subcommandTerm: (command) => { + const humanReadableArgumentName = (argument) => { + const nameOutput = argument.name + (argument.variadic === true ? "..." : ""); + + return argument.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]"; + }; + const args = command._args.map((arg) => humanReadableArgumentName(arg)).join(" "); + + return `${command.name()}|${command.aliases().join("|")}${args ? ` ${args}` : ""}${ + command.options.length > 0 ? " [options]" : "" + }`; + }, + visibleOptions: function visibleOptions(command) { + return command.options.filter((option) => { + if (option.hidden) { + return false; + } + + switch (option.helpLevel) { + case "verbose": + return isVerbose; + case "minimum": + default: + return true; + } + }); + }, + padWidth(command, helper) { + return Math.max( + helper.longestArgumentTermLength(command, helper), + helper.longestOptionTermLength(command, helper), + // For global options + helper.longestOptionTermLength(program, helper), + helper.longestSubcommandTermLength(isGlobalHelp ? program : command, helper), + ); + }, + formatHelp: (command, helper) => { + const termWidth = helper.padWidth(command, helper); + const helpWidth = helper.helpWidth || process.env.WEBPACK_CLI_HELP_WIDTH || 80; + const itemIndentWidth = 2; + const itemSeparatorWidth = 2; // between term and description + + const formatItem = (term, description) => { + if (description) { + const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`; + + return helper.wrap( + fullText, + helpWidth - itemIndentWidth, + termWidth + itemSeparatorWidth, + ); + } + + return term; + }; + + const formatList = (textArray) => + textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth)); + + // Usage + let output = [`${bold("Usage:")} ${helper.commandUsage(command)}`, ""]; + + // Description + const commandDescription = isGlobalHelp + ? "The build tool for modern web applications." + : helper.commandDescription(command); + + if (commandDescription.length > 0) { + output = output.concat([commandDescription, ""]); + } + + // Arguments + const argumentList = helper + .visibleArguments(command) + .map((argument) => formatItem(argument.term, argument.description)); + + if (argumentList.length > 0) { + output = output.concat([bold("Arguments:"), formatList(argumentList), ""]); + } + + // Options + const optionList = helper + .visibleOptions(command) + .map((option) => + formatItem(helper.optionTerm(option), helper.optionDescription(option)), + ); + + if (optionList.length > 0) { + output = output.concat([bold("Options:"), formatList(optionList), ""]); + } + + // Global options + const globalOptionList = program.options.map((option) => + formatItem(helper.optionTerm(option), helper.optionDescription(option)), + ); + + if (globalOptionList.length > 0) { + output = output.concat([bold("Global options:"), formatList(globalOptionList), ""]); + } + + // Commands + const commandList = helper + .visibleCommands(isGlobalHelp ? program : command) + .map((command) => + formatItem(helper.subcommandTerm(command), helper.subcommandDescription(command)), + ); + + if (commandList.length > 0) { + output = output.concat([bold("Commands:"), formatList(commandList), ""]); + } + + return output.join("\n"); + }, + }); + + if (isGlobalHelp) { + await Promise.all( + knownCommands.map((knownCommand) => { + return loadCommandByName(getCommandName(knownCommand.name)); + }), + ); + + const buildCommand = findCommandByName(getCommandName(buildCommandOptions.name)); + + this.logger.raw(buildCommand.helpInformation()); + } else { + const name = options[0]; + + await loadCommandByName(name); + + const command = findCommandByName(name); + + if (!command) { + const builtInCommandUsed = externalBuiltInCommandsInfo.find( + (command) => command.name.includes(name) || name === command.alias, + ); + if (typeof builtInCommandUsed !== "undefined") { + this.logger.error( + `For using '${name}' command you need to install '${builtInCommandUsed.pkg}' package.`, + ); + } else { + this.logger.error(`Can't find and load command '${name}'`); + this.logger.error("Run 'webpack --help' to see available commands and options."); + } + process.exit(2); + } + + this.logger.raw(command.helpInformation()); + } + } else if (isHelpCommandSyntax) { + let isCommandSpecified = false; + let commandName = getCommandName(buildCommandOptions.name); + let optionName; + + if (options.length === 1) { + optionName = options[0]; + } else if (options.length === 2) { + isCommandSpecified = true; + commandName = options[0]; + optionName = options[1]; + + if (isOption(commandName)) { + outputIncorrectUsageOfHelp(); + } + } else { + outputIncorrectUsageOfHelp(); + } + + await loadCommandByName(commandName); + + const command = isGlobalOption(optionName) ? program : findCommandByName(commandName); + + if (!command) { + this.logger.error(`Can't find and load command '${commandName}'`); + this.logger.error("Run 'webpack --help' to see available commands and options"); + process.exit(2); + } + + const option = command.options.find( + (option) => option.short === optionName || option.long === optionName, + ); + + if (!option) { + this.logger.error(`Unknown option '${optionName}'`); + this.logger.error("Run 'webpack --help' to see available commands and options"); + process.exit(2); + } + + const nameOutput = + option.flags.replace(/^.+[[<]/, "").replace(/(\.\.\.)?[\]>].*$/, "") + + (option.variadic === true ? "..." : ""); + const value = option.required + ? "<" + nameOutput + ">" + : option.optional + ? "[" + nameOutput + "]" + : ""; + + this.logger.raw( + `${bold("Usage")}: webpack${isCommandSpecified ? ` ${commandName}` : ""} ${option.long}${ + value ? ` ${value}` : "" + }`, + ); + + if (option.short) { + this.logger.raw( + `${bold("Short:")} webpack${isCommandSpecified ? ` ${commandName}` : ""} ${ + option.short + }${value ? ` ${value}` : ""}`, + ); + } + + if (option.description) { + this.logger.raw(`${bold("Description:")} ${option.description}`); + } + + if (!option.negate && option.defaultValue) { + this.logger.raw(`${bold("Default value:")} ${JSON.stringify(option.defaultValue)}`); + } + + const flag = this.getBuiltInOptions().find((flag) => option.long === `--${flag.name}`); + + if (flag && flag.configs) { + const possibleValues = flag.configs.reduce((accumulator, currentValue) => { + if (currentValue.values) { + return accumulator.concat(currentValue.values); + } else { + return accumulator; + } + }, []); + + if (possibleValues.length > 0) { + this.logger.raw( + `${bold("Possible values:")} ${JSON.stringify(possibleValues.join(" | "))}`, + ); + } + } + + this.logger.raw(""); + + // TODO implement this after refactor cli arguments + // logger.raw('Documentation: https://webpack.js.org/option/name/'); + } else { + outputIncorrectUsageOfHelp(); + } + + this.logger.raw( + "To see list of all supported commands and options run 'webpack --help=verbose'.\n", + ); + this.logger.raw(`${bold("Webpack documentation:")} https://webpack.js.org/.`); + this.logger.raw(`${bold("CLI documentation:")} https://webpack.js.org/api/cli/.`); + this.logger.raw(`${bold("Made with ♥ by the webpack team")}.`); + process.exit(0); + }; + this.program.helpOption(false); + this.program.addHelpCommand(false); + this.program.option("-h, --help [verbose]", "Display help for commands and options."); + + let isInternalActionCalled = false; + + // Default action + this.program.usage("[options]"); + this.program.allowUnknownOption(true); + this.program.action(async (options, program) => { + if (!isInternalActionCalled) { + isInternalActionCalled = true; + } else { + this.logger.error("No commands found to run"); + process.exit(2); + } + + // Command and options + const { operands, unknown } = this.program.parseOptions(program.args); + const defaultCommandToRun = getCommandName(buildCommandOptions.name); + const hasOperand = typeof operands[0] !== "undefined"; + const operand = hasOperand ? operands[0] : defaultCommandToRun; + const isHelpOption = typeof options.help !== "undefined"; + const isHelpCommandSyntax = isCommand(operand, helpCommandOptions); + + if (isHelpOption || isHelpCommandSyntax) { + let isVerbose = false; + + if (isHelpOption) { + if (typeof options.help === "string") { + if (options.help !== "verbose") { + this.logger.error("Unknown value for '--help' option, please use '--help=verbose'"); + process.exit(2); + } + + isVerbose = true; + } + } + + this.program.forHelp = true; + + const optionsForHelp = [] + .concat(isHelpOption && hasOperand ? [operand] : []) + // Syntax `webpack help [command]` + .concat(operands.slice(1)) + // Syntax `webpack help [option]` + .concat(unknown) + .concat( + isHelpCommandSyntax && typeof options.color !== "undefined" + ? [options.color ? "--color" : "--no-color"] + : [], + ) + .concat( + isHelpCommandSyntax && typeof options.version !== "undefined" ? ["--version"] : [], + ); + + await outputHelp(optionsForHelp, isVerbose, isHelpCommandSyntax, program); + } + + const isVersionOption = typeof options.version !== "undefined"; + const isVersionCommandSyntax = isCommand(operand, versionCommandOptions); + + if (isVersionOption || isVersionCommandSyntax) { + const optionsForVersion = [] + .concat(isVersionOption ? [operand] : []) + .concat(operands.slice(1)) + .concat(unknown); + + await outputVersion(optionsForVersion, program); + } + + let commandToRun = operand; + let commandOperands = operands.slice(1); + + if (isKnownCommand(commandToRun)) { + await loadCommandByName(commandToRun, true); + } else { + const isEntrySyntax = fs.existsSync(operand); + + if (isEntrySyntax) { + commandToRun = defaultCommandToRun; + commandOperands = operands; + + await loadCommandByName(commandToRun); + } else { + this.logger.error(`Unknown command or entry '${operand}'`); + + const levenshtein = require("fastest-levenshtein"); + const found = knownCommands.find( + (commandOptions) => + levenshtein.distance(operand, getCommandName(commandOptions.name)) < 3, + ); + + if (found) { + this.logger.error( + `Did you mean '${getCommandName(found.name)}' (alias '${ + Array.isArray(found.alias) ? found.alias.join(", ") : found.alias + }')?`, + ); + } + + this.logger.error("Run 'webpack --help' to see available commands and options"); + process.exit(2); + } + } + + await this.program.parseAsync([commandToRun, ...commandOperands, ...unknown], { + from: "user", + }); + }); + + await this.program.parseAsync(args, parseOptions); + } + + async loadConfig(options) { + const interpret = require("interpret"); + const loadConfigByPath = async (configPath, argv = {}) => { + const ext = path.extname(configPath); + const interpreted = Object.keys(interpret.jsVariants).find((variant) => variant === ext); + + if (interpreted) { + const rechoir = require("rechoir"); + + try { + rechoir.prepare(interpret.extensions, configPath); + } catch (error) { + if (error.failures) { + this.logger.error(`Unable load '${configPath}'`); + this.logger.error(error.message); + error.failures.forEach((failure) => { + this.logger.error(failure.error.message); + }); + this.logger.error("Please install one of them"); + process.exit(2); + } + + this.logger.error(error); + process.exit(2); + } + } + + let options; + + try { + options = await this.tryRequireThenImport(configPath, false); + } catch (error) { + this.logger.error(`Failed to load '${configPath}' config`); + + if (this.isValidationError(error)) { + this.logger.error(error.message); + } else { + this.logger.error(error); + } + + process.exit(2); + } + + if (Array.isArray(options)) { + await Promise.all( + options.map(async (_, i) => { + if (typeof options[i].then === "function") { + options[i] = await options[i]; + } + + // `Promise` may return `Function` + if (typeof options[i] === "function") { + // when config is a function, pass the env from args to the config function + options[i] = await options[i](argv.env, argv); + } + }), + ); + } else { + if (typeof options.then === "function") { + options = await options; + } + + // `Promise` may return `Function` + if (typeof options === "function") { + // when config is a function, pass the env from args to the config function + options = await options(argv.env, argv); + } + } + + const isObject = (value) => typeof value === "object" && value !== null; + + if (!isObject(options) && !Array.isArray(options)) { + this.logger.error(`Invalid configuration in '${configPath}'`); + + process.exit(2); + } + + return { options, path: configPath }; + }; + + const config = { options: {}, path: new WeakMap() }; + + if (options.config && options.config.length > 0) { + const loadedConfigs = await Promise.all( + options.config.map((configPath) => + loadConfigByPath(path.resolve(configPath), options.argv), + ), + ); + + config.options = []; + + loadedConfigs.forEach((loadedConfig) => { + const isArray = Array.isArray(loadedConfig.options); + + // TODO we should run webpack multiple times when the `--config` options have multiple values with `--merge`, need to solve for the next major release + if (config.options.length === 0) { + config.options = loadedConfig.options; + } else { + if (!Array.isArray(config.options)) { + config.options = [config.options]; + } + + if (isArray) { + loadedConfig.options.forEach((item) => { + config.options.push(item); + }); + } else { + config.options.push(loadedConfig.options); + } + } + + if (isArray) { + loadedConfig.options.forEach((options) => { + config.path.set(options, loadedConfig.path); + }); + } else { + config.path.set(loadedConfig.options, loadedConfig.path); + } + }); + + config.options = config.options.length === 1 ? config.options[0] : config.options; + } else { + // Order defines the priority, in decreasing order + const defaultConfigFiles = [ + "webpack.config", + ".webpack/webpack.config", + ".webpack/webpackfile", + ] + .map((filename) => + // Since .cjs is not available on interpret side add it manually to default config extension list + [...Object.keys(interpret.extensions), ".cjs"].map((ext) => ({ + path: path.resolve(filename + ext), + ext: ext, + module: interpret.extensions[ext], + })), + ) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); + + let foundDefaultConfigFile; + + for (const defaultConfigFile of defaultConfigFiles) { + if (!fs.existsSync(defaultConfigFile.path)) { + continue; + } + + foundDefaultConfigFile = defaultConfigFile; + break; + } + + if (foundDefaultConfigFile) { + const loadedConfig = await loadConfigByPath(foundDefaultConfigFile.path, options.argv); + + config.options = loadedConfig.options; + + if (Array.isArray(config.options)) { + config.options.forEach((item) => { + config.path.set(item, loadedConfig.path); + }); + } else { + config.path.set(loadedConfig.options, loadedConfig.path); + } + } + } + + if (options.configName) { + const notFoundConfigNames = []; + + config.options = options.configName.map((configName) => { + let found; + + if (Array.isArray(config.options)) { + found = config.options.find((options) => options.name === configName); + } else { + found = config.options.name === configName ? config.options : undefined; + } + + if (!found) { + notFoundConfigNames.push(configName); + } + + return found; + }); + + if (notFoundConfigNames.length > 0) { + this.logger.error( + notFoundConfigNames + .map((configName) => `Configuration with the name "${configName}" was not found.`) + .join(" "), + ); + process.exit(2); + } + } + + if (options.merge) { + const merge = await this.tryRequireThenImport("webpack-merge"); + + // we can only merge when there are multiple configurations + // either by passing multiple configs by flags or passing a + // single config exporting an array + if (!Array.isArray(config.options) || config.options.length <= 1) { + this.logger.error("At least two configurations are required for merge."); + process.exit(2); + } + + const mergedConfigPaths = []; + + config.options = config.options.reduce((accumulator, options) => { + const configPath = config.path.get(options); + const mergedOptions = merge(accumulator, options); + + mergedConfigPaths.push(configPath); + + return mergedOptions; + }, {}); + config.path.set(config.options, mergedConfigPaths); + } + + return config; + } + + async buildConfig(config, options) { + const runFunctionOnEachConfig = (options, fn) => { + if (Array.isArray(options)) { + for (let item of options) { + item = fn(item); + } + } else { + options = fn(options); + } + + return options; + }; + + if (options.analyze) { + if (!this.checkPackageExists("webpack-bundle-analyzer")) { + await this.doInstall("webpack-bundle-analyzer", { + preMessage: () => { + this.logger.error( + `It looks like ${this.colors.yellow("webpack-bundle-analyzer")} is not installed.`, + ); + }, + }); + + this.logger.success( + `${this.colors.yellow("webpack-bundle-analyzer")} was installed successfully.`, + ); + } + } + + if (typeof options.progress === "string" && options.progress !== "profile") { + this.logger.error( + `'${options.progress}' is an invalid value for the --progress option. Only 'profile' is allowed.`, + ); + process.exit(2); + } + + if (typeof options.hot === "string" && options.hot !== "only") { + this.logger.error( + `'${options.hot}' is an invalid value for the --hot option. Use 'only' instead.`, + ); + process.exit(2); + } + + const CLIPlugin = await this.tryRequireThenImport("./plugins/CLIPlugin"); + + const internalBuildConfig = (item) => { + // Output warnings + if ( + item.watch && + options.argv && + options.argv.env && + (options.argv.env["WEBPACK_WATCH"] || options.argv.env["WEBPACK_SERVE"]) + ) { + this.logger.warn( + `No need to use the '${ + options.argv.env["WEBPACK_WATCH"] ? "watch" : "serve" + }' command together with '{ watch: true }' configuration, it does not make sense.`, + ); + + if (options.argv.env["WEBPACK_SERVE"]) { + item.watch = false; + } + } + + // Apply options + if (this.webpack.cli) { + const args = this.getBuiltInOptions() + .filter((flag) => flag.group === "core") + .reduce((accumulator, flag) => { + accumulator[flag.name] = flag; + + return accumulator; + }, {}); + + const values = Object.keys(options).reduce((accumulator, name) => { + if (name === "argv") { + return accumulator; + } + + const kebabName = this.toKebabCase(name); + + if (args[kebabName]) { + accumulator[kebabName] = options[name]; + } + + return accumulator; + }, {}); + + const problems = this.webpack.cli.processArguments(args, item, values); + + if (problems) { + const groupBy = (xs, key) => { + return xs.reduce((rv, x) => { + (rv[x[key]] = rv[x[key]] || []).push(x); + + return rv; + }, {}); + }; + const problemsByPath = groupBy(problems, "path"); + + for (const path in problemsByPath) { + const problems = problemsByPath[path]; + + problems.forEach((problem) => { + this.logger.error( + `${this.capitalizeFirstLetter(problem.type.replace(/-/g, " "))}${ + problem.value ? ` '${problem.value}'` : "" + } for the '--${problem.argument}' option${ + problem.index ? ` by index '${problem.index}'` : "" + }`, + ); + + if (problem.expected) { + this.logger.error(`Expected: '${problem.expected}'`); + } + }); + } + + process.exit(2); + } + + // Setup default cache options + if (item.cache && item.cache.type === "filesystem") { + const configPath = config.path.get(item); + + if (configPath) { + if (!item.cache.buildDependencies) { + item.cache.buildDependencies = {}; + } + + if (!item.cache.buildDependencies.defaultConfig) { + item.cache.buildDependencies.defaultConfig = []; + } + + if (Array.isArray(configPath)) { + configPath.forEach((oneOfConfigPath) => { + item.cache.buildDependencies.defaultConfig.push(oneOfConfigPath); + }); + } else { + item.cache.buildDependencies.defaultConfig.push(configPath); + } + } + } + } + + // Setup legacy logic for webpack@4 + // TODO respect `--entry-reset` in th next major release + // TODO drop in the next major release + if (options.entry) { + item.entry = options.entry; + } + + if (options.outputPath) { + item.output = { ...item.output, ...{ path: path.resolve(options.outputPath) } }; + } + + if (options.target) { + item.target = options.target; + } + + if (typeof options.devtool !== "undefined") { + item.devtool = options.devtool; + } + + if (options.name) { + item.name = options.name; + } + + if (typeof options.stats !== "undefined") { + item.stats = options.stats; + } + + if (typeof options.watch !== "undefined") { + item.watch = options.watch; + } + + if (typeof options.watchOptionsStdin !== "undefined") { + item.watchOptions = { ...item.watchOptions, ...{ stdin: options.watchOptionsStdin } }; + } + + if (options.mode) { + item.mode = options.mode; + } + + // Respect `process.env.NODE_ENV` + if ( + !item.mode && + process.env && + process.env.NODE_ENV && + (process.env.NODE_ENV === "development" || + process.env.NODE_ENV === "production" || + process.env.NODE_ENV === "none") + ) { + item.mode = process.env.NODE_ENV; + } + + // Setup stats + // TODO remove after drop webpack@4 + const statsForWebpack4 = this.webpack.Stats && this.webpack.Stats.presetToOptions; + + if (statsForWebpack4) { + if (typeof item.stats === "undefined") { + item.stats = {}; + } else if (typeof item.stats === "boolean") { + item.stats = this.webpack.Stats.presetToOptions(item.stats); + } else if ( + typeof item.stats === "string" && + (item.stats === "none" || + item.stats === "verbose" || + item.stats === "detailed" || + item.stats === "normal" || + item.stats === "minimal" || + item.stats === "errors-only" || + item.stats === "errors-warnings") + ) { + item.stats = this.webpack.Stats.presetToOptions(item.stats); + } + } else { + if (typeof item.stats === "undefined") { + item.stats = { preset: "normal" }; + } else if (typeof item.stats === "boolean") { + item.stats = item.stats ? { preset: "normal" } : { preset: "none" }; + } else if (typeof item.stats === "string") { + item.stats = { preset: item.stats }; + } + } + + let colors; + + // From arguments + if (typeof this.isColorSupportChanged !== "undefined") { + colors = Boolean(this.isColorSupportChanged); + } + // From stats + else if (typeof item.stats.colors !== "undefined") { + colors = item.stats.colors; + } + // Default + else { + colors = Boolean(this.colors.isColorSupported); + } + + // TODO remove after drop webpack v4 + if (typeof item.stats === "object" && item.stats !== null) { + item.stats.colors = colors; + } + + // Apply CLI plugin + if (!item.plugins) { + item.plugins = []; + } + + item.plugins.unshift( + new CLIPlugin({ + configPath: config.path.get(item), + helpfulOutput: !options.json, + hot: options.hot, + progress: options.progress, + prefetch: options.prefetch, + analyze: options.analyze, + }), + ); + + return options; + }; + + runFunctionOnEachConfig(config.options, internalBuildConfig); + + return config; + } + + isValidationError(error) { + // https://github.com/webpack/webpack/blob/master/lib/index.js#L267 + // https://github.com/webpack/webpack/blob/v4.44.2/lib/webpack.js#L90 + const ValidationError = + this.webpack.ValidationError || this.webpack.WebpackOptionsValidationError; + + return error instanceof ValidationError || error.name === "ValidationError"; + } + + async createCompiler(options, callback) { + if (typeof options.nodeEnv === "string") { + process.env.NODE_ENV = options.nodeEnv; + } + + let config = await this.loadConfig(options); + config = await this.buildConfig(config, options); + + let compiler; + + try { + compiler = this.webpack( + config.options, + callback + ? (error, stats) => { + if (error && this.isValidationError(error)) { + this.logger.error(error.message); + process.exit(2); + } + + callback(error, stats); + } + : callback, + ); + } catch (error) { + if (this.isValidationError(error)) { + this.logger.error(error.message); + } else { + this.logger.error(error); + } + + process.exit(2); + } + + // TODO webpack@4 return Watching and MultiWatching instead Compiler and MultiCompiler, remove this after drop webpack@4 + if (compiler && compiler.compiler) { + compiler = compiler.compiler; + } + + return compiler; + } + + needWatchStdin(compiler) { + if (compiler.compilers) { + return compiler.compilers.some( + (compiler) => compiler.options.watchOptions && compiler.options.watchOptions.stdin, + ); + } + + return compiler.options.watchOptions && compiler.options.watchOptions.stdin; + } + + async runWebpack(options, isWatchCommand) { + // eslint-disable-next-line prefer-const + let compiler; + let createJsonStringifyStream; + + if (options.json) { + const jsonExt = await this.tryRequireThenImport("@discoveryjs/json-ext"); + + createJsonStringifyStream = jsonExt.stringifyStream; + } + + const callback = (error, stats) => { + if (error) { + this.logger.error(error); + process.exit(2); + } + + if (stats.hasErrors()) { + process.exitCode = 1; + } + + if (!compiler) { + return; + } + + const statsOptions = compiler.compilers + ? { + children: compiler.compilers.map((compiler) => + compiler.options ? compiler.options.stats : undefined, + ), + } + : compiler.options + ? compiler.options.stats + : undefined; + + // TODO webpack@4 doesn't support `{ children: [{ colors: true }, { colors: true }] }` for stats + const statsForWebpack4 = this.webpack.Stats && this.webpack.Stats.presetToOptions; + + if (compiler.compilers && statsForWebpack4) { + statsOptions.colors = statsOptions.children.some((child) => child.colors); + } + + if (options.json && createJsonStringifyStream) { + const handleWriteError = (error) => { + this.logger.error(error); + process.exit(2); + }; + + if (options.json === true) { + createJsonStringifyStream(stats.toJson(statsOptions)) + .on("error", handleWriteError) + .pipe(process.stdout) + .on("error", handleWriteError) + .on("close", () => process.stdout.write("\n")); + } else { + createJsonStringifyStream(stats.toJson(statsOptions)) + .on("error", handleWriteError) + .pipe(fs.createWriteStream(options.json)) + .on("error", handleWriteError) + // Use stderr to logging + .on("close", () => { + process.stderr.write( + `[webpack-cli] ${this.colors.green( + `stats are successfully stored as json to ${options.json}`, + )}\n`, + ); + }); + } + } else { + const printedStats = stats.toString(statsOptions); + + // Avoid extra empty line when `stats: 'none'` + if (printedStats) { + this.logger.raw(printedStats); + } + } + }; + + const env = + isWatchCommand || options.watch + ? { WEBPACK_WATCH: true, ...options.env } + : { WEBPACK_BUNDLE: true, WEBPACK_BUILD: true, ...options.env }; + + options.argv = { ...options, env }; + + if (isWatchCommand) { + options.watch = true; + } + + compiler = await this.createCompiler(options, callback); + + if (!compiler) { + return; + } + + const isWatch = (compiler) => + compiler.compilers + ? compiler.compilers.some((compiler) => compiler.options.watch) + : compiler.options.watch; + + if (isWatch(compiler) && this.needWatchStdin(compiler)) { + process.stdin.on("end", () => { + process.exit(0); + }); + process.stdin.resume(); + } + } +} + +module.exports = WebpackCLI; diff --git a/node_modules/mathjs/examples/node_modules/webpack-cli/node_modules/commander/CHANGELOG.md b/node_modules/mathjs/examples/node_modules/webpack-cli/node_modules/commander/CHANGELOG.md new file mode 100644 index 0000000..0b55881 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/webpack-cli/node_modules/commander/CHANGELOG.md @@ -0,0 +1,440 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). (Format adopted after v3.0.0.) + + + + +## [7.2.0] (2021-03-26) + +### Added + +- TypeScript typing for `parent` property on `Command` ([#1475]) +- TypeScript typing for `.attributeName()` on `Option` ([#1483]) +- support information in package ([#1477]) + +### Changed + +- improvements to error messages, README, and tests +- update dependencies + +## [7.1.0] (2021-02-15) + +### Added + +- support for named imports from ECMAScript modules ([#1440]) +- add `.cjs` to list of expected script file extensions ([#1449]) +- allow using option choices and variadic together ([#1454]) + +### Fixed + +- replace use of deprecated `process.mainModule` ([#1448]) +- regression for legacy `command('*')` and call when command line includes options ([#1464]) +- regression for `on('command:*', ...)` and call when command line includes unknown options ([#1464]) +- display best error for combination of unknown command and unknown option (i.e. unknown command) ([#1464]) + +### Changed + +- make TypeScript typings tests stricter ([#1453]) +- improvements to README and tests + +## [7.0.0] (2021-01-15) + +### Added + +- `.enablePositionalOptions()` to let program and subcommand reuse same option ([#1427]) +- `.passThroughOptions()` to pass options through to other programs without needing `--` ([#1427]) +- `.allowExcessArguments(false)` to show an error message if there are too many command-arguments on command line for the action handler ([#1409]) +- `.configureOutput()` to modify use of stdout and stderr or customise display of errors ([#1387]) +- use `.addHelpText()` to add text before or after the built-in help, for just current command or also for all subcommands ([#1296]) +- enhance Option class ([#1331]) + - allow hiding options from help + - allow restricting option arguments to a list of choices + - allow setting how default value is shown in help +- `.createOption()` to support subclassing of automatically created options (like `.createCommand()`) ([#1380]) +- refactor the code generating the help into a separate public Help class ([#1365]) + - support sorting subcommands and options in help + - support specifying wrap width (columns) + - allow subclassing Help class + - allow configuring Help class without subclassing + +### Changed + +- *Breaking:* options are stored safely by default, not as properties on the command ([#1409]) + - this especially affects accessing options on program, use `program.opts()` + - revert behaviour with `.storeOptionsAsProperties()` +- *Breaking:* action handlers are passed options and command separately ([#1409]) +- deprecated callback parameter to `.help()` and `.outputHelp()` (removed from README) ([#1296]) +- *Breaking:* errors now displayed using `process.stderr.write()` instead of `console.error()` +- deprecate `.on('--help')` (removed from README) ([#1296]) +- initialise the command description to empty string (previously undefined) ([#1365]) +- document and annotate deprecated routines ([#1349]) + +### Fixed + +- wrapping bugs in help ([#1365]) + - first line of command description was wrapping two characters early + - pad width calculation was not including help option and help command + - pad width calculation was including hidden options and commands +- improve backwards compatibility for custom command event listeners ([#1403]) + +### Deleted + +- *Breaking:* `.passCommandToAction()` ([#1409]) + - no longer needed as action handler is passed options and command +- *Breaking:* "extra arguments" parameter to action handler ([#1409]) + - if being used to detect excess arguments, there is now an error available by setting `.allowExcessArguments(false)` + +### Migration Tips + +The biggest change is the parsed option values. Previously the options were stored by default as properties on the command object, and now the options are stored separately. + +If you wish to restore the old behaviour and get running quickly you can call `.storeOptionsAsProperties()`. +To allow you to move to the new code patterns incrementally, the action handler will be passed the command _twice_, +to match the new "options" and "command" parameters (see below). + +**program options** + +Use the `.opts()` method to access the options. This is available on any command but is used most with the program. + +```js +program.option('-d, --debug'); +program.parse(); +// Old code before Commander 7 +if (program.debug) console.log(`Program name is ${program.name()}`); +``` + +```js +// New code +const options = program.opts(); +if (options.debug) console.log(`Program name is ${program.name()}`); +``` + +**action handler** + +The action handler gets passed a parameter for each command-argument you declared. Previously by default the next parameter was the command object with the options as properties. Now the next two parameters are instead the options and the command. If you +only accessed the options there may be no code changes required. + +```js +program + .command('compress ') + .option('-t, --trace') + // Old code before Commander 7 + .action((filename, cmd)) => { + if (cmd.trace) console.log(`Command name is ${cmd.name()}`); + }); +``` + +```js + // New code + .action((filename, options, command)) => { + if (options.trace) console.log(`Command name is ${command.name()}`); + }); +``` + +If you already set `.storeOptionsAsProperties(false)` you may still need to adjust your code. + +```js +program + .command('compress ') + .storeOptionsAsProperties(false) + .option('-t, --trace') + // Old code before Commander 7 + .action((filename, command)) => { + if (command.opts().trace) console.log(`Command name is ${command.name()}`); + }); +``` + +```js + // New code + .action((filename, options, command)) => { + if (command.opts().trace) console.log(`Command name is ${command.name()}`); + }); +``` + +## [7.0.0-2] (2020-12-14) + +(Released in 7.0.0) + +## [7.0.0-1] (2020-11-21) + +(Released in 7.0.0) + +## [7.0.0-0] (2020-10-25) + +(Released in 7.0.0) + +## [6.2.1] (2020-12-13) + +### Fixed + +- some tests failed if directory path included a space ([1390]) + +## [6.2.0] (2020-10-25) + +### Added + +- added 'tsx' file extension for stand-alone executable subcommands ([#1368]) +- documented second parameter to `.description()` to describe command arguments ([#1353]) +- documentation of special cases with options taking varying numbers of option-arguments ([#1332]) +- documentation for terminology ([#1361]) + +### Fixed + +- add missing TypeScript definition for `.addHelpCommand()' ([#1375]) +- removed blank line after "Arguments:" in help, to match "Options:" and "Commands:" ([#1360]) + +### Changed + +- update dependencies + +## [6.1.0] (2020-08-28) + +### Added + +- include URL to relevant section of README for error for potential conflict between Command properties and option values ([#1306]) +- `.combineFlagAndOptionalValue(false)` to ease upgrade path from older versions of Commander ([#1326]) +- allow disabling the built-in help option using `.helpOption(false)` ([#1325]) +- allow just some arguments in `argumentDescription` to `.description()` ([#1323]) + +### Changed + +- tidy async test and remove lint override ([#1312]) + +### Fixed + +- executable subcommand launching when script path not known ([#1322]) + +## [6.0.0] (2020-07-21) + +### Added + +- add support for variadic options ([#1250]) +- allow options to be added with just a short flag ([#1256]) + - *Breaking* the option property has same case as flag. e.g. flag `-n` accessed as `opts().n` (previously uppercase) +- *Breaking* throw an error if there might be a clash between option name and a Command property, with advice on how to resolve ([#1275]) + +### Fixed + +- Options which contain -no- in the middle of the option flag should not be treated as negatable. ([#1301]) + +## [6.0.0-0] (2020-06-20) + +(Released in 6.0.0) + +## [5.1.0] (2020-04-25) + +### Added + +- support for multiple command aliases, the first of which is shown in the auto-generated help ([#531], [#1236]) +- configuration support in `addCommand()` for `hidden` and `isDefault` ([#1232]) + +### Fixed + +- omit masked help flags from the displayed help ([#645], [#1247]) +- remove old short help flag when change help flags using `helpOption` ([#1248]) + +### Changed + +- remove use of `arguments` to improve auto-generated help in editors ([#1235]) +- rename `.command()` configuration `noHelp` to `hidden` (but not remove old support) ([#1232]) +- improvements to documentation +- update dependencies +- update tested versions of node +- eliminate lint errors in TypeScript ([#1208]) + +## [5.0.0] (2020-03-14) + +### Added + +* support for nested commands with action-handlers ([#1] [#764] [#1149]) +* `.addCommand()` for adding a separately configured command ([#764] [#1149]) +* allow a non-executable to be set as the default command ([#742] [#1149]) +* implicit help command when there are subcommands (previously only if executables) ([#1149]) +* customise implicit help command with `.addHelpCommand()` ([#1149]) +* display error message for unknown subcommand, by default ([#432] [#1088] [#1149]) +* display help for missing subcommand, by default ([#1088] [#1149]) +* combined short options as single argument may include boolean flags and value flag and value (e.g. `-a -b -p 80` can be written as `-abp80`) ([#1145]) +* `.parseOption()` includes short flag and long flag expansions ([#1145]) +* `.helpInformation()` returns help text as a string, previously a private routine ([#1169]) +* `.parse()` implicitly uses `process.argv` if arguments not specified ([#1172]) +* optionally specify where `.parse()` arguments "from", if not following node conventions ([#512] [#1172]) +* suggest help option along with unknown command error ([#1179]) +* TypeScript definition for `commands` property of `Command` ([#1184]) +* export `program` property ([#1195]) +* `createCommand` factory method to simplify subclassing ([#1191]) + +### Fixed + +* preserve argument order in subcommands ([#508] [#962] [#1138]) +* do not emit `command:*` for executable subcommands ([#809] [#1149]) +* action handler called whether or not there are non-option arguments ([#1062] [#1149]) +* combining option short flag and value in single argument now works for subcommands ([#1145]) +* only add implicit help command when it will not conflict with other uses of argument ([#1153] [#1149]) +* implicit help command works with command aliases ([#948] [#1149]) +* options are validated whether or not there is an action handler ([#1149]) + +### Changed + +* *Breaking* `.args` contains command arguments with just recognised options removed ([#1032] [#1138]) +* *Breaking* display error if required argument for command is missing ([#995] [#1149]) +* tighten TypeScript definition of custom option processing function passed to `.option()` ([#1119]) +* *Breaking* `.allowUnknownOption()` ([#802] [#1138]) + * unknown options included in arguments passed to command action handler + * unknown options included in `.args` +* only recognised option short flags and long flags are expanded (e.g. `-ab` or `--foo=bar`) ([#1145]) +* *Breaking* `.parseOptions()` ([#1138]) + * `args` in returned result renamed `operands` and does not include anything after first unknown option + * `unknown` in returned result has arguments after first unknown option including operands, not just options and values +* *Breaking* `.on('command:*', callback)` and other command events passed (changed) results from `.parseOptions`, i.e. operands and unknown ([#1138]) +* refactor Option from prototype to class ([#1133]) +* refactor Command from prototype to class ([#1159]) +* changes to error handling ([#1165]) + * throw for author error, not just display message + * preflight for variadic error + * add tips to missing subcommand executable +* TypeScript fluent return types changed to be more subclass friendly, return `this` rather than `Command` ([#1180]) +* `.parseAsync` returns `Promise` to be consistent with `.parse()` ([#1180]) +* update dependencies + +### Removed + +* removed EventEmitter from TypeScript definition for Command, eliminating implicit peer dependency on `@types/node` ([#1146]) +* removed private function `normalize` (the functionality has been integrated into `parseOptions`) ([#1145]) +* `parseExpectedArgs` is now private ([#1149]) + +### Migration Tips + +If you use `.on('command:*')` or more complicated tests to detect an unrecognised subcommand, you may be able to delete the code and rely on the default behaviour. + +If you use `program.args` or more complicated tests to detect a missing subcommand, you may be able to delete the code and rely on the default behaviour. + +If you use `.command('*')` to add a default command, you may be be able to switch to `isDefault:true` with a named command. + +If you want to continue combining short options with optional values as though they were boolean flags, set `combineFlagAndOptionalValue(false)` +to expand `-fb` to `-f -b` rather than `-f b`. + +## [5.0.0-4] (2020-03-03) + +(Released in 5.0.0) + +## [5.0.0-3] (2020-02-20) + +(Released in 5.0.0) + +## [5.0.0-2] (2020-02-10) + +(Released in 5.0.0) + +## [5.0.0-1] (2020-02-08) + +(Released in 5.0.0) + +## [5.0.0-0] (2020-02-02) + +(Released in 5.0.0) + +## Older versions + +* [4.x](./changelogs/CHANGELOG-4.md) +* [3.x](./changelogs/CHANGELOG-3.md) +* [2.x](./changelogs/CHANGELOG-2.md) +* [1.x](./changelogs/CHANGELOG-1.md) +* [0.x](./changelogs/CHANGELOG-0.md) + +[#1]: https://github.com/tj/commander.js/issues/1 +[#432]: https://github.com/tj/commander.js/issues/432 +[#508]: https://github.com/tj/commander.js/issues/508 +[#512]: https://github.com/tj/commander.js/issues/512 +[#531]: https://github.com/tj/commander.js/issues/531 +[#645]: https://github.com/tj/commander.js/issues/645 +[#742]: https://github.com/tj/commander.js/issues/742 +[#764]: https://github.com/tj/commander.js/issues/764 +[#802]: https://github.com/tj/commander.js/issues/802 +[#809]: https://github.com/tj/commander.js/issues/809 +[#948]: https://github.com/tj/commander.js/issues/948 +[#962]: https://github.com/tj/commander.js/issues/962 +[#995]: https://github.com/tj/commander.js/issues/995 +[#1032]: https://github.com/tj/commander.js/issues/1032 +[#1062]: https://github.com/tj/commander.js/pull/1062 +[#1088]: https://github.com/tj/commander.js/issues/1088 +[#1119]: https://github.com/tj/commander.js/pull/1119 +[#1133]: https://github.com/tj/commander.js/pull/1133 +[#1138]: https://github.com/tj/commander.js/pull/1138 +[#1145]: https://github.com/tj/commander.js/pull/1145 +[#1146]: https://github.com/tj/commander.js/pull/1146 +[#1149]: https://github.com/tj/commander.js/pull/1149 +[#1153]: https://github.com/tj/commander.js/issues/1153 +[#1159]: https://github.com/tj/commander.js/pull/1159 +[#1165]: https://github.com/tj/commander.js/pull/1165 +[#1169]: https://github.com/tj/commander.js/pull/1169 +[#1172]: https://github.com/tj/commander.js/pull/1172 +[#1179]: https://github.com/tj/commander.js/pull/1179 +[#1180]: https://github.com/tj/commander.js/pull/1180 +[#1184]: https://github.com/tj/commander.js/pull/1184 +[#1191]: https://github.com/tj/commander.js/pull/1191 +[#1195]: https://github.com/tj/commander.js/pull/1195 +[#1208]: https://github.com/tj/commander.js/pull/1208 +[#1232]: https://github.com/tj/commander.js/pull/1232 +[#1235]: https://github.com/tj/commander.js/pull/1235 +[#1236]: https://github.com/tj/commander.js/pull/1236 +[#1247]: https://github.com/tj/commander.js/pull/1247 +[#1248]: https://github.com/tj/commander.js/pull/1248 +[#1250]: https://github.com/tj/commander.js/pull/1250 +[#1256]: https://github.com/tj/commander.js/pull/1256 +[#1275]: https://github.com/tj/commander.js/pull/1275 +[#1296]: https://github.com/tj/commander.js/pull/1296 +[#1301]: https://github.com/tj/commander.js/issues/1301 +[#1306]: https://github.com/tj/commander.js/pull/1306 +[#1312]: https://github.com/tj/commander.js/pull/1312 +[#1322]: https://github.com/tj/commander.js/pull/1322 +[#1323]: https://github.com/tj/commander.js/pull/1323 +[#1325]: https://github.com/tj/commander.js/pull/1325 +[#1326]: https://github.com/tj/commander.js/pull/1326 +[#1331]: https://github.com/tj/commander.js/pull/1331 +[#1332]: https://github.com/tj/commander.js/pull/1332 +[#1349]: https://github.com/tj/commander.js/pull/1349 +[#1353]: https://github.com/tj/commander.js/pull/1353 +[#1360]: https://github.com/tj/commander.js/pull/1360 +[#1361]: https://github.com/tj/commander.js/pull/1361 +[#1365]: https://github.com/tj/commander.js/pull/1365 +[#1368]: https://github.com/tj/commander.js/pull/1368 +[#1375]: https://github.com/tj/commander.js/pull/1375 +[#1380]: https://github.com/tj/commander.js/pull/1380 +[#1387]: https://github.com/tj/commander.js/pull/1387 +[#1390]: https://github.com/tj/commander.js/pull/1390 +[#1403]: https://github.com/tj/commander.js/pull/1403 +[#1409]: https://github.com/tj/commander.js/pull/1409 +[#1427]: https://github.com/tj/commander.js/pull/1427 +[#1440]: https://github.com/tj/commander.js/pull/1440 +[#1448]: https://github.com/tj/commander.js/pull/1448 +[#1449]: https://github.com/tj/commander.js/pull/1449 +[#1453]: https://github.com/tj/commander.js/pull/1453 +[#1454]: https://github.com/tj/commander.js/pull/1454 +[#1464]: https://github.com/tj/commander.js/pull/1464 +[#1475]: https://github.com/tj/commander.js/pull/1475 +[#1477]: https://github.com/tj/commander.js/pull/1477 +[#1483]: https://github.com/tj/commander.js/pull/1483 + +[Unreleased]: https://github.com/tj/commander.js/compare/master...develop +[7.2.0]: https://github.com/tj/commander.js/compare/v7.1.0...v7.2.0 +[7.1.0]: https://github.com/tj/commander.js/compare/v7.0.0...v7.1.0 +[7.0.0]: https://github.com/tj/commander.js/compare/v6.2.1...v7.0.0 +[7.0.0-2]: https://github.com/tj/commander.js/compare/v7.0.0-1...v7.0.0-2 +[7.0.0-1]: https://github.com/tj/commander.js/compare/v7.0.0-0...v7.0.0-1 +[7.0.0-0]: https://github.com/tj/commander.js/compare/v6.2.0...v7.0.0-0 +[6.2.1]: https://github.com/tj/commander.js/compare/v6.2.0..v6.2.1 +[6.2.0]: https://github.com/tj/commander.js/compare/v6.1.0..v6.2.0 +[6.1.0]: https://github.com/tj/commander.js/compare/v6.0.0..v6.1.0 +[6.0.0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0 +[6.0.0-0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0-0 +[5.1.0]: https://github.com/tj/commander.js/compare/v5.0.0..v5.1.0 +[5.0.0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0 +[5.0.0-4]: https://github.com/tj/commander.js/compare/v5.0.0-3..v5.0.0-4 +[5.0.0-3]: https://github.com/tj/commander.js/compare/v5.0.0-2..v5.0.0-3 +[5.0.0-2]: https://github.com/tj/commander.js/compare/v5.0.0-1..v5.0.0-2 +[5.0.0-1]: https://github.com/tj/commander.js/compare/v5.0.0-0..v5.0.0-1 +[5.0.0-0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0-0 diff --git a/node_modules/mathjs/examples/node_modules/webpack-cli/node_modules/commander/LICENSE b/node_modules/mathjs/examples/node_modules/webpack-cli/node_modules/commander/LICENSE new file mode 100644 index 0000000..10f997a --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/webpack-cli/node_modules/commander/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk + +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. diff --git a/node_modules/mathjs/examples/node_modules/webpack-cli/node_modules/commander/Readme.md b/node_modules/mathjs/examples/node_modules/webpack-cli/node_modules/commander/Readme.md new file mode 100644 index 0000000..d2a88a7 --- /dev/null +++ b/node_modules/mathjs/examples/node_modules/webpack-cli/node_modules/commander/Readme.md @@ -0,0 +1,917 @@ +# Commander.js + +[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22) +[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander) +[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true) +[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander) + +The complete solution for [node.js](http://nodejs.org) command-line interfaces. + +Read this in other languages: English | [简体中文](./Readme_zh-CN.md) + +- [Commander.js](#commanderjs) + - [Installation](#installation) + - [Declaring _program_ variable](#declaring-program-variable) + - [Options](#options) + - [Common option types, boolean and value](#common-option-types-boolean-and-value) + - [Default option value](#default-option-value) + - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue) + - [Required option](#required-option) + - [Variadic option](#variadic-option) + - [Version option](#version-option) + - [More configuration](#more-configuration) + - [Custom option processing](#custom-option-processing) + - [Commands](#commands) + - [Specify the argument syntax](#specify-the-argument-syntax) + - [Action handler](#action-handler) + - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands) + - [Automated help](#automated-help) + - [Custom help](#custom-help) + - [Display help from code](#display-help-from-code) + - [.usage and .name](#usage-and-name) + - [.helpOption(flags, description)](#helpoptionflags-description) + - [.addHelpCommand()](#addhelpcommand) + - [More configuration](#more-configuration-1) + - [Custom event listeners](#custom-event-listeners) + - [Bits and pieces](#bits-and-pieces) + - [.parse() and .parseAsync()](#parse-and-parseasync) + - [Parsing Configuration](#parsing-configuration) + - [Legacy options as properties](#legacy-options-as-properties) + - [TypeScript](#typescript) + - [createCommand()](#createcommand) + - [Node options such as `--harmony`](#node-options-such-as---harmony) + - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands) + - [Override exit and output handling](#override-exit-and-output-handling) + - [Additional documentation](#additional-documentation) + - [Examples](#examples) + - [Support](#support) + - [Commander for enterprise](#commander-for-enterprise) + +For information about terms used in this document see: [terminology](./docs/terminology.md) + +## Installation + +```bash +npm install commander +``` + +## Declaring _program_ variable + +Commander exports a global object which is convenient for quick programs. +This is used in the examples in this README for brevity. + +```js +const { program } = require('commander'); +program.version('0.0.1'); +``` + +For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use. + +```js +const { Command } = require('commander'); +const program = new Command(); +program.version('0.0.1'); +``` + +For named imports in ECMAScript modules, import from `commander/esm.mjs`. + +```js +// index.mjs +import { Command } from 'commander/esm.mjs'; +const program = new Command(); +``` + +And in TypeScript: + +```ts +// index.ts +import { Command } from 'commander'; +const program = new Command(); +``` + + +## Options + +Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|'). + +The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler. Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc. + +Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value). +For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`. + +You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted. + +By default options on the command line are not positional, and can be specified before or after other arguments. + +### Common option types, boolean and value + +The two most used option types are a boolean option, and an option which takes its value +from the following argument (declared with angle brackets like `--expect `). Both are `undefined` unless specified on command line. + +Example file: [options-common.js](./examples/options-common.js) + +```js +program + .option('-d, --debug', 'output extra debugging') + .option('-s, --small', 'small pizza size') + .option('-p, --pizza-type ', 'flavour of pizza'); + +program.parse(process.argv); + +const options = program.opts(); +if (options.debug) console.log(options); +console.log('pizza details:'); +if (options.small) console.log('- small pizza size'); +if (options.pizzaType) console.log(`- ${options.pizzaType}`); +``` + +```bash +$ pizza-options -d +{ debug: true, small: undefined, pizzaType: undefined } +pizza details: +$ pizza-options -p +error: option '-p, --pizza-type ' argument missing +$ pizza-options -ds -p vegetarian +{ debug: true, small: true, pizzaType: 'vegetarian' } +pizza details: +- small pizza size +- vegetarian +$ pizza-options --pizza-type=cheese +pizza details: +- cheese +``` + +`program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array. The parameter is optional and defaults to `process.argv`. + +### Default option value + +You can specify a default value for an option which takes a value. + +Example file: [options-defaults.js](./examples/options-defaults.js) + +```js +program + .option('-c, --cheese ', 'add the specified type of cheese', 'blue'); + +program.parse(); + +console.log(`cheese: ${program.opts().cheese}`); +``` + +```bash +$ pizza-options +cheese: blue +$ pizza-options --cheese stilton +cheese: stilton +``` + +### Other option types, negatable boolean and boolean|value + +You can define a boolean option long name with a leading `no-` to set the option value to false when used. +Defined alone this also makes the option true by default. + +If you define `--foo` first, adding `--no-foo` does not change the default value from what it would +otherwise be. You can specify a default boolean value for a boolean option and it can be overridden on command line. + +Example file: [options-negatable.js](./examples/options-negatable.js) + +```js +program + .option('--no-sauce', 'Remove sauce') + .option('--cheese ', 'cheese flavour', 'mozzarella') + .option('--no-cheese', 'plain with no cheese') + .parse(); + +const options = program.opts(); +const sauceStr = options.sauce ? 'sauce' : 'no sauce'; +const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`; +console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`); +``` + +```bash +$ pizza-options +You ordered a pizza with sauce and mozzarella cheese +$ pizza-options --sauce +error: unknown option '--sauce' +$ pizza-options --cheese=blue +You ordered a pizza with sauce and blue cheese +$ pizza-options --no-sauce --no-cheese +You ordered a pizza with no sauce and no cheese +``` + +You can specify an option which may be used as a boolean option but may optionally take an option-argument +(declared with square brackets like `--optional [value]`). + +Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js) + +```js +program + .option('-c, --cheese [type]', 'Add cheese with optional type'); + +program.parse(process.argv); + +const options = program.opts(); +if (options.cheese === undefined) console.log('no cheese'); +else if (options.cheese === true) console.log('add cheese'); +else console.log(`add cheese type ${options.cheese}`); +``` + +```bash +$ pizza-options +no cheese +$ pizza-options --cheese +add cheese +$ pizza-options --cheese mozzarella +add cheese type mozzarella +``` + +For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md). + +### Required option + +You may specify a required (mandatory) option using `.requiredOption`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing. + +Example file: [options-required.js](./examples/options-required.js) + +```js +program + .requiredOption('-c, --cheese ', 'pizza must have cheese'); + +program.parse(); +``` + +```bash +$ pizza +error: required option '-c, --cheese ' not specified +``` + +### Variadic option + +You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you +can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments +are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value +is specified in the same argument as the option then no further values are read. + +Example file: [options-variadic.js](./examples/options-variadic.js) + +```js +program + .option('-n, --number ', 'specify numbers') + .option('-l, --letter [letters...]', 'specify letters'); + +program.parse(); + +console.log('Options: ', program.opts()); +console.log('Remaining arguments: ', program.args); +``` + +```bash +$ collect -n 1 2 3 --letter a b c +Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] } +Remaining arguments: [] +$ collect --letter=A -n80 operand +Options: { number: [ '80' ], letter: [ 'A' ] } +Remaining arguments: [ 'operand' ] +$ collect --letter -n 1 -n 2 3 -- operand +Options: { number: [ '1', '2', '3' ], letter: true } +Remaining arguments: [ 'operand' ] +``` + +For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md). + +### Version option + +The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits. + +```js +program.version('0.0.1'); +``` + +```bash +$ ./examples/pizza -V +0.0.1 +``` + +You may change the flags and description by passing additional parameters to the `version` method, using +the same syntax for flags as the `option` method. + +```js +program.version('0.0.1', '-v, --vers', 'output the current version'); +``` + +### More configuration + +You can add most options using the `.option()` method, but there are some additional features available +by constructing an `Option` explicitly for less common cases. + +Example file: [options-extra.js](./examples/options-extra.js) + +```js +program + .addOption(new Option('-s, --secret').hideHelp()) + .addOption(new Option('-t, --timeout ', 'timeout in seconds').default(60, 'one minute')) + .addOption(new Option('-d, --drink ', 'drink size').choices(['small', 'medium', 'large'])); +``` + +```bash +$ extra --help +Usage: help [options] + +Options: + -t, --timeout timeout in seconds (default: one minute) + -d, --drink drink cup size (choices: "small", "medium", "large") + -h, --help display help for command + +$ extra --drink huge +error: option '-d, --drink ' argument 'huge' is invalid. Allowed choices are small, medium, large. +``` + +### Custom option processing + +You may specify a function to do custom processing of option-arguments. The callback function receives two parameters, +the user specified option-argument and the previous value for the option. It returns the new value for the option. + +This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing. + +You can optionally specify the default/starting value for the option after the function parameter. + +Example file: [options-custom-processing.js](./examples/options-custom-processing.js) + +```js +function myParseInt(value, dummyPrevious) { + // parseInt takes a string and a radix + const parsedValue = parseInt(value, 10); + if (isNaN(parsedValue)) { + throw new commander.InvalidOptionArgumentError('Not a number.'); + } + return parsedValue; +} + +function increaseVerbosity(dummyValue, previous) { + return previous + 1; +} + +function collect(value, previous) { + return previous.concat([value]); +} + +function commaSeparatedList(value, dummyPrevious) { + return value.split(','); +} + +program + .option('-f, --float ', 'float argument', parseFloat) + .option('-i, --integer ', 'integer argument', myParseInt) + .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0) + .option('-c, --collect ', 'repeatable value', collect, []) + .option('-l, --list ', 'comma separated list', commaSeparatedList) +; + +program.parse(); + +const options = program.opts(); +if (options.float !== undefined) console.log(`float: ${options.float}`); +if (options.integer !== undefined) console.log(`integer: ${options.integer}`); +if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`); +if (options.collect.length > 0) console.log(options.collect); +if (options.list !== undefined) console.log(options.list); +``` + +```bash +$ custom -f 1e2 +float: 100 +$ custom --integer 2 +integer: 2 +$ custom -v -v -v +verbose: 3 +$ custom -c a -c b -c c +[ 'a', 'b', 'c' ] +$ custom --list x,y,z +[ 'x', 'y', 'z' ] +``` + +## Commands + +You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)). + +In the first parameter to `.command()` you specify the command name and any command-arguments. The arguments may be `` or `[optional]`, and the last argument may also be `variadic...`. + +You can use `.addCommand()` to add an already configured subcommand to the program. + +For example: + +```js +// Command implemented using action handler (description is supplied separately to `.command`) +// Returns new command for configuring. +program + .command('clone [destination]') + .description('clone a repository into a newly created directory') + .action((source, destination) => { + console.log('clone command called'); + }); + +// Command implemented using stand-alone executable file (description is second parameter to `.command`) +// Returns `this` for adding more commands. +program + .command('start ', 'start named service') + .command('stop [service]', 'stop named service, or all if no name supplied'); + +// Command prepared separately. +// Returns `this` for adding more commands. +program + .addCommand(build.makeBuildCommand()); +``` + +Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will +remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other +subcommand is specified ([example](./examples/defaultCommand.js)). + +### Specify the argument syntax + +You use `.arguments` to specify the expected command-arguments for the top-level command, and for subcommands they are usually +included in the `.command` call. Angled brackets (e.g. ``) indicate required command-arguments. +Square brackets (e.g. `[optional]`) indicate optional command-arguments. +You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`. + +Example file: [arguments.js](./examples/arguments.js) + +```js +program + .version('0.1.0') + .arguments(' [password]') + .description('test command', { + username: 'user to login', + password: 'password for user, if required' + }) + .action((username, password) => { + console.log('username:', username); + console.log('environment:', password || 'no password given'); + }); +``` + + The last argument of a command can be variadic, and only the last argument. To make an argument variadic you + append `...` to the argument name. For example: + +```js +program + .version('0.1.0') + .command('rmdir ') + .action(function (dirs) { + dirs.forEach((dir) => { + console.log('rmdir %s', dir); + }); + }); +``` + +The variadic argument is passed to the action handler as an array. + +### Action handler + +The action handler gets passed a parameter for each command-argument you declared, and two additional parameters +which are the parsed options and the command object itself. + +Example file: [thank.js](./examples/thank.js) + +```js +program + .arguments('') + .option('-t, --title ', 'title to use before name') + .option('-d, --debug', 'display some debugging') + .action((name, options, command) => { + if (options.debug) { + console.error('Called %s with options %o', command.name(), options); + } + const title = options.title ? `${options.title} ` : ''; + console.log(`Thank-you ${title}${name}`); + }); +``` + +You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`. + +```js +async function run() { /* code goes here */ } + +async function main() { + program + .command('run') + .action(run); + await program.parseAsync(process.argv); +} +``` + +A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments will be reported as an error. You can suppress the unknown option checks with `.allowUnknownOption()`. By default it is not an error to +pass more arguments than declared, but you can make this an error with `.allowExcessArguments(false)`. + +### Stand-alone executable (sub)commands + +When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands. +Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`. +You can specify a custom name with the `executableFile` configuration option. + +You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level. + +Example file: [pm](./examples/pm) + +```js +program + .version('0.1.0') + .command('install [name]', 'install one or more packages') + .command('search [query]', 'search with optional query') + .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' }) + .command('list', 'list packages installed', { isDefault: true }); + +program.parse(process.argv); +``` + +If the program is designed to be installed globally, make sure the executables have proper modes, like `755`. + +## Automated help + +The help information is auto-generated based on the information commander already knows about your program. The default +help option is `-h,--help`. + +Example file: [pizza](./examples/pizza) + +```bash +$ node ./examples/pizza --help +Usage: pizza [options] + +An application for pizza ordering + +Options: + -p, --peppers Add peppers + -c, --cheese Add the specified type of cheese (default: "marble") + -C, --no-cheese You do not want any cheese + -h, --help display help for command +``` + +A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show +further help for the subcommand. These are effectively the same if the `shell` program has implicit help: + +```bash +shell help +shell --help + +shell help spawn +shell spawn --help +``` + +### Custom help + +You can add extra text to be displayed along with the built-in help. + +Example file: [custom-help](./examples/custom-help) + +```js +program + .option('-f, --foo', 'enable some foo'); + +program.addHelpText('after', ` + +Example call: + $ custom-help --help`); +``` + +Yields the following help output: + +```Text +Usage: custom-help [options] + +Options: + -f, --foo enable some foo + -h, --help display help for command + +Example call: + $ custom-help --help +``` + +The positions in order displayed are: + +- `beforeAll`: add to the program for a global banner or header +- `before`: display extra information before built-in help +- `after`: display extra information after built-in help +- `afterAll`: add to the program for a global footer (epilog) + +The positions "beforeAll" and "afterAll" apply to the command and all its subcommands. + +The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are: + +- error: a boolean for whether the help is being displayed due to a usage error +- command: the Command which is displaying the help + +### Display help from code + +`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status. + +`.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr. + +`.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself. + +### .usage and .name + +These allow you to customise the usage description in the first line of the help. The name is otherwise +deduced from the (full) program arguments. Given: + +```js +program + .name("my-command") + .usage("[global options] command") +``` + +The help will start with: + +```Text +Usage: my-command [global options] command +``` + +### .helpOption(flags, description) + +By default every command has a help option. Override the default help flags and description. Pass false to disable the built-in help option. + +```js +program + .helpOption('-e, --HELP', 'read more information'); +``` + +### .addHelpCommand() + +A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`. + +You can both turn on and customise the help command by supplying the name and description: + +```js +program.addHelpCommand('assist [command]', 'show assistance'); +``` + +### More configuration + +The built-in help is formatted using the Help class. +You can configure the Help behaviour by modifying data properties and methods using `.configureHelp()`, or by subclassing using `.createHelp()` if you prefer. + +The data properties are: + +- `helpWidth`: specify the wrap width, useful for unit tests +- `sortSubcommands`: sort the subcommands alphabetically +- `sortOptions`: sort the options alphabetically + +There are methods getting the visible lists of arguments, options, and subcommands. There are methods for formatting the items in the lists, with each item having a _term_ and _description_. Take a look at `.formatHelp()` to see how they are used. + +Example file: [configure-help.js](./examples/configure-help.js) + +``` +program.configureHelp({ + sortSubcommands: true, + subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage. +}); +``` + +## Custom event listeners + +You can execute custom actions by listening to command and option events. + +```js +program.on('option:verbose', function () { + process.env.VERBOSE = this.opts().verbose; +}); + +program.on('command:*', function (operands) { + console.error(`error: unknown command '${operands[0]}'`); + const availableCommands = program.commands.map(cmd => cmd.name()); + mySuggestBestMatch(operands[0], availableCommands); + process.exitCode = 1; +}); +``` + +## Bits and pieces + +### .parse() and .parseAsync() + +The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`. + +If the arguments follow different conventions than node you can pass a `from` option in the second parameter: + +- 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that +- 'electron': `argv[1]` varies depending on whether the electron application is packaged +- 'user': all of the arguments from the user + +For example: + +```js +program.parse(process.argv); // Explicit, node conventions +program.parse(); // Implicit, and auto-detect electron +program.parse(['-f', 'filename'], { from: 'user' }); +``` + +### Parsing Configuration + +If the default parsing does not suit your needs, there are some behaviours to support other usage patterns. + +By default program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use +an option for a different purpose in subcommands. + +Example file: [positional-options.js](./examples/positional-options.js) + +With positional options, the `-b` is a program option in the first line and a subcommand option in the second line: + +```sh +program -b subcommand +program subcommand -b +``` + +By default options are recognised before and after command-arguments. To only process options that come +before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program +without needing to use `--` to end the option processing. +To use pass through options in a subcommand, the program needs to enable positional options. + +Example file: [pass-through-options.js](./examples/pass-through-options.js) + +With pass through options, the `--port=80` is a program option in the first line and passed through as a command-argument in the second line: + +```sh +program --port=80 arg +program arg --port=80 +``` + +By default the option processing shows an error for an unknown option. To have an unknown option treated as an ordinary command-argument and continue looking for options, use `.allowUnknownOption()`. This lets you mix known and unknown options. + +By default the argument processing does not display an error for more command-arguments than expected. +To display an error for excess arguments, use`.allowExcessArguments(false)`. + +### Legacy options as properties + +Before Commander 7, the option values were stored as properties on the command. +This was convenient to code but the downside was possible clashes with +existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`. + +```js +program + .storeOptionsAsProperties() + .option('-d, --debug') + .action((commandAndOptions) => { + if (commandAndOptions.debug) { + console.error(`Called ${commandAndOptions.name()}`); + } + }); +``` + +### TypeScript + +If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly. e.g. + +```bash +node -r ts-node/register pm.ts +``` + +### createCommand() + +This factory function creates a new command. It is exported and may be used instead of using `new`, like: + +```js +const { createCommand } = require('commander'); +const program = createCommand(); +``` + +`createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally +when creating subcommands using `.command()`, and you may override it to +customise the new subcommand (example file [custom-command-class.js](./examples/custom-command-class.js)). + +### Node options such as `--harmony` + +You can enable `--harmony` option in two ways: + +- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.) +- Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand process. + +### Debugging stand-alone executable subcommands + +An executable subcommand is launched as a separate child process. + +If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al, +the inspector port is incremented by 1 for the spawned subcommand. + +If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration. + +### Override exit and output handling + +By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override +this behaviour and optionally supply a callback. The default override throws a `CommanderError`. + +The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help +is not affected by the override which is called after the display. + +```js +program.exitOverride(); + +try { + program.parse(process.argv); +} catch (err) { + // custom processing... +} +``` + +By default Commander is configured for a command-line application and writes to stdout and stderr. +You can modify this behaviour for custom applications. In addition, you can modify the display of error messages. + +Example file: [configure-output.js](./examples/configure-output.js) + + +```js +function errorColor(str) { + // Add ANSI escape codes to display text in red. + return `\x1b[31m${str}\x1b[0m`; +} + +program + .configureOutput({ + // Visibly override write routines as example! + writeOut: (str) => process.stdout.write(`[OUT] ${str}`), + writeErr: (str) => process.stdout.write(`[ERR] ${str}`), + // Highlight errors in color. + outputError: (str, write) => write(errorColor(str)) + }); +``` + +### Additional documentation + +There is more information available about: + +- [deprecated](./docs/deprecated.md) features still supported for backwards compatibility +- [options taking varying arguments](./docs/options-taking-varying-arguments.md) + +## Examples + +In a single command program, you might not need an action handler. + +Example file: [pizza](./examples/pizza) + +```js +const { program } = require('commander'); + +program + .description('An application for pizza ordering') + .option('-p, --peppers', 'Add peppers') + .option('-c, --cheese ', 'Add the specified type of cheese', 'marble') + .option('-C, --no-cheese', 'You do not want any cheese'); + +program.parse(); + +const options = program.opts(); +console.log('you ordered a pizza with:'); +if (options.peppers) console.log(' - peppers'); +const cheese = !options.cheese ? 'no' : options.cheese; +console.log(' - %s cheese', cheese); +``` + +In a multi-command program, you will have action handlers for each command (or stand-alone executables for the commands). + +Example file: [deploy](./examples/deploy) + +```js +const { Command } = require('commander'); +const program = new Command(); + +program + .version('0.0.1') + .option('-c, --config ', 'set config path', './deploy.conf'); + +program + .command('setup [env]') + .description('run setup commands for all envs') + .option('-s, --setup_mode ', 'Which setup mode to use', 'normal') + .action((env, options) => { + env = env || 'all'; + console.log('read config from %s', program.opts().config); + console.log('setup for %s env(s) with %s mode', env, options.setup_mode); + }); + +program + .command('exec +``` + +```js +// Make a predictable pseudorandom number generator. +var myrng = new Math.seedrandom('hello.'); +console.log(myrng()); // Always 0.9282578795792454 +console.log(myrng()); // Always 0.3752569768646784 + +// Use "quick" to get only 32 bits of randomness in a float. +console.log(myrng.quick()); // Always 0.7316977467853576 + +// Use "int32" to get a 32 bit (signed) integer +console.log(myrng.int32()); // Always 1966374204 + +// Calling seedrandom with no arguments creates an ARC4-based PRNG +// that is autoseeded using the current time, dom state, and other +// accumulated local entropy. +var prng = new Math.seedrandom(); +console.log(prng()); // Reasonably unpredictable. + +// Seeds using the given explicit seed mixed with accumulated entropy. +prng = new Math.seedrandom('added entropy.', { entropy: true }); +console.log(prng()); // As unpredictable as added entropy. + +// Warning: if you call Math.seedrandom without `new`, it replaces +// Math.random with the predictable new Math.seedrandom(...), as follows: +Math.seedrandom('hello.'); +console.log(Math.random()); // Always 0.9282578795792454 +console.log(Math.random()); // Always 0.3752569768646784 + +``` + +**Note**: calling `Math.seedrandom('constant')` without `new` will make +`Math.random()` predictable globally, which is intended to be useful for +derandomizing code for testing, but should not be done in a production library. +If you need a local seeded PRNG, use `myrng = new Math.seedrandom('seed')` +instead. For example, [cryptico](https://www.npmjs.com/package/cryptico), +an RSA encryption package, [uses the wrong form]( +https://github.com/wwwtyro/cryptico/blob/9291ece6/api.js#L264), +and thus secretly makes `Math.random()` perfectly predictable. +The cryptico library (and any other library that does this) +should not be trusted in a security-sensitive application. + + +Other Fast PRNG Algorithms +-------------------------- + +The package includes some other fast PRNGs. To use Johannes Baagøe's +extremely fast Alea PRNG: + + +```html + +``` + +```js +// Use alea for Johannes Baagøe's clever and fast floating-point RNG. +var arng = new alea('hello.'); + +// By default provides 32 bits of randomness in a float. +console.log(arng()); // Always 0.4783254903741181 + +// Use "double" to get 56 bits of randomness. +console.log(arng.double()); // Always 0.8297006866124559 + +// Use "int32" to get a 32 bit (signed) integer. +console.log(arng.int32()); // Always 1076136327 +``` + +Besides alea, there are several other faster PRNGs available. +Note that none of these fast PRNGs provide autoseeding: you +need to provide your own seed (or use the default autoseeded +seedrandom to make a seed). + +|PRNG name | Time vs native | Period | Author | +|-----------|----------------|-------------|----------------------| +|`alea` | 1.95 ns, 0.9x | ~2^116 | Baagøe | +|`xor128` | 2.04 ns, 0.9x | 2^128-1 | Marsaglia | +|`tychei` | 2.32 ns, 1.1x | ~2^127 | Neves/Araujo (ChaCha)| +|`xorwow` | 2.40 ns, 1.1x | 2^192-2^32 | Marsaglia | +|`xor4096` | 2.40 ns, 1.1x | 2^4096-2^32 | Brent (xorgens) | +|`xorshift7`| 2.64 ns, 1.3x | 2^256-1 | Panneton/L'ecuyer | +|`quick` | 3.80 ns, 1.8x | ~2^1600 | Bau (ARC4) | + +(Timings were done on node v0.12.2 on a single-core Google Compute Engine +instance. `quick` is just the 32-bit version of the RC4-based PRNG +originally packaged with seedrandom.) + + +CJS / Node.js usage +------------------- + +``` +npm install seedrandom +``` + +```js +// Local PRNG: does not affect Math.random. +var seedrandom = require('seedrandom'); +var rng = seedrandom('hello.'); +console.log(rng()); // Always 0.9282578795792454 + +// Global PRNG: set Math.random. +seedrandom('hello.', { global: true }); +console.log(Math.random()); // Always 0.9282578795792454 + +// Autoseeded ARC4-based PRNG. +rng = seedrandom(); +console.log(rng()); // Reasonably unpredictable. + +// Mixing accumulated entropy. +rng = seedrandom('added entropy.', { entropy: true }); +console.log(rng()); // As unpredictable as added entropy. + +// Using alternate algorithms, as listed above. +var rng2 = seedrandom.xor4096('hello.') +console.log(rng2()); +``` + +Starting in version 3, when using via require('seedrandom'), the global +`Math.seedrandom` is no longer available. + + +Require.js usage +---------------- + +Similar to Node.js usage: + +``` +bower install seedrandom +``` + +``` +require(['seedrandom'], function(seedrandom) { + var rng = seedrandom('hello.'); + console.log(rng()); // Always 0.9282578795792454 +}); +``` + + +Network seeding +--------------- + +```html + + + + + + +``` + +Reseeding using user input +-------------------------- + +```js +var seed = Math.seedrandom(); // Use prng with an automatic seed. +document.write(Math.random()); // Pretty much unpredictable x. + +var rng = new Math.seedrandom(seed); // A new prng with the same seed. +document.write(rng()); // Repeat the 'unpredictable' x. + +function reseed(event, count) { // Define a custom entropy collector. + var t = []; + function w(e) { + t.push([e.pageX, e.pageY, +new Date]); + if (t.length < count) { return; } + document.removeEventListener(event, w); + Math.seedrandom(t, { entropy: true }); + } + document.addEventListener(event, w); +} +reseed('mousemove', 100); // Reseed after 100 mouse moves. +``` + +The "pass" option can be used to get both the prng and the seed. +The following returns both an autoseeded prng and the seed as an object, +without mutating Math.random: + +```js +var obj = Math.seedrandom(null, { pass: function(prng, seed) { + return { random: prng, seed: seed }; +}}); +``` + + +Saving and Restoring PRNG state +------------------------------- + +```js +var seedrandom = Math.seedrandom; +var saveable = seedrandom("secret-seed", {state: true}); +for (var j = 0; j < 1e5; ++j) saveable(); +var saved = saveable.state(); +var replica = seedrandom("", {state: saved}); +assert(replica() == saveable()); +``` + +In normal use the prng is opaque and its internal state cannot be accessed. +However, if the "state" option is specified, the prng gets a state() method +that returns a plain object the can be used to reconstruct a prng later in +the same state (by passing that saved object back as the state option). + + +Version notes +------------- + +The random number sequence is the same as version 1.0 for string seeds. + +* Version 2.0 changed the sequence for non-string seeds. +* Version 2.1 speeds seeding and uses window.crypto to autoseed if present. +* Version 2.2 alters non-crypto autoseeding to sweep up entropy from plugins. +* Version 2.3 adds support for "new", module loading, and a null seed arg. +* Version 2.3.1 adds a build environment, module packaging, and tests. +* Version 2.3.4 fixes bugs on IE8, and switches to MIT license. +* Version 2.3.6 adds a readable options object argument. +* Version 2.3.10 adds support for node.js crypto (contributed by ctd1500). +* Version 2.3.11 adds an option to load and save internal state. +* Version 2.4.0 adds implementations of several other fast PRNGs. +* Version 2.4.2 adds an implementation of Baagoe's very fast Alea PRNG. +* Version 2.4.3 ignores nodejs crypto when under browserify. +* Version 2.4.4 avoids strict mode problem with global this reference. +* Version 3.0.1 removes Math.seedrandom for require('seedrandom') users. +* Version 3.0.3 updates package.json for CDN entrypoints. +* Version 3.0.5 removes eval to avoid triggering content-security policy. + +The standard ARC4 key scheduler cycles short keys, which means that +seedrandom('ab') is equivalent to seedrandom('abab') and 'ababab'. +Therefore it is a good idea to add a terminator to avoid trivial +equivalences on short string seeds, e.g., Math.seedrandom(str + '\0'). +Starting with version 2.0, a terminator is added automatically for +non-string seeds, so seeding with the number 111 is the same as seeding +with '111\0'. + +When seedrandom() is called with zero args or a null seed, it uses a +seed drawn from the browser crypto object if present. If there is no +crypto support, seedrandom() uses the current time, the native rng, +and a walk of several DOM objects to collect a few bits of entropy. + +Each time the one- or two-argument forms of seedrandom are called, +entropy from the passed seed is accumulated in a pool to help generate +future seeds for the zero- and two-argument forms of seedrandom. + +On speed - This javascript implementation of Math.random() is several +times slower than the built-in Math.random() because it is not native +code, but that is typically fast enough. Some details (timings on +Chrome 25 on a 2010 vintage macbook): + +* seeded Math.random() - avg less than 0.0002 milliseconds per call +* seedrandom('explicit.') - avg less than 0.2 milliseconds per call +* seedrandom('explicit.', true) - avg less than 0.2 milliseconds per call +* seedrandom() with crypto - avg less than 0.2 milliseconds per call + +Autoseeding without crypto is somewhat slow, about 20-30 milliseconds on +a 2012 windows 7 1.5ghz i5 laptop, as seen on Firefox 19, IE 10, and Opera. +Seeded rng calls themselves are fast across these browsers, with slowest +numbers on Opera at about 0.0005 ms per seeded Math.random(). + + +LICENSE (MIT) +------------- + +Copyright 2019 David Bau. + +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. + diff --git a/node_modules/seedrandom/bower.json b/node_modules/seedrandom/bower.json new file mode 100644 index 0000000..8e62b3a --- /dev/null +++ b/node_modules/seedrandom/bower.json @@ -0,0 +1,16 @@ +{ + "name": "seedrandom", + "description": "Seeded random number generator for Javascript.", + "main": "seedrandom.js", + "license": "MIT", + "keywords": [ + "random", + "seed", + "crypto" + ], + "ignore": [], + "devDependencies": { + "qunit": "latest", + "requirejs": "latest" + } +} diff --git a/node_modules/seedrandom/component.json b/node_modules/seedrandom/component.json new file mode 100644 index 0000000..43fea29 --- /dev/null +++ b/node_modules/seedrandom/component.json @@ -0,0 +1,10 @@ +{ + "name": "seedrandom", + "version": "3.0.0", + "description": "Seeded random number generator for Javascript", + "repository": "davidbau/seedrandom", + "main": "seedrandom.js", + "scripts": [ "seedrandom.js" ], + "keywords": [ "random", "seed", "crypto" ], + "license": "MIT" +} diff --git a/node_modules/seedrandom/coverage/coverage.json b/node_modules/seedrandom/coverage/coverage.json new file mode 100644 index 0000000..9e9657b --- /dev/null +++ b/node_modules/seedrandom/coverage/coverage.json @@ -0,0 +1 @@ +{"/home/davidbau/git/seedrandom/seedrandom.js":{"path":"/home/davidbau/git/seedrandom/seedrandom.js","s":{"1":6,"2":6,"3":1,"4":23,"5":23,"6":23,"7":23,"8":23,"9":3694,"10":3694,"11":3918,"12":3918,"13":3918,"14":3694,"15":9252,"16":9252,"17":9252,"18":3694,"19":23,"20":1025,"21":23,"22":4100001,"23":23,"24":23,"25":23,"26":20,"27":4,"28":2,"29":4,"30":2,"31":20,"32":1,"33":1,"34":19,"35":1,"36":23,"37":23,"38":1,"39":23,"40":5888,"41":23,"42":5888,"43":5888,"44":23,"45":4108661,"46":4108661,"47":16436074,"48":16436074,"49":4108661,"50":4108661,"51":4108661,"52":1,"53":4,"54":4,"55":4,"56":4,"57":1,"58":174,"59":174,"60":8,"61":151,"62":151,"63":174,"64":1,"65":52,"66":52,"67":46040,"68":52,"69":1,"70":4,"71":4,"72":4,"73":3,"74":1,"75":1,"76":3,"77":1,"78":1,"79":1,"80":81,"81":6,"82":6,"83":6,"84":6,"85":6,"86":0,"87":0,"88":0,"89":0},"b":{"1":[1,22],"2":[22,11],"3":[2,21],"4":[4,17],"5":[23,21,20],"6":[4,16],"7":[2,2],"8":[1,19],"9":[4,19],"10":[1,22],"11":[8,166],"12":[174,56],"13":[8,166],"14":[29,137],"15":[3,1],"16":[4,3],"17":[1,1],"18":[1,0],"19":[6,0],"20":[6,6],"21":[0,0],"22":[0,0]},"f":{"1":6,"2":23,"3":3694,"4":1025,"5":4100001,"6":20,"7":2,"8":23,"9":4108661,"10":4,"11":174,"12":52,"13":4,"14":81,"15":0},"fnMap":{"1":{"name":"(anonymous_1)","line":25,"loc":{"start":{"line":25,"column":1},"end":{"line":25,"column":23}}},"2":{"name":"seedrandom","line":47,"loc":{"start":{"line":47,"column":0},"end":{"line":47,"column":45}}},"3":{"name":"(anonymous_3)","line":61,"loc":{"start":{"line":61,"column":13},"end":{"line":61,"column":24}}},"4":{"name":"(anonymous_4)","line":78,"loc":{"start":{"line":78,"column":15},"end":{"line":78,"column":26}}},"5":{"name":"(anonymous_5)","line":79,"loc":{"start":{"line":79,"column":15},"end":{"line":79,"column":26}}},"6":{"name":"(anonymous_6)","line":87,"loc":{"start":{"line":87,"column":6},"end":{"line":87,"column":48}}},"7":{"name":"(anonymous_7)","line":92,"loc":{"start":{"line":92,"column":23},"end":{"line":92,"column":34}}},"8":{"name":"ARC4","line":119,"loc":{"start":{"line":119,"column":0},"end":{"line":119,"column":19}}},"9":{"name":"(anonymous_9)","line":136,"loc":{"start":{"line":136,"column":10},"end":{"line":136,"column":26}}},"10":{"name":"copy","line":156,"loc":{"start":{"line":156,"column":0},"end":{"line":156,"column":20}}},"11":{"name":"flatten","line":167,"loc":{"start":{"line":167,"column":0},"end":{"line":167,"column":29}}},"12":{"name":"mixkey","line":182,"loc":{"start":{"line":182,"column":0},"end":{"line":182,"column":27}}},"13":{"name":"autoseed","line":196,"loc":{"start":{"line":196,"column":0},"end":{"line":196,"column":20}}},"14":{"name":"tostring","line":218,"loc":{"start":{"line":218,"column":0},"end":{"line":218,"column":21}}},"15":{"name":"(anonymous_15)","line":242,"loc":{"start":{"line":242,"column":9},"end":{"line":242,"column":20}}}},"statementMap":{"1":{"start":{"line":25,"column":0},"end":{"line":253,"column":2}},"2":{"start":{"line":32,"column":0},"end":{"line":41,"column":15}},"3":{"start":{"line":47,"column":0},"end":{"line":107,"column":1}},"4":{"start":{"line":48,"column":2},"end":{"line":48,"column":15}},"5":{"start":{"line":49,"column":2},"end":{"line":49,"column":68}},"6":{"start":{"line":52,"column":2},"end":{"line":54,"column":49}},"7":{"start":{"line":57,"column":2},"end":{"line":57,"column":27}},"8":{"start":{"line":61,"column":2},"end":{"line":76,"column":4}},"9":{"start":{"line":62,"column":4},"end":{"line":64,"column":14}},"10":{"start":{"line":65,"column":4},"end":{"line":69,"column":5}},"11":{"start":{"line":66,"column":6},"end":{"line":66,"column":26}},"12":{"start":{"line":67,"column":6},"end":{"line":67,"column":17}},"13":{"start":{"line":68,"column":6},"end":{"line":68,"column":20}},"14":{"start":{"line":70,"column":4},"end":{"line":74,"column":5}},"15":{"start":{"line":71,"column":6},"end":{"line":71,"column":13}},"16":{"start":{"line":72,"column":6},"end":{"line":72,"column":13}},"17":{"start":{"line":73,"column":6},"end":{"line":73,"column":15}},"18":{"start":{"line":75,"column":4},"end":{"line":75,"column":23}},"19":{"start":{"line":78,"column":2},"end":{"line":78,"column":51}},"20":{"start":{"line":78,"column":28},"end":{"line":78,"column":49}},"21":{"start":{"line":79,"column":2},"end":{"line":79,"column":61}},"22":{"start":{"line":79,"column":28},"end":{"line":79,"column":59}},"23":{"start":{"line":80,"column":2},"end":{"line":80,"column":21}},"24":{"start":{"line":83,"column":2},"end":{"line":83,"column":33}},"25":{"start":{"line":86,"column":2},"end":{"line":106,"column":17}},"26":{"start":{"line":88,"column":8},"end":{"line":93,"column":9}},"27":{"start":{"line":90,"column":10},"end":{"line":90,"column":45}},"28":{"start":{"line":90,"column":25},"end":{"line":90,"column":43}},"29":{"start":{"line":92,"column":10},"end":{"line":92,"column":60}},"30":{"start":{"line":92,"column":36},"end":{"line":92,"column":58}},"31":{"start":{"line":97,"column":8},"end":{"line":101,"column":25}},"32":{"start":{"line":97,"column":28},"end":{"line":97,"column":49}},"33":{"start":{"line":97,"column":50},"end":{"line":97,"column":62}},"34":{"start":{"line":101,"column":13},"end":{"line":101,"column":25}},"35":{"start":{"line":119,"column":0},"end":{"line":150,"column":1}},"36":{"start":{"line":120,"column":2},"end":{"line":121,"column":59}},"37":{"start":{"line":124,"column":2},"end":{"line":124,"column":36}},"38":{"start":{"line":124,"column":17},"end":{"line":124,"column":34}},"39":{"start":{"line":127,"column":2},"end":{"line":129,"column":3}},"40":{"start":{"line":128,"column":4},"end":{"line":128,"column":15}},"41":{"start":{"line":130,"column":2},"end":{"line":133,"column":3}},"42":{"start":{"line":131,"column":4},"end":{"line":131,"column":60}},"43":{"start":{"line":132,"column":4},"end":{"line":132,"column":13}},"44":{"start":{"line":136,"column":2},"end":{"line":149,"column":12}},"45":{"start":{"line":138,"column":4},"end":{"line":139,"column":37}},"46":{"start":{"line":140,"column":4},"end":{"line":143,"column":5}},"47":{"start":{"line":141,"column":6},"end":{"line":141,"column":32}},"48":{"start":{"line":142,"column":6},"end":{"line":142,"column":78}},"49":{"start":{"line":144,"column":4},"end":{"line":144,"column":13}},"50":{"start":{"line":144,"column":14},"end":{"line":144,"column":23}},"51":{"start":{"line":145,"column":4},"end":{"line":145,"column":13}},"52":{"start":{"line":156,"column":0},"end":{"line":161,"column":1}},"53":{"start":{"line":157,"column":2},"end":{"line":157,"column":12}},"54":{"start":{"line":158,"column":2},"end":{"line":158,"column":12}},"55":{"start":{"line":159,"column":2},"end":{"line":159,"column":20}},"56":{"start":{"line":160,"column":2},"end":{"line":160,"column":11}},"57":{"start":{"line":167,"column":0},"end":{"line":175,"column":1}},"58":{"start":{"line":168,"column":2},"end":{"line":168,"column":44}},"59":{"start":{"line":169,"column":2},"end":{"line":173,"column":3}},"60":{"start":{"line":170,"column":4},"end":{"line":172,"column":5}},"61":{"start":{"line":171,"column":6},"end":{"line":171,"column":70}},"62":{"start":{"line":171,"column":12},"end":{"line":171,"column":55}},"63":{"start":{"line":174,"column":2},"end":{"line":174,"column":71}},"64":{"start":{"line":182,"column":0},"end":{"line":189,"column":1}},"65":{"start":{"line":183,"column":2},"end":{"line":183,"column":43}},"66":{"start":{"line":184,"column":2},"end":{"line":187,"column":3}},"67":{"start":{"line":185,"column":4},"end":{"line":186,"column":74}},"68":{"start":{"line":188,"column":2},"end":{"line":188,"column":23}},"69":{"start":{"line":196,"column":0},"end":{"line":212,"column":1}},"70":{"start":{"line":197,"column":2},"end":{"line":211,"column":3}},"71":{"start":{"line":198,"column":4},"end":{"line":198,"column":12}},"72":{"start":{"line":199,"column":4},"end":{"line":205,"column":5}},"73":{"start":{"line":201,"column":6},"end":{"line":201,"column":23}},"74":{"start":{"line":203,"column":6},"end":{"line":203,"column":34}},"75":{"start":{"line":204,"column":6},"end":{"line":204,"column":62}},"76":{"start":{"line":206,"column":4},"end":{"line":206,"column":25}},"77":{"start":{"line":208,"column":4},"end":{"line":209,"column":45}},"78":{"start":{"line":210,"column":4},"end":{"line":210,"column":71}},"79":{"start":{"line":218,"column":0},"end":{"line":220,"column":1}},"80":{"start":{"line":219,"column":2},"end":{"line":219,"column":41}},"81":{"start":{"line":229,"column":0},"end":{"line":229,"column":28}},"82":{"start":{"line":235,"column":0},"end":{"line":246,"column":1}},"83":{"start":{"line":236,"column":2},"end":{"line":236,"column":30}},"84":{"start":{"line":238,"column":2},"end":{"line":240,"column":17}},"85":{"start":{"line":239,"column":4},"end":{"line":239,"column":35}},"86":{"start":{"line":241,"column":7},"end":{"line":246,"column":1}},"87":{"start":{"line":242,"column":2},"end":{"line":242,"column":44}},"88":{"start":{"line":242,"column":22},"end":{"line":242,"column":40}},"89":{"start":{"line":245,"column":2},"end":{"line":245,"column":38}}},"branchMap":{"1":{"line":49,"type":"cond-expr","locations":[{"start":{"line":49,"column":32},"end":{"line":49,"column":49}},{"start":{"line":49,"column":53},"end":{"line":49,"column":66}}]},"2":{"line":49,"type":"binary-expr","locations":[{"start":{"line":49,"column":53},"end":{"line":49,"column":60}},{"start":{"line":49,"column":64},"end":{"line":49,"column":66}}]},"3":{"line":53,"type":"cond-expr","locations":[{"start":{"line":53,"column":22},"end":{"line":53,"column":44}},{"start":{"line":54,"column":4},"end":{"line":54,"column":38}}]},"4":{"line":54,"type":"cond-expr","locations":[{"start":{"line":54,"column":21},"end":{"line":54,"column":31}},{"start":{"line":54,"column":34},"end":{"line":54,"column":38}}]},"5":{"line":86,"type":"binary-expr","locations":[{"start":{"line":86,"column":10},"end":{"line":86,"column":22}},{"start":{"line":86,"column":26},"end":{"line":86,"column":34}},{"start":{"line":87,"column":6},"end":{"line":102,"column":7}}]},"6":{"line":88,"type":"if","locations":[{"start":{"line":88,"column":8},"end":{"line":88,"column":8}},{"start":{"line":88,"column":8},"end":{"line":88,"column":8}}]},"7":{"line":90,"type":"if","locations":[{"start":{"line":90,"column":10},"end":{"line":90,"column":10}},{"start":{"line":90,"column":10},"end":{"line":90,"column":10}}]},"8":{"line":97,"type":"if","locations":[{"start":{"line":97,"column":8},"end":{"line":97,"column":8}},{"start":{"line":97,"column":8},"end":{"line":97,"column":8}}]},"9":{"line":105,"type":"cond-expr","locations":[{"start":{"line":105,"column":24},"end":{"line":105,"column":38}},{"start":{"line":105,"column":42},"end":{"line":105,"column":54}}]},"10":{"line":124,"type":"if","locations":[{"start":{"line":124,"column":2},"end":{"line":124,"column":2}},{"start":{"line":124,"column":2},"end":{"line":124,"column":2}}]},"11":{"line":169,"type":"if","locations":[{"start":{"line":169,"column":2},"end":{"line":169,"column":2}},{"start":{"line":169,"column":2},"end":{"line":169,"column":2}}]},"12":{"line":169,"type":"binary-expr","locations":[{"start":{"line":169,"column":6},"end":{"line":169,"column":11}},{"start":{"line":169,"column":15},"end":{"line":169,"column":30}}]},"13":{"line":174,"type":"cond-expr","locations":[{"start":{"line":174,"column":26},"end":{"line":174,"column":32}},{"start":{"line":174,"column":35},"end":{"line":174,"column":69}}]},"14":{"line":174,"type":"cond-expr","locations":[{"start":{"line":174,"column":53},"end":{"line":174,"column":56}},{"start":{"line":174,"column":59},"end":{"line":174,"column":69}}]},"15":{"line":199,"type":"if","locations":[{"start":{"line":199,"column":4},"end":{"line":199,"column":4}},{"start":{"line":199,"column":4},"end":{"line":199,"column":4}}]},"16":{"line":199,"type":"binary-expr","locations":[{"start":{"line":199,"column":8},"end":{"line":199,"column":18}},{"start":{"line":199,"column":23},"end":{"line":199,"column":51}}]},"17":{"line":204,"type":"binary-expr","locations":[{"start":{"line":204,"column":7},"end":{"line":204,"column":20}},{"start":{"line":204,"column":24},"end":{"line":204,"column":39}}]},"18":{"line":209,"type":"binary-expr","locations":[{"start":{"line":209,"column":18},"end":{"line":209,"column":25}},{"start":{"line":209,"column":29},"end":{"line":209,"column":44}}]},"19":{"line":235,"type":"if","locations":[{"start":{"line":235,"column":0},"end":{"line":235,"column":0}},{"start":{"line":235,"column":0},"end":{"line":235,"column":0}}]},"20":{"line":235,"type":"binary-expr","locations":[{"start":{"line":235,"column":4},"end":{"line":235,"column":31}},{"start":{"line":235,"column":35},"end":{"line":235,"column":49}}]},"21":{"line":241,"type":"if","locations":[{"start":{"line":241,"column":7},"end":{"line":241,"column":7}},{"start":{"line":241,"column":7},"end":{"line":241,"column":7}}]},"22":{"line":241,"type":"binary-expr","locations":[{"start":{"line":241,"column":11},"end":{"line":241,"column":40}},{"start":{"line":241,"column":44},"end":{"line":241,"column":54}}]}}},"/home/davidbau/git/seedrandom/lib/xor128.js":{"path":"/home/davidbau/git/seedrandom/lib/xor128.js","s":{"1":1,"2":1,"3":3,"4":3,"5":3,"6":3,"7":3,"8":3,"9":4105327,"10":4105327,"11":4105327,"12":4105327,"13":4105327,"14":3,"15":2,"16":1,"17":3,"18":198,"19":198,"20":1,"21":2,"22":2,"23":2,"24":2,"25":2,"26":1,"27":3,"28":4102054,"29":3,"30":1025,"31":1025,"32":1025,"33":3,"34":3,"35":3,"36":2,"37":1,"38":2,"39":1,"40":3,"41":1,"42":1,"43":0,"44":0,"45":0,"46":0},"b":{"1":[2,1],"2":[3,2],"3":[2,1],"4":[1,1],"5":[1,0],"6":[1,1],"7":[0,0],"8":[0,0],"9":[1,1],"10":[1,0]},"f":{"1":1,"2":3,"3":4105327,"4":2,"5":3,"6":4102054,"7":1025,"8":1,"9":0},"fnMap":{"1":{"name":"(anonymous_1)","line":4,"loc":{"start":{"line":4,"column":1},"end":{"line":4,"column":34}}},"2":{"name":"XorGen","line":6,"loc":{"start":{"line":6,"column":0},"end":{"line":6,"column":22}}},"3":{"name":"(anonymous_3)","line":15,"loc":{"start":{"line":15,"column":12},"end":{"line":15,"column":23}}},"4":{"name":"copy","line":38,"loc":{"start":{"line":38,"column":0},"end":{"line":38,"column":20}}},"5":{"name":"impl","line":46,"loc":{"start":{"line":46,"column":0},"end":{"line":46,"column":26}}},"6":{"name":"(anonymous_6)","line":49,"loc":{"start":{"line":49,"column":13},"end":{"line":49,"column":24}}},"7":{"name":"(anonymous_7)","line":50,"loc":{"start":{"line":50,"column":16},"end":{"line":50,"column":27}}},"8":{"name":"(anonymous_8)","line":62,"loc":{"start":{"line":62,"column":17},"end":{"line":62,"column":28}}},"9":{"name":"(anonymous_9)","line":70,"loc":{"start":{"line":70,"column":9},"end":{"line":70,"column":20}}}},"statementMap":{"1":{"start":{"line":4,"column":0},"end":{"line":79,"column":2}},"2":{"start":{"line":6,"column":0},"end":{"line":36,"column":1}},"3":{"start":{"line":7,"column":2},"end":{"line":7,"column":30}},"4":{"start":{"line":9,"column":2},"end":{"line":9,"column":11}},"5":{"start":{"line":10,"column":2},"end":{"line":10,"column":11}},"6":{"start":{"line":11,"column":2},"end":{"line":11,"column":11}},"7":{"start":{"line":12,"column":2},"end":{"line":12,"column":11}},"8":{"start":{"line":15,"column":2},"end":{"line":21,"column":4}},"9":{"start":{"line":16,"column":4},"end":{"line":16,"column":32}},"10":{"start":{"line":17,"column":4},"end":{"line":17,"column":16}},"11":{"start":{"line":18,"column":4},"end":{"line":18,"column":16}},"12":{"start":{"line":19,"column":4},"end":{"line":19,"column":16}},"13":{"start":{"line":20,"column":4},"end":{"line":20,"column":49}},"14":{"start":{"line":23,"column":2},"end":{"line":29,"column":3}},"15":{"start":{"line":25,"column":4},"end":{"line":25,"column":16}},"16":{"start":{"line":28,"column":4},"end":{"line":28,"column":20}},"17":{"start":{"line":32,"column":2},"end":{"line":35,"column":3}},"18":{"start":{"line":33,"column":4},"end":{"line":33,"column":38}},"19":{"start":{"line":34,"column":4},"end":{"line":34,"column":14}},"20":{"start":{"line":38,"column":0},"end":{"line":44,"column":1}},"21":{"start":{"line":39,"column":2},"end":{"line":39,"column":12}},"22":{"start":{"line":40,"column":2},"end":{"line":40,"column":12}},"23":{"start":{"line":41,"column":2},"end":{"line":41,"column":12}},"24":{"start":{"line":42,"column":2},"end":{"line":42,"column":12}},"25":{"start":{"line":43,"column":2},"end":{"line":43,"column":11}},"26":{"start":{"line":46,"column":0},"end":{"line":65,"column":1}},"27":{"start":{"line":47,"column":2},"end":{"line":49,"column":68}},"28":{"start":{"line":49,"column":26},"end":{"line":49,"column":65}},"29":{"start":{"line":50,"column":2},"end":{"line":57,"column":4}},"30":{"start":{"line":51,"column":4},"end":{"line":55,"column":27}},"31":{"start":{"line":52,"column":6},"end":{"line":54,"column":43}},"32":{"start":{"line":56,"column":4},"end":{"line":56,"column":18}},"33":{"start":{"line":58,"column":2},"end":{"line":58,"column":23}},"34":{"start":{"line":59,"column":2},"end":{"line":59,"column":20}},"35":{"start":{"line":60,"column":2},"end":{"line":63,"column":3}},"36":{"start":{"line":61,"column":4},"end":{"line":61,"column":51}},"37":{"start":{"line":61,"column":35},"end":{"line":61,"column":51}},"38":{"start":{"line":62,"column":4},"end":{"line":62,"column":52}},"39":{"start":{"line":62,"column":30},"end":{"line":62,"column":50}},"40":{"start":{"line":64,"column":2},"end":{"line":64,"column":14}},"41":{"start":{"line":67,"column":0},"end":{"line":73,"column":1}},"42":{"start":{"line":68,"column":2},"end":{"line":68,"column":24}},"43":{"start":{"line":69,"column":7},"end":{"line":73,"column":1}},"44":{"start":{"line":70,"column":2},"end":{"line":70,"column":38}},"45":{"start":{"line":70,"column":22},"end":{"line":70,"column":34}},"46":{"start":{"line":72,"column":2},"end":{"line":72,"column":21}}},"branchMap":{"1":{"line":23,"type":"if","locations":[{"start":{"line":23,"column":2},"end":{"line":23,"column":2}},{"start":{"line":23,"column":2},"end":{"line":23,"column":2}}]},"2":{"line":48,"type":"binary-expr","locations":[{"start":{"line":48,"column":14},"end":{"line":48,"column":18}},{"start":{"line":48,"column":22},"end":{"line":48,"column":32}}]},"3":{"line":60,"type":"if","locations":[{"start":{"line":60,"column":2},"end":{"line":60,"column":2}},{"start":{"line":60,"column":2},"end":{"line":60,"column":2}}]},"4":{"line":61,"type":"if","locations":[{"start":{"line":61,"column":4},"end":{"line":61,"column":4}},{"start":{"line":61,"column":4},"end":{"line":61,"column":4}}]},"5":{"line":67,"type":"if","locations":[{"start":{"line":67,"column":0},"end":{"line":67,"column":0}},{"start":{"line":67,"column":0},"end":{"line":67,"column":0}}]},"6":{"line":67,"type":"binary-expr","locations":[{"start":{"line":67,"column":4},"end":{"line":67,"column":10}},{"start":{"line":67,"column":14},"end":{"line":67,"column":28}}]},"7":{"line":69,"type":"if","locations":[{"start":{"line":69,"column":7},"end":{"line":69,"column":7}},{"start":{"line":69,"column":7},"end":{"line":69,"column":7}}]},"8":{"line":69,"type":"binary-expr","locations":[{"start":{"line":69,"column":11},"end":{"line":69,"column":17}},{"start":{"line":69,"column":21},"end":{"line":69,"column":31}}]},"9":{"line":77,"type":"binary-expr","locations":[{"start":{"line":77,"column":2},"end":{"line":77,"column":29}},{"start":{"line":77,"column":33},"end":{"line":77,"column":39}}]},"10":{"line":78,"type":"binary-expr","locations":[{"start":{"line":78,"column":2},"end":{"line":78,"column":31}},{"start":{"line":78,"column":35},"end":{"line":78,"column":41}}]}}},"/home/davidbau/git/seedrandom/lib/xorwow.js":{"path":"/home/davidbau/git/seedrandom/lib/xorwow.js","s":{"1":1,"2":1,"3":3,"4":3,"5":4105327,"6":4105327,"7":4105327,"8":4105327,"9":4105327,"10":4105327,"11":3,"12":3,"13":3,"14":3,"15":3,"16":3,"17":2,"18":1,"19":3,"20":198,"21":198,"22":3,"23":198,"24":1,"25":2,"26":2,"27":2,"28":2,"29":2,"30":2,"31":2,"32":1,"33":3,"34":4102054,"35":3,"36":1025,"37":1025,"38":1025,"39":3,"40":3,"41":3,"42":2,"43":1,"44":2,"45":1,"46":3,"47":1,"48":1,"49":0,"50":0,"51":0,"52":0},"b":{"1":[2,1],"2":[3,195],"3":[3,2],"4":[2,1],"5":[1,1],"6":[1,0],"7":[1,1],"8":[0,0],"9":[0,0],"10":[1,1],"11":[1,0]},"f":{"1":1,"2":3,"3":4105327,"4":2,"5":3,"6":4102054,"7":1025,"8":1,"9":0},"fnMap":{"1":{"name":"(anonymous_1)","line":4,"loc":{"start":{"line":4,"column":1},"end":{"line":4,"column":34}}},"2":{"name":"XorGen","line":6,"loc":{"start":{"line":6,"column":0},"end":{"line":6,"column":22}}},"3":{"name":"(anonymous_3)","line":10,"loc":{"start":{"line":10,"column":12},"end":{"line":10,"column":23}}},"4":{"name":"copy","line":41,"loc":{"start":{"line":41,"column":0},"end":{"line":41,"column":20}}},"5":{"name":"impl","line":51,"loc":{"start":{"line":51,"column":0},"end":{"line":51,"column":26}}},"6":{"name":"(anonymous_6)","line":54,"loc":{"start":{"line":54,"column":13},"end":{"line":54,"column":24}}},"7":{"name":"(anonymous_7)","line":55,"loc":{"start":{"line":55,"column":16},"end":{"line":55,"column":27}}},"8":{"name":"(anonymous_8)","line":67,"loc":{"start":{"line":67,"column":17},"end":{"line":67,"column":28}}},"9":{"name":"(anonymous_9)","line":75,"loc":{"start":{"line":75,"column":9},"end":{"line":75,"column":20}}}},"statementMap":{"1":{"start":{"line":4,"column":0},"end":{"line":84,"column":2}},"2":{"start":{"line":6,"column":0},"end":{"line":39,"column":1}},"3":{"start":{"line":7,"column":2},"end":{"line":7,"column":30}},"4":{"start":{"line":10,"column":2},"end":{"line":15,"column":4}},"5":{"start":{"line":11,"column":4},"end":{"line":11,"column":34}},"6":{"start":{"line":12,"column":4},"end":{"line":12,"column":16}},"7":{"start":{"line":12,"column":17},"end":{"line":12,"column":29}},"8":{"start":{"line":12,"column":30},"end":{"line":12,"column":42}},"9":{"start":{"line":12,"column":43},"end":{"line":12,"column":55}},"10":{"start":{"line":13,"column":4},"end":{"line":14,"column":58}},"11":{"start":{"line":17,"column":2},"end":{"line":17,"column":11}},"12":{"start":{"line":18,"column":2},"end":{"line":18,"column":11}},"13":{"start":{"line":19,"column":2},"end":{"line":19,"column":11}},"14":{"start":{"line":20,"column":2},"end":{"line":20,"column":11}},"15":{"start":{"line":21,"column":2},"end":{"line":21,"column":11}},"16":{"start":{"line":23,"column":2},"end":{"line":29,"column":3}},"17":{"start":{"line":25,"column":4},"end":{"line":25,"column":16}},"18":{"start":{"line":28,"column":4},"end":{"line":28,"column":20}},"19":{"start":{"line":32,"column":2},"end":{"line":38,"column":3}},"20":{"start":{"line":33,"column":4},"end":{"line":33,"column":38}},"21":{"start":{"line":34,"column":4},"end":{"line":36,"column":5}},"22":{"start":{"line":35,"column":6},"end":{"line":35,"column":37}},"23":{"start":{"line":37,"column":4},"end":{"line":37,"column":14}},"24":{"start":{"line":41,"column":0},"end":{"line":49,"column":1}},"25":{"start":{"line":42,"column":2},"end":{"line":42,"column":12}},"26":{"start":{"line":43,"column":2},"end":{"line":43,"column":12}},"27":{"start":{"line":44,"column":2},"end":{"line":44,"column":12}},"28":{"start":{"line":45,"column":2},"end":{"line":45,"column":12}},"29":{"start":{"line":46,"column":2},"end":{"line":46,"column":12}},"30":{"start":{"line":47,"column":2},"end":{"line":47,"column":12}},"31":{"start":{"line":48,"column":2},"end":{"line":48,"column":11}},"32":{"start":{"line":51,"column":0},"end":{"line":70,"column":1}},"33":{"start":{"line":52,"column":2},"end":{"line":54,"column":68}},"34":{"start":{"line":54,"column":26},"end":{"line":54,"column":65}},"35":{"start":{"line":55,"column":2},"end":{"line":62,"column":4}},"36":{"start":{"line":56,"column":4},"end":{"line":60,"column":27}},"37":{"start":{"line":57,"column":6},"end":{"line":59,"column":43}},"38":{"start":{"line":61,"column":4},"end":{"line":61,"column":18}},"39":{"start":{"line":63,"column":2},"end":{"line":63,"column":23}},"40":{"start":{"line":64,"column":2},"end":{"line":64,"column":20}},"41":{"start":{"line":65,"column":2},"end":{"line":68,"column":3}},"42":{"start":{"line":66,"column":4},"end":{"line":66,"column":51}},"43":{"start":{"line":66,"column":35},"end":{"line":66,"column":51}},"44":{"start":{"line":67,"column":4},"end":{"line":67,"column":52}},"45":{"start":{"line":67,"column":30},"end":{"line":67,"column":50}},"46":{"start":{"line":69,"column":2},"end":{"line":69,"column":14}},"47":{"start":{"line":72,"column":0},"end":{"line":78,"column":1}},"48":{"start":{"line":73,"column":2},"end":{"line":73,"column":24}},"49":{"start":{"line":74,"column":7},"end":{"line":78,"column":1}},"50":{"start":{"line":75,"column":2},"end":{"line":75,"column":38}},"51":{"start":{"line":75,"column":22},"end":{"line":75,"column":34}},"52":{"start":{"line":77,"column":2},"end":{"line":77,"column":21}}},"branchMap":{"1":{"line":23,"type":"if","locations":[{"start":{"line":23,"column":2},"end":{"line":23,"column":2}},{"start":{"line":23,"column":2},"end":{"line":23,"column":2}}]},"2":{"line":34,"type":"if","locations":[{"start":{"line":34,"column":4},"end":{"line":34,"column":4}},{"start":{"line":34,"column":4},"end":{"line":34,"column":4}}]},"3":{"line":53,"type":"binary-expr","locations":[{"start":{"line":53,"column":14},"end":{"line":53,"column":18}},{"start":{"line":53,"column":22},"end":{"line":53,"column":32}}]},"4":{"line":65,"type":"if","locations":[{"start":{"line":65,"column":2},"end":{"line":65,"column":2}},{"start":{"line":65,"column":2},"end":{"line":65,"column":2}}]},"5":{"line":66,"type":"if","locations":[{"start":{"line":66,"column":4},"end":{"line":66,"column":4}},{"start":{"line":66,"column":4},"end":{"line":66,"column":4}}]},"6":{"line":72,"type":"if","locations":[{"start":{"line":72,"column":0},"end":{"line":72,"column":0}},{"start":{"line":72,"column":0},"end":{"line":72,"column":0}}]},"7":{"line":72,"type":"binary-expr","locations":[{"start":{"line":72,"column":4},"end":{"line":72,"column":10}},{"start":{"line":72,"column":14},"end":{"line":72,"column":28}}]},"8":{"line":74,"type":"if","locations":[{"start":{"line":74,"column":7},"end":{"line":74,"column":7}},{"start":{"line":74,"column":7},"end":{"line":74,"column":7}}]},"9":{"line":74,"type":"binary-expr","locations":[{"start":{"line":74,"column":11},"end":{"line":74,"column":17}},{"start":{"line":74,"column":21},"end":{"line":74,"column":31}}]},"10":{"line":82,"type":"binary-expr","locations":[{"start":{"line":82,"column":2},"end":{"line":82,"column":29}},{"start":{"line":82,"column":33},"end":{"line":82,"column":39}}]},"11":{"line":83,"type":"binary-expr","locations":[{"start":{"line":83,"column":2},"end":{"line":83,"column":31}},{"start":{"line":83,"column":35},"end":{"line":83,"column":41}}]}}},"/home/davidbau/git/seedrandom/lib/xorshift7.js":{"path":"/home/davidbau/git/seedrandom/lib/xorshift7.js","s":{"1":1,"2":1,"3":3,"4":3,"5":4105897,"6":4105897,"7":4105897,"8":4105897,"9":4105897,"10":4105897,"11":4105897,"12":4105897,"13":4105897,"14":4105897,"15":4105897,"16":4105897,"17":4105897,"18":4105897,"19":4105897,"20":4105897,"21":1,"22":3,"23":3,"24":2,"25":1,"26":1,"27":6,"28":3,"29":16,"30":3,"31":3,"32":2,"33":1,"34":3,"35":3,"36":3,"37":768,"38":3,"39":1,"40":2,"41":2,"42":2,"43":1,"44":3,"45":0,"46":3,"47":4102054,"48":3,"49":1025,"50":1025,"51":1025,"52":3,"53":3,"54":3,"55":2,"56":1,"57":2,"58":1,"59":3,"60":1,"61":1,"62":0,"63":0,"64":0,"65":0},"b":{"1":[2,1],"2":[19,17],"3":[2,1],"4":[0,3],"5":[3,2],"6":[2,1],"7":[1,1],"8":[1,0],"9":[1,1],"10":[0,0],"11":[0,0],"12":[1,1],"13":[1,0]},"f":{"1":1,"2":3,"3":4105897,"4":3,"5":2,"6":3,"7":4102054,"8":1025,"9":1,"10":0},"fnMap":{"1":{"name":"(anonymous_1)","line":6,"loc":{"start":{"line":6,"column":1},"end":{"line":6,"column":34}}},"2":{"name":"XorGen","line":8,"loc":{"start":{"line":8,"column":0},"end":{"line":8,"column":22}}},"3":{"name":"(anonymous_3)","line":12,"loc":{"start":{"line":12,"column":12},"end":{"line":12,"column":23}}},"4":{"name":"init","line":25,"loc":{"start":{"line":25,"column":2},"end":{"line":25,"column":26}}},"5":{"name":"copy","line":56,"loc":{"start":{"line":56,"column":0},"end":{"line":56,"column":20}}},"6":{"name":"impl","line":62,"loc":{"start":{"line":62,"column":0},"end":{"line":62,"column":26}}},"7":{"name":"(anonymous_7)","line":66,"loc":{"start":{"line":66,"column":13},"end":{"line":66,"column":24}}},"8":{"name":"(anonymous_8)","line":67,"loc":{"start":{"line":67,"column":16},"end":{"line":67,"column":27}}},"9":{"name":"(anonymous_9)","line":79,"loc":{"start":{"line":79,"column":17},"end":{"line":79,"column":28}}},"10":{"name":"(anonymous_10)","line":87,"loc":{"start":{"line":87,"column":9},"end":{"line":87,"column":20}}}},"statementMap":{"1":{"start":{"line":6,"column":0},"end":{"line":96,"column":2}},"2":{"start":{"line":8,"column":0},"end":{"line":54,"column":1}},"3":{"start":{"line":9,"column":2},"end":{"line":9,"column":16}},"4":{"start":{"line":12,"column":2},"end":{"line":23,"column":4}},"5":{"start":{"line":14,"column":4},"end":{"line":14,"column":36}},"6":{"start":{"line":15,"column":4},"end":{"line":15,"column":13}},"7":{"start":{"line":15,"column":14},"end":{"line":15,"column":29}},"8":{"start":{"line":15,"column":30},"end":{"line":15,"column":48}},"9":{"start":{"line":16,"column":4},"end":{"line":16,"column":23}},"10":{"start":{"line":16,"column":24},"end":{"line":16,"column":44}},"11":{"start":{"line":17,"column":4},"end":{"line":17,"column":23}},"12":{"start":{"line":17,"column":24},"end":{"line":17,"column":43}},"13":{"start":{"line":18,"column":4},"end":{"line":18,"column":23}},"14":{"start":{"line":18,"column":24},"end":{"line":18,"column":42}},"15":{"start":{"line":19,"column":4},"end":{"line":19,"column":23}},"16":{"start":{"line":19,"column":24},"end":{"line":19,"column":42}},"17":{"start":{"line":19,"column":43},"end":{"line":19,"column":61}},"18":{"start":{"line":20,"column":4},"end":{"line":20,"column":13}},"19":{"start":{"line":21,"column":4},"end":{"line":21,"column":23}},"20":{"start":{"line":22,"column":4},"end":{"line":22,"column":13}},"21":{"start":{"line":25,"column":2},"end":{"line":51,"column":3}},"22":{"start":{"line":26,"column":4},"end":{"line":26,"column":21}},"23":{"start":{"line":28,"column":4},"end":{"line":38,"column":5}},"24":{"start":{"line":30,"column":6},"end":{"line":30,"column":22}},"25":{"start":{"line":33,"column":6},"end":{"line":33,"column":23}},"26":{"start":{"line":34,"column":6},"end":{"line":37,"column":7}},"27":{"start":{"line":35,"column":8},"end":{"line":36,"column":56}},"28":{"start":{"line":40,"column":4},"end":{"line":40,"column":35}},"29":{"start":{"line":40,"column":25},"end":{"line":40,"column":35}},"30":{"start":{"line":41,"column":4},"end":{"line":41,"column":42}},"31":{"start":{"line":42,"column":4},"end":{"line":42,"column":45}},"32":{"start":{"line":42,"column":16},"end":{"line":42,"column":30}},"33":{"start":{"line":42,"column":36},"end":{"line":42,"column":45}},"34":{"start":{"line":44,"column":4},"end":{"line":44,"column":13}},"35":{"start":{"line":45,"column":4},"end":{"line":45,"column":13}},"36":{"start":{"line":48,"column":4},"end":{"line":50,"column":5}},"37":{"start":{"line":49,"column":6},"end":{"line":49,"column":16}},"38":{"start":{"line":53,"column":2},"end":{"line":53,"column":17}},"39":{"start":{"line":56,"column":0},"end":{"line":60,"column":1}},"40":{"start":{"line":57,"column":2},"end":{"line":57,"column":20}},"41":{"start":{"line":58,"column":2},"end":{"line":58,"column":12}},"42":{"start":{"line":59,"column":2},"end":{"line":59,"column":11}},"43":{"start":{"line":62,"column":0},"end":{"line":82,"column":1}},"44":{"start":{"line":63,"column":2},"end":{"line":63,"column":39}},"45":{"start":{"line":63,"column":20},"end":{"line":63,"column":39}},"46":{"start":{"line":64,"column":2},"end":{"line":66,"column":68}},"47":{"start":{"line":66,"column":26},"end":{"line":66,"column":65}},"48":{"start":{"line":67,"column":2},"end":{"line":74,"column":4}},"49":{"start":{"line":68,"column":4},"end":{"line":72,"column":27}},"50":{"start":{"line":69,"column":6},"end":{"line":71,"column":43}},"51":{"start":{"line":73,"column":4},"end":{"line":73,"column":18}},"52":{"start":{"line":75,"column":2},"end":{"line":75,"column":23}},"53":{"start":{"line":76,"column":2},"end":{"line":76,"column":20}},"54":{"start":{"line":77,"column":2},"end":{"line":80,"column":3}},"55":{"start":{"line":78,"column":4},"end":{"line":78,"column":33}},"56":{"start":{"line":78,"column":17},"end":{"line":78,"column":33}},"57":{"start":{"line":79,"column":4},"end":{"line":79,"column":52}},"58":{"start":{"line":79,"column":30},"end":{"line":79,"column":50}},"59":{"start":{"line":81,"column":2},"end":{"line":81,"column":14}},"60":{"start":{"line":84,"column":0},"end":{"line":90,"column":1}},"61":{"start":{"line":85,"column":2},"end":{"line":85,"column":24}},"62":{"start":{"line":86,"column":7},"end":{"line":90,"column":1}},"63":{"start":{"line":87,"column":2},"end":{"line":87,"column":38}},"64":{"start":{"line":87,"column":22},"end":{"line":87,"column":34}},"65":{"start":{"line":89,"column":2},"end":{"line":89,"column":24}}},"branchMap":{"1":{"line":28,"type":"if","locations":[{"start":{"line":28,"column":4},"end":{"line":28,"column":4}},{"start":{"line":28,"column":4},"end":{"line":28,"column":4}}]},"2":{"line":41,"type":"binary-expr","locations":[{"start":{"line":41,"column":16},"end":{"line":41,"column":21}},{"start":{"line":41,"column":25},"end":{"line":41,"column":35}}]},"3":{"line":42,"type":"if","locations":[{"start":{"line":42,"column":4},"end":{"line":42,"column":4}},{"start":{"line":42,"column":4},"end":{"line":42,"column":4}}]},"4":{"line":63,"type":"if","locations":[{"start":{"line":63,"column":2},"end":{"line":63,"column":2}},{"start":{"line":63,"column":2},"end":{"line":63,"column":2}}]},"5":{"line":65,"type":"binary-expr","locations":[{"start":{"line":65,"column":14},"end":{"line":65,"column":18}},{"start":{"line":65,"column":22},"end":{"line":65,"column":32}}]},"6":{"line":77,"type":"if","locations":[{"start":{"line":77,"column":2},"end":{"line":77,"column":2}},{"start":{"line":77,"column":2},"end":{"line":77,"column":2}}]},"7":{"line":78,"type":"if","locations":[{"start":{"line":78,"column":4},"end":{"line":78,"column":4}},{"start":{"line":78,"column":4},"end":{"line":78,"column":4}}]},"8":{"line":84,"type":"if","locations":[{"start":{"line":84,"column":0},"end":{"line":84,"column":0}},{"start":{"line":84,"column":0},"end":{"line":84,"column":0}}]},"9":{"line":84,"type":"binary-expr","locations":[{"start":{"line":84,"column":4},"end":{"line":84,"column":10}},{"start":{"line":84,"column":14},"end":{"line":84,"column":28}}]},"10":{"line":86,"type":"if","locations":[{"start":{"line":86,"column":7},"end":{"line":86,"column":7}},{"start":{"line":86,"column":7},"end":{"line":86,"column":7}}]},"11":{"line":86,"type":"binary-expr","locations":[{"start":{"line":86,"column":11},"end":{"line":86,"column":17}},{"start":{"line":86,"column":21},"end":{"line":86,"column":31}}]},"12":{"line":94,"type":"binary-expr","locations":[{"start":{"line":94,"column":2},"end":{"line":94,"column":29}},{"start":{"line":94,"column":33},"end":{"line":94,"column":39}}]},"13":{"line":95,"type":"binary-expr","locations":[{"start":{"line":95,"column":2},"end":{"line":95,"column":31}},{"start":{"line":95,"column":35},"end":{"line":95,"column":41}}]}}},"/home/davidbau/git/seedrandom/lib/xor4096.js":{"path":"/home/davidbau/git/seedrandom/lib/xor4096.js","s":{"1":1,"2":1,"3":3,"4":3,"5":4105129,"6":4105129,"7":4105129,"8":4105129,"9":4105129,"10":4105129,"11":4105129,"12":4105129,"13":4105129,"14":4105129,"15":4105129,"16":1,"17":3,"18":3,"19":2,"20":2,"21":1,"22":1,"23":1,"24":3,"25":480,"26":160,"27":480,"28":3,"29":480,"30":480,"31":480,"32":480,"33":480,"34":384,"35":384,"36":384,"37":3,"38":0,"39":3,"40":3,"41":1536,"42":1536,"43":1536,"44":1536,"45":1536,"46":1536,"47":1536,"48":3,"49":3,"50":3,"51":3,"52":1,"53":2,"54":2,"55":2,"56":2,"57":1,"58":3,"59":0,"60":3,"61":4102054,"62":3,"63":1025,"64":1025,"65":1025,"66":3,"67":3,"68":3,"69":2,"70":1,"71":2,"72":1,"73":3,"74":1,"75":1,"76":0,"77":0,"78":0,"79":0},"b":{"1":[2,1],"2":[160,320],"3":[3,477],"4":[384,96],"5":[0,384],"6":[0,3],"7":[0,0,0],"8":[0,3],"9":[3,2],"10":[2,1],"11":[1,1],"12":[1,0],"13":[1,1],"14":[0,0],"15":[0,0],"16":[1,1],"17":[1,0]},"f":{"1":1,"2":3,"3":4105129,"4":3,"5":2,"6":3,"7":4102054,"8":1025,"9":1,"10":0},"fnMap":{"1":{"name":"(anonymous_1)","line":26,"loc":{"start":{"line":26,"column":1},"end":{"line":26,"column":34}}},"2":{"name":"XorGen","line":28,"loc":{"start":{"line":28,"column":0},"end":{"line":28,"column":22}}},"3":{"name":"(anonymous_3)","line":32,"loc":{"start":{"line":32,"column":12},"end":{"line":32,"column":23}}},"4":{"name":"init","line":51,"loc":{"start":{"line":51,"column":2},"end":{"line":51,"column":26}}},"5":{"name":"copy","line":105,"loc":{"start":{"line":105,"column":0},"end":{"line":105,"column":20}}},"6":{"name":"impl","line":112,"loc":{"start":{"line":112,"column":0},"end":{"line":112,"column":26}}},"7":{"name":"(anonymous_7)","line":116,"loc":{"start":{"line":116,"column":13},"end":{"line":116,"column":24}}},"8":{"name":"(anonymous_8)","line":117,"loc":{"start":{"line":117,"column":16},"end":{"line":117,"column":27}}},"9":{"name":"(anonymous_9)","line":129,"loc":{"start":{"line":129,"column":17},"end":{"line":129,"column":28}}},"10":{"name":"(anonymous_10)","line":137,"loc":{"start":{"line":137,"column":9},"end":{"line":137,"column":20}}}},"statementMap":{"1":{"start":{"line":26,"column":0},"end":{"line":146,"column":2}},"2":{"start":{"line":28,"column":0},"end":{"line":103,"column":1}},"3":{"start":{"line":29,"column":2},"end":{"line":29,"column":16}},"4":{"start":{"line":32,"column":2},"end":{"line":49,"column":4}},"5":{"start":{"line":33,"column":4},"end":{"line":34,"column":33}},"6":{"start":{"line":36,"column":4},"end":{"line":36,"column":36}},"7":{"start":{"line":38,"column":4},"end":{"line":38,"column":26}},"8":{"start":{"line":39,"column":4},"end":{"line":39,"column":31}},"9":{"start":{"line":40,"column":4},"end":{"line":40,"column":17}},"10":{"start":{"line":41,"column":4},"end":{"line":41,"column":17}},"11":{"start":{"line":42,"column":4},"end":{"line":42,"column":18}},"12":{"start":{"line":43,"column":4},"end":{"line":43,"column":18}},"13":{"start":{"line":45,"column":4},"end":{"line":45,"column":21}},"14":{"start":{"line":46,"column":4},"end":{"line":46,"column":13}},"15":{"start":{"line":48,"column":4},"end":{"line":48,"column":38}},"16":{"start":{"line":51,"column":2},"end":{"line":100,"column":3}},"17":{"start":{"line":52,"column":4},"end":{"line":52,"column":43}},"18":{"start":{"line":53,"column":4},"end":{"line":62,"column":5}},"19":{"start":{"line":55,"column":6},"end":{"line":55,"column":15}},"20":{"start":{"line":56,"column":6},"end":{"line":56,"column":18}},"21":{"start":{"line":59,"column":6},"end":{"line":59,"column":25}},"22":{"start":{"line":60,"column":6},"end":{"line":60,"column":12}},"23":{"start":{"line":61,"column":6},"end":{"line":61,"column":43}},"24":{"start":{"line":64,"column":4},"end":{"line":78,"column":5}},"25":{"start":{"line":66,"column":6},"end":{"line":66,"column":61}},"26":{"start":{"line":66,"column":16},"end":{"line":66,"column":61}},"27":{"start":{"line":68,"column":6},"end":{"line":68,"column":25}},"28":{"start":{"line":68,"column":19},"end":{"line":68,"column":25}},"29":{"start":{"line":69,"column":6},"end":{"line":69,"column":19}},"30":{"start":{"line":70,"column":6},"end":{"line":70,"column":20}},"31":{"start":{"line":71,"column":6},"end":{"line":71,"column":18}},"32":{"start":{"line":72,"column":6},"end":{"line":72,"column":20}},"33":{"start":{"line":73,"column":6},"end":{"line":77,"column":7}},"34":{"start":{"line":74,"column":8},"end":{"line":74,"column":33}},"35":{"start":{"line":75,"column":8},"end":{"line":75,"column":36}},"36":{"start":{"line":76,"column":8},"end":{"line":76,"column":33}},"37":{"start":{"line":80,"column":4},"end":{"line":82,"column":5}},"38":{"start":{"line":81,"column":6},"end":{"line":81,"column":47}},"39":{"start":{"line":86,"column":4},"end":{"line":86,"column":12}},"40":{"start":{"line":87,"column":4},"end":{"line":95,"column":5}},"41":{"start":{"line":88,"column":6},"end":{"line":88,"column":28}},"42":{"start":{"line":89,"column":6},"end":{"line":89,"column":33}},"43":{"start":{"line":90,"column":6},"end":{"line":90,"column":19}},"44":{"start":{"line":91,"column":6},"end":{"line":91,"column":19}},"45":{"start":{"line":92,"column":6},"end":{"line":92,"column":20}},"46":{"start":{"line":93,"column":6},"end":{"line":93,"column":20}},"47":{"start":{"line":94,"column":6},"end":{"line":94,"column":19}},"48":{"start":{"line":97,"column":4},"end":{"line":97,"column":13}},"49":{"start":{"line":98,"column":4},"end":{"line":98,"column":13}},"50":{"start":{"line":99,"column":4},"end":{"line":99,"column":13}},"51":{"start":{"line":102,"column":2},"end":{"line":102,"column":17}},"52":{"start":{"line":105,"column":0},"end":{"line":110,"column":1}},"53":{"start":{"line":106,"column":2},"end":{"line":106,"column":12}},"54":{"start":{"line":107,"column":2},"end":{"line":107,"column":12}},"55":{"start":{"line":108,"column":2},"end":{"line":108,"column":20}},"56":{"start":{"line":109,"column":2},"end":{"line":109,"column":11}},"57":{"start":{"line":112,"column":0},"end":{"line":132,"column":1}},"58":{"start":{"line":113,"column":2},"end":{"line":113,"column":39}},"59":{"start":{"line":113,"column":20},"end":{"line":113,"column":39}},"60":{"start":{"line":114,"column":2},"end":{"line":116,"column":68}},"61":{"start":{"line":116,"column":26},"end":{"line":116,"column":65}},"62":{"start":{"line":117,"column":2},"end":{"line":124,"column":4}},"63":{"start":{"line":118,"column":4},"end":{"line":122,"column":27}},"64":{"start":{"line":119,"column":6},"end":{"line":121,"column":43}},"65":{"start":{"line":123,"column":4},"end":{"line":123,"column":18}},"66":{"start":{"line":125,"column":2},"end":{"line":125,"column":23}},"67":{"start":{"line":126,"column":2},"end":{"line":126,"column":20}},"68":{"start":{"line":127,"column":2},"end":{"line":130,"column":3}},"69":{"start":{"line":128,"column":4},"end":{"line":128,"column":33}},"70":{"start":{"line":128,"column":17},"end":{"line":128,"column":33}},"71":{"start":{"line":129,"column":4},"end":{"line":129,"column":52}},"72":{"start":{"line":129,"column":30},"end":{"line":129,"column":50}},"73":{"start":{"line":131,"column":2},"end":{"line":131,"column":14}},"74":{"start":{"line":134,"column":0},"end":{"line":140,"column":1}},"75":{"start":{"line":135,"column":2},"end":{"line":135,"column":24}},"76":{"start":{"line":136,"column":7},"end":{"line":140,"column":1}},"77":{"start":{"line":137,"column":2},"end":{"line":137,"column":38}},"78":{"start":{"line":137,"column":22},"end":{"line":137,"column":34}},"79":{"start":{"line":139,"column":2},"end":{"line":139,"column":22}}},"branchMap":{"1":{"line":53,"type":"if","locations":[{"start":{"line":53,"column":4},"end":{"line":53,"column":4}},{"start":{"line":53,"column":4},"end":{"line":53,"column":4}}]},"2":{"line":66,"type":"if","locations":[{"start":{"line":66,"column":6},"end":{"line":66,"column":6}},{"start":{"line":66,"column":6},"end":{"line":66,"column":6}}]},"3":{"line":68,"type":"if","locations":[{"start":{"line":68,"column":6},"end":{"line":68,"column":6}},{"start":{"line":68,"column":6},"end":{"line":68,"column":6}}]},"4":{"line":73,"type":"if","locations":[{"start":{"line":73,"column":6},"end":{"line":73,"column":6}},{"start":{"line":73,"column":6},"end":{"line":73,"column":6}}]},"5":{"line":76,"type":"cond-expr","locations":[{"start":{"line":76,"column":23},"end":{"line":76,"column":28}},{"start":{"line":76,"column":31},"end":{"line":76,"column":32}}]},"6":{"line":80,"type":"if","locations":[{"start":{"line":80,"column":4},"end":{"line":80,"column":4}},{"start":{"line":80,"column":4},"end":{"line":80,"column":4}}]},"7":{"line":81,"type":"binary-expr","locations":[{"start":{"line":81,"column":9},"end":{"line":81,"column":13}},{"start":{"line":81,"column":17},"end":{"line":81,"column":28}},{"start":{"line":81,"column":32},"end":{"line":81,"column":33}}]},"8":{"line":113,"type":"if","locations":[{"start":{"line":113,"column":2},"end":{"line":113,"column":2}},{"start":{"line":113,"column":2},"end":{"line":113,"column":2}}]},"9":{"line":115,"type":"binary-expr","locations":[{"start":{"line":115,"column":14},"end":{"line":115,"column":18}},{"start":{"line":115,"column":22},"end":{"line":115,"column":32}}]},"10":{"line":127,"type":"if","locations":[{"start":{"line":127,"column":2},"end":{"line":127,"column":2}},{"start":{"line":127,"column":2},"end":{"line":127,"column":2}}]},"11":{"line":128,"type":"if","locations":[{"start":{"line":128,"column":4},"end":{"line":128,"column":4}},{"start":{"line":128,"column":4},"end":{"line":128,"column":4}}]},"12":{"line":134,"type":"if","locations":[{"start":{"line":134,"column":0},"end":{"line":134,"column":0}},{"start":{"line":134,"column":0},"end":{"line":134,"column":0}}]},"13":{"line":134,"type":"binary-expr","locations":[{"start":{"line":134,"column":4},"end":{"line":134,"column":10}},{"start":{"line":134,"column":14},"end":{"line":134,"column":28}}]},"14":{"line":136,"type":"if","locations":[{"start":{"line":136,"column":7},"end":{"line":136,"column":7}},{"start":{"line":136,"column":7},"end":{"line":136,"column":7}}]},"15":{"line":136,"type":"binary-expr","locations":[{"start":{"line":136,"column":11},"end":{"line":136,"column":17}},{"start":{"line":136,"column":21},"end":{"line":136,"column":31}}]},"16":{"line":144,"type":"binary-expr","locations":[{"start":{"line":144,"column":2},"end":{"line":144,"column":29}},{"start":{"line":144,"column":33},"end":{"line":144,"column":39}}]},"17":{"line":145,"type":"binary-expr","locations":[{"start":{"line":145,"column":2},"end":{"line":145,"column":31}},{"start":{"line":145,"column":35},"end":{"line":145,"column":41}}]}}},"/home/davidbau/git/seedrandom/lib/tychei.js":{"path":"/home/davidbau/git/seedrandom/lib/tychei.js","s":{"1":1,"2":1,"3":3,"4":3,"5":4105195,"6":4105195,"7":4105195,"8":4105195,"9":4105195,"10":4105195,"11":4105195,"12":4105195,"13":4105195,"14":3,"15":3,"16":3,"17":3,"18":3,"19":2,"20":2,"21":1,"22":3,"23":66,"24":66,"25":1,"26":2,"27":2,"28":2,"29":2,"30":2,"31":1,"32":3,"33":4102054,"34":3,"35":1025,"36":1025,"37":1025,"38":3,"39":3,"40":3,"41":2,"42":1,"43":2,"44":1,"45":3,"46":1,"47":1,"48":0,"49":0,"50":0,"51":0},"b":{"1":[2,1],"2":[3,2],"3":[2,1],"4":[1,1],"5":[1,0],"6":[1,1],"7":[0,0],"8":[0,0],"9":[1,1],"10":[1,0]},"f":{"1":1,"2":3,"3":4105195,"4":2,"5":3,"6":4102054,"7":1025,"8":1,"9":0},"fnMap":{"1":{"name":"(anonymous_1)","line":5,"loc":{"start":{"line":5,"column":1},"end":{"line":5,"column":34}}},"2":{"name":"XorGen","line":7,"loc":{"start":{"line":7,"column":0},"end":{"line":7,"column":22}}},"3":{"name":"(anonymous_3)","line":11,"loc":{"start":{"line":11,"column":12},"end":{"line":11,"column":23}}},"4":{"name":"copy","line":60,"loc":{"start":{"line":60,"column":0},"end":{"line":60,"column":20}}},"5":{"name":"impl","line":68,"loc":{"start":{"line":68,"column":0},"end":{"line":68,"column":26}}},"6":{"name":"(anonymous_6)","line":71,"loc":{"start":{"line":71,"column":13},"end":{"line":71,"column":24}}},"7":{"name":"(anonymous_7)","line":72,"loc":{"start":{"line":72,"column":16},"end":{"line":72,"column":27}}},"8":{"name":"(anonymous_8)","line":84,"loc":{"start":{"line":84,"column":17},"end":{"line":84,"column":28}}},"9":{"name":"(anonymous_9)","line":92,"loc":{"start":{"line":92,"column":9},"end":{"line":92,"column":20}}}},"statementMap":{"1":{"start":{"line":5,"column":0},"end":{"line":101,"column":2}},"2":{"start":{"line":7,"column":0},"end":{"line":58,"column":1}},"3":{"start":{"line":8,"column":2},"end":{"line":8,"column":30}},"4":{"start":{"line":11,"column":2},"end":{"line":21,"column":4}},"5":{"start":{"line":12,"column":4},"end":{"line":12,"column":47}},"6":{"start":{"line":13,"column":4},"end":{"line":13,"column":34}},"7":{"start":{"line":14,"column":4},"end":{"line":14,"column":20}},"8":{"start":{"line":15,"column":4},"end":{"line":15,"column":34}},"9":{"start":{"line":16,"column":4},"end":{"line":16,"column":20}},"10":{"start":{"line":17,"column":4},"end":{"line":17,"column":42}},"11":{"start":{"line":18,"column":4},"end":{"line":18,"column":27}},"12":{"start":{"line":19,"column":4},"end":{"line":19,"column":38}},"13":{"start":{"line":20,"column":4},"end":{"line":20,"column":30}},"14":{"start":{"line":39,"column":2},"end":{"line":39,"column":11}},"15":{"start":{"line":40,"column":2},"end":{"line":40,"column":11}},"16":{"start":{"line":41,"column":2},"end":{"line":41,"column":24}},"17":{"start":{"line":42,"column":2},"end":{"line":42,"column":20}},"18":{"start":{"line":44,"column":2},"end":{"line":51,"column":3}},"19":{"start":{"line":46,"column":4},"end":{"line":46,"column":36}},"20":{"start":{"line":47,"column":4},"end":{"line":47,"column":20}},"21":{"start":{"line":50,"column":4},"end":{"line":50,"column":20}},"22":{"start":{"line":54,"column":2},"end":{"line":57,"column":3}},"23":{"start":{"line":55,"column":4},"end":{"line":55,"column":38}},"24":{"start":{"line":56,"column":4},"end":{"line":56,"column":14}},"25":{"start":{"line":60,"column":0},"end":{"line":66,"column":1}},"26":{"start":{"line":61,"column":2},"end":{"line":61,"column":12}},"27":{"start":{"line":62,"column":2},"end":{"line":62,"column":12}},"28":{"start":{"line":63,"column":2},"end":{"line":63,"column":12}},"29":{"start":{"line":64,"column":2},"end":{"line":64,"column":12}},"30":{"start":{"line":65,"column":2},"end":{"line":65,"column":11}},"31":{"start":{"line":68,"column":0},"end":{"line":87,"column":1}},"32":{"start":{"line":69,"column":2},"end":{"line":71,"column":68}},"33":{"start":{"line":71,"column":26},"end":{"line":71,"column":65}},"34":{"start":{"line":72,"column":2},"end":{"line":79,"column":4}},"35":{"start":{"line":73,"column":4},"end":{"line":77,"column":27}},"36":{"start":{"line":74,"column":6},"end":{"line":76,"column":43}},"37":{"start":{"line":78,"column":4},"end":{"line":78,"column":18}},"38":{"start":{"line":80,"column":2},"end":{"line":80,"column":23}},"39":{"start":{"line":81,"column":2},"end":{"line":81,"column":20}},"40":{"start":{"line":82,"column":2},"end":{"line":85,"column":3}},"41":{"start":{"line":83,"column":4},"end":{"line":83,"column":51}},"42":{"start":{"line":83,"column":35},"end":{"line":83,"column":51}},"43":{"start":{"line":84,"column":4},"end":{"line":84,"column":52}},"44":{"start":{"line":84,"column":30},"end":{"line":84,"column":50}},"45":{"start":{"line":86,"column":2},"end":{"line":86,"column":14}},"46":{"start":{"line":89,"column":0},"end":{"line":95,"column":1}},"47":{"start":{"line":90,"column":2},"end":{"line":90,"column":24}},"48":{"start":{"line":91,"column":7},"end":{"line":95,"column":1}},"49":{"start":{"line":92,"column":2},"end":{"line":92,"column":38}},"50":{"start":{"line":92,"column":22},"end":{"line":92,"column":34}},"51":{"start":{"line":94,"column":2},"end":{"line":94,"column":21}}},"branchMap":{"1":{"line":44,"type":"if","locations":[{"start":{"line":44,"column":2},"end":{"line":44,"column":2}},{"start":{"line":44,"column":2},"end":{"line":44,"column":2}}]},"2":{"line":70,"type":"binary-expr","locations":[{"start":{"line":70,"column":14},"end":{"line":70,"column":18}},{"start":{"line":70,"column":22},"end":{"line":70,"column":32}}]},"3":{"line":82,"type":"if","locations":[{"start":{"line":82,"column":2},"end":{"line":82,"column":2}},{"start":{"line":82,"column":2},"end":{"line":82,"column":2}}]},"4":{"line":83,"type":"if","locations":[{"start":{"line":83,"column":4},"end":{"line":83,"column":4}},{"start":{"line":83,"column":4},"end":{"line":83,"column":4}}]},"5":{"line":89,"type":"if","locations":[{"start":{"line":89,"column":0},"end":{"line":89,"column":0}},{"start":{"line":89,"column":0},"end":{"line":89,"column":0}}]},"6":{"line":89,"type":"binary-expr","locations":[{"start":{"line":89,"column":4},"end":{"line":89,"column":10}},{"start":{"line":89,"column":14},"end":{"line":89,"column":28}}]},"7":{"line":91,"type":"if","locations":[{"start":{"line":91,"column":7},"end":{"line":91,"column":7}},{"start":{"line":91,"column":7},"end":{"line":91,"column":7}}]},"8":{"line":91,"type":"binary-expr","locations":[{"start":{"line":91,"column":11},"end":{"line":91,"column":17}},{"start":{"line":91,"column":21},"end":{"line":91,"column":31}}]},"9":{"line":99,"type":"binary-expr","locations":[{"start":{"line":99,"column":2},"end":{"line":99,"column":29}},{"start":{"line":99,"column":33},"end":{"line":99,"column":39}}]},"10":{"line":100,"type":"binary-expr","locations":[{"start":{"line":100,"column":2},"end":{"line":100,"column":31}},{"start":{"line":100,"column":35},"end":{"line":100,"column":41}}]}}},"/home/davidbau/git/seedrandom/lib/alea.js":{"path":"/home/davidbau/git/seedrandom/lib/alea.js","s":{"1":1,"2":1,"3":3,"4":3,"5":4105129,"6":4105129,"7":4105129,"8":4105129,"9":3,"10":3,"11":3,"12":3,"13":3,"14":3,"15":1,"16":3,"17":3,"18":3,"19":3,"20":3,"21":0,"22":3,"23":1,"24":2,"25":2,"26":2,"27":2,"28":2,"29":1,"30":3,"31":3,"32":1025,"33":3,"34":1025,"35":3,"36":3,"37":2,"38":1,"39":2,"40":1,"41":3,"42":1,"43":3,"44":3,"45":18,"46":18,"47":33,"48":33,"49":33,"50":33,"51":33,"52":33,"53":33,"54":33,"55":18,"56":3,"57":1,"58":1,"59":0,"60":0,"61":0,"62":0},"b":{"1":[1,2],"2":[3,0],"3":[0,3],"4":[3,2],"5":[2,1],"6":[1,1],"7":[1,0],"8":[1,1],"9":[0,0],"10":[0,0],"11":[1,1],"12":[1,0]},"f":{"1":1,"2":3,"3":4105129,"4":2,"5":3,"6":1025,"7":1025,"8":1,"9":3,"10":18,"11":0},"fnMap":{"1":{"name":"(anonymous_1)","line":28,"loc":{"start":{"line":28,"column":1},"end":{"line":28,"column":34}}},"2":{"name":"Alea","line":30,"loc":{"start":{"line":30,"column":0},"end":{"line":30,"column":20}}},"3":{"name":"(anonymous_3)","line":33,"loc":{"start":{"line":33,"column":12},"end":{"line":33,"column":23}}},"4":{"name":"copy","line":54,"loc":{"start":{"line":54,"column":0},"end":{"line":54,"column":20}}},"5":{"name":"impl","line":62,"loc":{"start":{"line":62,"column":0},"end":{"line":62,"column":26}}},"6":{"name":"(anonymous_6)","line":66,"loc":{"start":{"line":66,"column":15},"end":{"line":66,"column":26}}},"7":{"name":"(anonymous_7)","line":67,"loc":{"start":{"line":67,"column":16},"end":{"line":67,"column":27}}},"8":{"name":"(anonymous_8)","line":73,"loc":{"start":{"line":73,"column":17},"end":{"line":73,"column":28}}},"9":{"name":"Mash","line":78,"loc":{"start":{"line":78,"column":0},"end":{"line":78,"column":16}}},"10":{"name":"(anonymous_10)","line":81,"loc":{"start":{"line":81,"column":13},"end":{"line":81,"column":28}}},"11":{"name":"(anonymous_11)","line":103,"loc":{"start":{"line":103,"column":9},"end":{"line":103,"column":20}}}},"statementMap":{"1":{"start":{"line":28,"column":0},"end":{"line":112,"column":2}},"2":{"start":{"line":30,"column":0},"end":{"line":52,"column":1}},"3":{"start":{"line":31,"column":2},"end":{"line":31,"column":31}},"4":{"start":{"line":33,"column":2},"end":{"line":38,"column":4}},"5":{"start":{"line":34,"column":4},"end":{"line":34,"column":60}},"6":{"start":{"line":35,"column":4},"end":{"line":35,"column":18}},"7":{"start":{"line":36,"column":4},"end":{"line":36,"column":18}},"8":{"start":{"line":37,"column":4},"end":{"line":37,"column":38}},"9":{"start":{"line":41,"column":2},"end":{"line":41,"column":11}},"10":{"start":{"line":42,"column":2},"end":{"line":42,"column":20}},"11":{"start":{"line":43,"column":2},"end":{"line":43,"column":20}},"12":{"start":{"line":44,"column":2},"end":{"line":44,"column":20}},"13":{"start":{"line":45,"column":2},"end":{"line":45,"column":22}},"14":{"start":{"line":46,"column":2},"end":{"line":46,"column":32}},"15":{"start":{"line":46,"column":19},"end":{"line":46,"column":30}},"16":{"start":{"line":47,"column":2},"end":{"line":47,"column":22}},"17":{"start":{"line":48,"column":2},"end":{"line":48,"column":32}},"18":{"start":{"line":48,"column":19},"end":{"line":48,"column":30}},"19":{"start":{"line":49,"column":2},"end":{"line":49,"column":22}},"20":{"start":{"line":50,"column":2},"end":{"line":50,"column":32}},"21":{"start":{"line":50,"column":19},"end":{"line":50,"column":30}},"22":{"start":{"line":51,"column":2},"end":{"line":51,"column":14}},"23":{"start":{"line":54,"column":0},"end":{"line":60,"column":1}},"24":{"start":{"line":55,"column":2},"end":{"line":55,"column":12}},"25":{"start":{"line":56,"column":2},"end":{"line":56,"column":14}},"26":{"start":{"line":57,"column":2},"end":{"line":57,"column":14}},"27":{"start":{"line":58,"column":2},"end":{"line":58,"column":14}},"28":{"start":{"line":59,"column":2},"end":{"line":59,"column":11}},"29":{"start":{"line":62,"column":0},"end":{"line":76,"column":1}},"30":{"start":{"line":63,"column":2},"end":{"line":65,"column":21}},"31":{"start":{"line":66,"column":2},"end":{"line":66,"column":67}},"32":{"start":{"line":66,"column":28},"end":{"line":66,"column":65}},"33":{"start":{"line":67,"column":2},"end":{"line":69,"column":4}},"34":{"start":{"line":68,"column":4},"end":{"line":68,"column":69}},"35":{"start":{"line":70,"column":2},"end":{"line":70,"column":20}},"36":{"start":{"line":71,"column":2},"end":{"line":74,"column":3}},"37":{"start":{"line":72,"column":4},"end":{"line":72,"column":51}},"38":{"start":{"line":72,"column":35},"end":{"line":72,"column":51}},"39":{"start":{"line":73,"column":4},"end":{"line":73,"column":52}},"40":{"start":{"line":73,"column":30},"end":{"line":73,"column":50}},"41":{"start":{"line":75,"column":2},"end":{"line":75,"column":14}},"42":{"start":{"line":78,"column":0},"end":{"line":97,"column":1}},"43":{"start":{"line":79,"column":2},"end":{"line":79,"column":21}},"44":{"start":{"line":81,"column":2},"end":{"line":94,"column":4}},"45":{"start":{"line":82,"column":4},"end":{"line":82,"column":24}},"46":{"start":{"line":83,"column":4},"end":{"line":92,"column":5}},"47":{"start":{"line":84,"column":6},"end":{"line":84,"column":30}},"48":{"start":{"line":85,"column":6},"end":{"line":85,"column":38}},"49":{"start":{"line":86,"column":6},"end":{"line":86,"column":18}},"50":{"start":{"line":87,"column":6},"end":{"line":87,"column":13}},"51":{"start":{"line":88,"column":6},"end":{"line":88,"column":13}},"52":{"start":{"line":89,"column":6},"end":{"line":89,"column":18}},"53":{"start":{"line":90,"column":6},"end":{"line":90,"column":13}},"54":{"start":{"line":91,"column":6},"end":{"line":91,"column":27}},"55":{"start":{"line":93,"column":4},"end":{"line":93,"column":46}},"56":{"start":{"line":96,"column":2},"end":{"line":96,"column":14}},"57":{"start":{"line":100,"column":0},"end":{"line":106,"column":1}},"58":{"start":{"line":101,"column":2},"end":{"line":101,"column":24}},"59":{"start":{"line":102,"column":7},"end":{"line":106,"column":1}},"60":{"start":{"line":103,"column":2},"end":{"line":103,"column":38}},"61":{"start":{"line":103,"column":22},"end":{"line":103,"column":34}},"62":{"start":{"line":105,"column":2},"end":{"line":105,"column":19}}},"branchMap":{"1":{"line":46,"type":"if","locations":[{"start":{"line":46,"column":2},"end":{"line":46,"column":2}},{"start":{"line":46,"column":2},"end":{"line":46,"column":2}}]},"2":{"line":48,"type":"if","locations":[{"start":{"line":48,"column":2},"end":{"line":48,"column":2}},{"start":{"line":48,"column":2},"end":{"line":48,"column":2}}]},"3":{"line":50,"type":"if","locations":[{"start":{"line":50,"column":2},"end":{"line":50,"column":2}},{"start":{"line":50,"column":2},"end":{"line":50,"column":2}}]},"4":{"line":64,"type":"binary-expr","locations":[{"start":{"line":64,"column":14},"end":{"line":64,"column":18}},{"start":{"line":64,"column":22},"end":{"line":64,"column":32}}]},"5":{"line":71,"type":"if","locations":[{"start":{"line":71,"column":2},"end":{"line":71,"column":2}},{"start":{"line":71,"column":2},"end":{"line":71,"column":2}}]},"6":{"line":72,"type":"if","locations":[{"start":{"line":72,"column":4},"end":{"line":72,"column":4}},{"start":{"line":72,"column":4},"end":{"line":72,"column":4}}]},"7":{"line":100,"type":"if","locations":[{"start":{"line":100,"column":0},"end":{"line":100,"column":0}},{"start":{"line":100,"column":0},"end":{"line":100,"column":0}}]},"8":{"line":100,"type":"binary-expr","locations":[{"start":{"line":100,"column":4},"end":{"line":100,"column":10}},{"start":{"line":100,"column":14},"end":{"line":100,"column":28}}]},"9":{"line":102,"type":"if","locations":[{"start":{"line":102,"column":7},"end":{"line":102,"column":7}},{"start":{"line":102,"column":7},"end":{"line":102,"column":7}}]},"10":{"line":102,"type":"binary-expr","locations":[{"start":{"line":102,"column":11},"end":{"line":102,"column":17}},{"start":{"line":102,"column":21},"end":{"line":102,"column":31}}]},"11":{"line":110,"type":"binary-expr","locations":[{"start":{"line":110,"column":2},"end":{"line":110,"column":29}},{"start":{"line":110,"column":33},"end":{"line":110,"column":39}}]},"12":{"line":111,"type":"binary-expr","locations":[{"start":{"line":111,"column":2},"end":{"line":111,"column":31}},{"start":{"line":111,"column":35},"end":{"line":111,"column":41}}]}}}} \ No newline at end of file diff --git a/node_modules/seedrandom/coverage/lcov-report/base.css b/node_modules/seedrandom/coverage/lcov-report/base.css new file mode 100644 index 0000000..f418035 --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/base.css @@ -0,0 +1,224 @@ +body, html { + margin:0; padding: 0; + height: 100%; +} +body { + font-family: Helvetica Neue, Helvetica, Arial; + font-size: 14px; + color:#333; +} +.small { font-size: 12px; } +*, *:after, *:before { + -webkit-box-sizing:border-box; + -moz-box-sizing:border-box; + box-sizing:border-box; + } +h1 { font-size: 20px; margin: 0;} +h2 { font-size: 14px; } +pre { + font: 12px/1.4 Consolas, "Liberation Mono", Menlo, Courier, monospace; + margin: 0; + padding: 0; + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; +} +a { color:#0074D9; text-decoration:none; } +a:hover { text-decoration:underline; } +.strong { font-weight: bold; } +.space-top1 { padding: 10px 0 0 0; } +.pad2y { padding: 20px 0; } +.pad1y { padding: 10px 0; } +.pad2x { padding: 0 20px; } +.pad2 { padding: 20px; } +.pad1 { padding: 10px; } +.space-left2 { padding-left:55px; } +.space-right2 { padding-right:20px; } +.center { text-align:center; } +.clearfix { display:block; } +.clearfix:after { + content:''; + display:block; + height:0; + clear:both; + visibility:hidden; + } +.fl { float: left; } +@media only screen and (max-width:640px) { + .col3 { width:100%; max-width:100%; } + .hide-mobile { display:none!important; } +} + +.quiet { + color: #7f7f7f; + color: rgba(0,0,0,0.5); +} +.quiet a { opacity: 0.7; } + +.fraction { + font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; + font-size: 10px; + color: #555; + background: #E8E8E8; + padding: 4px 5px; + border-radius: 3px; + vertical-align: middle; +} + +div.path a:link, div.path a:visited { color: #333; } +table.coverage { + border-collapse: collapse; + margin: 10px 0 0 0; + padding: 0; +} + +table.coverage td { + margin: 0; + padding: 0; + vertical-align: top; +} +table.coverage td.line-count { + text-align: right; + padding: 0 5px 0 20px; +} +table.coverage td.line-coverage { + text-align: right; + padding-right: 10px; + min-width:20px; +} + +table.coverage td span.cline-any { + display: inline-block; + padding: 0 5px; + width: 100%; +} +.missing-if-branch { + display: inline-block; + margin-right: 5px; + border-radius: 3px; + position: relative; + padding: 0 4px; + background: #333; + color: yellow; +} + +.skip-if-branch { + display: none; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: #ccc; + color: white; +} +.missing-if-branch .typ, .skip-if-branch .typ { + color: inherit !important; +} +.coverage-summary { + border-collapse: collapse; + width: 100%; +} +.coverage-summary tr { border-bottom: 1px solid #bbb; } +.keyline-all { border: 1px solid #ddd; } +.coverage-summary td, .coverage-summary th { padding: 10px; } +.coverage-summary tbody { border: 1px solid #bbb; } +.coverage-summary td { border-right: 1px solid #bbb; } +.coverage-summary td:last-child { border-right: none; } +.coverage-summary th { + text-align: left; + font-weight: normal; + white-space: nowrap; +} +.coverage-summary th.file { border-right: none !important; } +.coverage-summary th.pct { } +.coverage-summary th.pic, +.coverage-summary th.abs, +.coverage-summary td.pct, +.coverage-summary td.abs { text-align: right; } +.coverage-summary td.file { white-space: nowrap; } +.coverage-summary td.pic { min-width: 120px !important; } +.coverage-summary tfoot td { } + +.coverage-summary .sorter { + height: 10px; + width: 7px; + display: inline-block; + margin-left: 0.5em; + background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; +} +.coverage-summary .sorted .sorter { + background-position: 0 -20px; +} +.coverage-summary .sorted-desc .sorter { + background-position: 0 -10px; +} +.status-line { height: 10px; } +/* yellow */ +.cbranch-no { background: yellow !important; color: #111; } +/* dark red */ +.red.solid, .status-line.low, .low .cover-fill { background:#C21F39 } +.low .chart { border:1px solid #C21F39 } +.highlighted, +.highlighted .cstat-no, .highlighted .fstat-no, .highlighted .cbranch-no{ + background: #C21F39 !important; +} +/* medium red */ +.cstat-no, .fstat-no, .cbranch-no, .cbranch-no { background:#F6C6CE } +/* light red */ +.low, .cline-no { background:#FCE1E5 } +/* light green */ +.high, .cline-yes { background:rgb(230,245,208) } +/* medium green */ +.cstat-yes { background:rgb(161,215,106) } +/* dark green */ +.status-line.high, .high .cover-fill { background:rgb(77,146,33) } +.high .chart { border:1px solid rgb(77,146,33) } +/* dark yellow (gold) */ +.status-line.medium, .medium .cover-fill { background: #f9cd0b; } +.medium .chart { border:1px solid #f9cd0b; } +/* light yellow */ +.medium { background: #fff4c2; } + +.cstat-skip { background: #ddd; color: #111; } +.fstat-skip { background: #ddd; color: #111 !important; } +.cbranch-skip { background: #ddd !important; color: #111; } + +span.cline-neutral { background: #eaeaea; } + +.coverage-summary td.empty { + opacity: .5; + padding-top: 4px; + padding-bottom: 4px; + line-height: 1; + color: #888; +} + +.cover-fill, .cover-empty { + display:inline-block; + height: 12px; +} +.chart { + line-height: 0; +} +.cover-empty { + background: white; +} +.cover-full { + border-right: none !important; +} +pre.prettyprint { + border: none !important; + padding: 0 !important; + margin: 0 !important; +} +.com { color: #999 !important; } +.ignore-none { color: #999; font-weight: normal; } + +.wrapper { + min-height: 100%; + height: auto !important; + height: 100%; + margin: 0 auto -48px; +} +.footer, .push { + height: 48px; +} diff --git a/node_modules/seedrandom/coverage/lcov-report/block-navigation.js b/node_modules/seedrandom/coverage/lcov-report/block-navigation.js new file mode 100644 index 0000000..c7ff5a5 --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/block-navigation.js @@ -0,0 +1,79 @@ +/* eslint-disable */ +var jumpToCode = (function init() { + // Classes of code we would like to highlight in the file view + var missingCoverageClasses = ['.cbranch-no', '.cstat-no', '.fstat-no']; + + // Elements to highlight in the file listing view + var fileListingElements = ['td.pct.low']; + + // We don't want to select elements that are direct descendants of another match + var notSelector = ':not(' + missingCoverageClasses.join('):not(') + ') > '; // becomes `:not(a):not(b) > ` + + // Selecter that finds elements on the page to which we can jump + var selector = + fileListingElements.join(', ') + + ', ' + + notSelector + + missingCoverageClasses.join(', ' + notSelector); // becomes `:not(a):not(b) > a, :not(a):not(b) > b` + + // The NodeList of matching elements + var missingCoverageElements = document.querySelectorAll(selector); + + var currentIndex; + + function toggleClass(index) { + missingCoverageElements + .item(currentIndex) + .classList.remove('highlighted'); + missingCoverageElements.item(index).classList.add('highlighted'); + } + + function makeCurrent(index) { + toggleClass(index); + currentIndex = index; + missingCoverageElements.item(index).scrollIntoView({ + behavior: 'smooth', + block: 'center', + inline: 'center' + }); + } + + function goToPrevious() { + var nextIndex = 0; + if (typeof currentIndex !== 'number' || currentIndex === 0) { + nextIndex = missingCoverageElements.length - 1; + } else if (missingCoverageElements.length > 1) { + nextIndex = currentIndex - 1; + } + + makeCurrent(nextIndex); + } + + function goToNext() { + var nextIndex = 0; + + if ( + typeof currentIndex === 'number' && + currentIndex < missingCoverageElements.length - 1 + ) { + nextIndex = currentIndex + 1; + } + + makeCurrent(nextIndex); + } + + return function jump(event) { + switch (event.which) { + case 78: // n + case 74: // j + goToNext(); + break; + case 66: // b + case 75: // k + case 80: // p + goToPrevious(); + break; + } + }; +})(); +window.addEventListener('keydown', jumpToCode); diff --git a/node_modules/seedrandom/coverage/lcov-report/index.html b/node_modules/seedrandom/coverage/lcov-report/index.html new file mode 100644 index 0000000..6109d95 --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/index.html @@ -0,0 +1,110 @@ + + + + Code coverage report for All files + + + + + + + +
    +
    +

    + All files +

    +
    +
    + 93.21% + Statements + 439/471 +
    +
    + 73.2% + Branches + 142/194 +
    +
    + 90.41% + Functions + 66/73 +
    +
    + 94.44% + Lines + 374/396 +
    +
    +

    + Press n or j to go to the next uncovered block, b, p or k for the previous block. +

    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    FileStatementsBranchesFunctionsLines
    seedrandom
    96%96/10085.11%40/4793.33%14/1596.39%80/83
    seedrandom/lib
    92.45%343/37169.39%102/14789.66%52/5893.93%294/313
    +
    +
    + + + + + + + + diff --git a/node_modules/seedrandom/coverage/lcov-report/prettify.css b/node_modules/seedrandom/coverage/lcov-report/prettify.css new file mode 100644 index 0000000..b317a7c --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/node_modules/seedrandom/coverage/lcov-report/prettify.js b/node_modules/seedrandom/coverage/lcov-report/prettify.js new file mode 100644 index 0000000..b322523 --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/prettify.js @@ -0,0 +1,2 @@ +/* eslint-disable */ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/node_modules/seedrandom/coverage/lcov-report/seedrandom/index.html b/node_modules/seedrandom/coverage/lcov-report/seedrandom/index.html new file mode 100644 index 0000000..7c99c88 --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/seedrandom/index.html @@ -0,0 +1,97 @@ + + + + Code coverage report for seedrandom + + + + + + + +
    +
    +

    + All files seedrandom +

    +
    +
    + 96% + Statements + 96/100 +
    +
    + 85.11% + Branches + 40/47 +
    +
    + 93.33% + Functions + 14/15 +
    +
    + 96.39% + Lines + 80/83 +
    +
    +

    + Press n or j to go to the next uncovered block, b, p or k for the previous block. +

    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    FileStatementsBranchesFunctionsLines
    seedrandom.js
    96%96/10085.11%40/4793.33%14/1596.39%80/83
    +
    +
    + + + + + + + + diff --git a/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/alea.js.html b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/alea.js.html new file mode 100644 index 0000000..584d7c2 --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/alea.js.html @@ -0,0 +1,411 @@ + + + + Code coverage report for seedrandom/lib/alea.js + + + + + + + +
    +
    +

    + All files / seedrandom/lib alea.js +

    +
    +
    + 91.94% + Statements + 57/62 +
    +
    + 66.67% + Branches + 16/24 +
    +
    + 90.91% + Functions + 10/11 +
    +
    + 94.34% + Lines + 50/53 +
    +
    +

    + Press n or j to go to the next uncovered block, b, p or k for the previous block. +

    +
    +
    +
    
    +
    +
    1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +  +  +3x +  +3x +4105129x +4105129x +4105129x +4105129x +  +  +  +3x +3x +3x +3x +3x +3x +3x +3x +3x +3x +3x +  +  +  +2x +2x +2x +2x +2x +  +  +  +3x +3x +3x +1025x +3x +1025x +  +3x +3x +2x +2x +  +3x +  +  +  +3x +  +3x +18x +18x +33x +33x +33x +33x +33x +33x +33x +33x +  +18x +  +  +3x +  +  +  +1x +1x +  +  +  +  +  +  +  +  +  +  +  +  +  + 
    // A port of an algorithm by Johannes Baagøe <baagoe@baagoe.com>, 2010
    +// http://baagoe.com/en/RandomMusings/javascript/
    +// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
    +// Original work is under MIT license -
    + 
    +// Copyright (C) 2010 by Johannes Baagøe <baagoe@baagoe.org>
    +//
    +// 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.
    + 
    + 
    + 
    +(function(global, module, define) {
    + 
    +function Alea(seed) {
    +  var me = this, mash = Mash();
    + 
    +  me.next = function() {
    +    var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32
    +    me.s0 = me.s1;
    +    me.s1 = me.s2;
    +    return me.s2 = t - (me.c = t | 0);
    +  };
    + 
    +  // Apply the seeding algorithm from Baagoe.
    +  me.c = 1;
    +  me.s0 = mash(' ');
    +  me.s1 = mash(' ');
    +  me.s2 = mash(' ');
    +  me.s0 -= mash(seed);
    +  if (me.s0 < 0) { me.s0 += 1; }
    +  me.s1 -= mash(seed);
    +  Eif (me.s1 < 0) { me.s1 += 1; }
    +  me.s2 -= mash(seed);
    +  Iif (me.s2 < 0) { me.s2 += 1; }
    +  mash = null;
    +}
    + 
    +function copy(f, t) {
    +  t.c = f.c;
    +  t.s0 = f.s0;
    +  t.s1 = f.s1;
    +  t.s2 = f.s2;
    +  return t;
    +}
    + 
    +function impl(seed, opts) {
    +  var xg = new Alea(seed),
    +      state = opts && opts.state,
    +      prng = xg.next;
    +  prng.int32 = function() { return (xg.next() * 0x100000000) | 0; }
    +  prng.double = function() {
    +    return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
    +  };
    +  prng.quick = prng;
    +  if (state) {
    +    if (typeof(state) == 'object') copy(state, xg);
    +    prng.state = function() { return copy(xg, {}); }
    +  }
    +  return prng;
    +}
    + 
    +function Mash() {
    +  var n = 0xefc8249d;
    + 
    +  var mash = function(data) {
    +    data = String(data);
    +    for (var i = 0; i < data.length; i++) {
    +      n += data.charCodeAt(i);
    +      var h = 0.02519603282416938 * n;
    +      n = h >>> 0;
    +      h -= n;
    +      h *= n;
    +      n = h >>> 0;
    +      h -= n;
    +      n += h * 0x100000000; // 2^32
    +    }
    +    return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
    +  };
    + 
    +  return mash;
    +}
    + 
    + 
    +Eif (module && module.exports) {
    +  module.exports = impl;
    +} else if (define && define.amd) {
    +  define(function() { return impl; });
    +} else {
    +  this.alea = impl;
    +}
    + 
    +})(
    +  this,
    +  (typeof module) == 'object' && module,    // present in node.js
    +  (typeof define) == 'function' && define   // present with an AMD loader
    +);
    + 
    + 
    + 
    +
    +
    + + + + + + + + diff --git a/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/index.html b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/index.html new file mode 100644 index 0000000..4986a5b --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/index.html @@ -0,0 +1,162 @@ + + + + Code coverage report for seedrandom/lib + + + + + + + +
    +
    +

    + All files seedrandom/lib +

    +
    +
    + 92.45% + Statements + 343/371 +
    +
    + 69.39% + Branches + 102/147 +
    +
    + 89.66% + Functions + 52/58 +
    +
    + 93.93% + Lines + 294/313 +
    +
    +

    + Press n or j to go to the next uncovered block, b, p or k for the previous block. +

    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    FileStatementsBranchesFunctionsLines
    alea.js
    91.94%57/6266.67%16/2490.91%10/1194.34%50/53
    tychei.js
    92.98%53/5770%14/2088.89%8/993.75%45/48
    xor128.js
    91.84%45/4970%14/2088.89%8/993.02%40/43
    xor4096.js
    92.68%76/8265.71%23/3590%9/1094.52%69/73
    xorshift7.js
    92.42%61/6673.08%19/2690%9/1094%47/50
    xorwow.js
    92.73%51/5572.73%16/2288.89%8/993.48%43/46
    +
    +
    + + + + + + + + diff --git a/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/tychei.js.html b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/tychei.js.html new file mode 100644 index 0000000..29c3483 --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/tychei.js.html @@ -0,0 +1,378 @@ + + + + Code coverage report for seedrandom/lib/tychei.js + + + + + + + +
    +
    +

    + All files / seedrandom/lib tychei.js +

    +
    +
    + 92.98% + Statements + 53/57 +
    +
    + 70% + Branches + 14/20 +
    +
    + 88.89% + Functions + 8/9 +
    +
    + 93.75% + Lines + 45/48 +
    +
    +

    + Press n or j to go to the next uncovered block, b, p or k for the previous block. +

    +
    +
    +
    
    +
    +
    1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104  +  +  +  +1x +  +  +3x +  +  +3x +4105195x +4105195x +4105195x +4105195x +4105195x +4105195x +4105195x +4105195x +4105195x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +3x +3x +3x +3x +  +3x +  +2x +2x +  +  +1x +  +  +  +3x +66x +66x +  +  +  +  +2x +2x +2x +2x +2x +  +  +  +3x +3x +4102054x +3x +1025x +1025x +1025x +1025x +  +1025x +  +3x +3x +3x +2x +2x +  +3x +  +  +1x +1x +  +  +  +  +  +  +  +  +  +  +  +  +  + 
    // A Javascript implementaion of the "Tyche-i" prng algorithm by
    +// Samuel Neves and Filipe Araujo.
    +// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
    + 
    +(function(global, module, define) {
    + 
    +function XorGen(seed) {
    +  var me = this, strseed = '';
    + 
    +  // Set up generator function.
    +  me.next = function() {
    +    var b = me.b, c = me.c, d = me.d, a = me.a;
    +    b = (b << 25) ^ (b >>> 7) ^ c;
    +    c = (c - d) | 0;
    +    d = (d << 24) ^ (d >>> 8) ^ a;
    +    a = (a - b) | 0;
    +    me.b = b = (b << 20) ^ (b >>> 12) ^ c;
    +    me.c = c = (c - d) | 0;
    +    me.d = (d << 16) ^ (c >>> 16) ^ a;
    +    return me.a = (a - b) | 0;
    +  };
    + 
    +  /* The following is non-inverted tyche, which has better internal
    +   * bit diffusion, but which is about 25% slower than tyche-i in JS.
    +  me.next = function() {
    +    var a = me.a, b = me.b, c = me.c, d = me.d;
    +    a = (me.a + me.b | 0) >>> 0;
    +    d = me.d ^ a; d = d << 16 ^ d >>> 16;
    +    c = me.c + d | 0;
    +    b = me.b ^ c; b = b << 12 ^ d >>> 20;
    +    me.a = a = a + b | 0;
    +    d = d ^ a; me.d = d = d << 8 ^ d >>> 24;
    +    me.c = c = c + d | 0;
    +    b = b ^ c;
    +    return me.b = (b << 7 ^ b >>> 25);
    +  }
    +  */
    + 
    +  me.a = 0;
    +  me.b = 0;
    +  me.c = 2654435769 | 0;
    +  me.d = 1367130551;
    + 
    +  if (seed === Math.floor(seed)) {
    +    // Integer seed.
    +    me.a = (seed / 0x100000000) | 0;
    +    me.b = seed | 0;
    +  } else {
    +    // String seed.
    +    strseed += seed;
    +  }
    + 
    +  // Mix in string seed, then discard an initial batch of 64 values.
    +  for (var k = 0; k < strseed.length + 20; k++) {
    +    me.b ^= strseed.charCodeAt(k) | 0;
    +    me.next();
    +  }
    +}
    + 
    +function copy(f, t) {
    +  t.a = f.a;
    +  t.b = f.b;
    +  t.c = f.c;
    +  t.d = f.d;
    +  return t;
    +};
    + 
    +function impl(seed, opts) {
    +  var xg = new XorGen(seed),
    +      state = opts && opts.state,
    +      prng = function() { return (xg.next() >>> 0) / 0x100000000; };
    +  prng.double = function() {
    +    do {
    +      var top = xg.next() >>> 11,
    +          bot = (xg.next() >>> 0) / 0x100000000,
    +          result = (top + bot) / (1 << 21);
    +    } while (result === 0);
    +    return result;
    +  };
    +  prng.int32 = xg.next;
    +  prng.quick = prng;
    +  if (state) {
    +    if (typeof(state) == 'object') copy(state, xg);
    +    prng.state = function() { return copy(xg, {}); }
    +  }
    +  return prng;
    +}
    + 
    +Eif (module && module.exports) {
    +  module.exports = impl;
    +} else if (define && define.amd) {
    +  define(function() { return impl; });
    +} else {
    +  this.tychei = impl;
    +}
    + 
    +})(
    +  this,
    +  (typeof module) == 'object' && module,    // present in node.js
    +  (typeof define) == 'function' && define   // present with an AMD loader
    +);
    + 
    + 
    + 
    +
    +
    + + + + + + + + diff --git a/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xor128.js.html b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xor128.js.html new file mode 100644 index 0000000..77ec76f --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xor128.js.html @@ -0,0 +1,312 @@ + + + + Code coverage report for seedrandom/lib/xor128.js + + + + + + + +
    +
    +

    + All files / seedrandom/lib xor128.js +

    +
    +
    + 91.84% + Statements + 45/49 +
    +
    + 70% + Branches + 14/20 +
    +
    + 88.89% + Functions + 8/9 +
    +
    + 93.02% + Lines + 40/43 +
    +
    +

    + Press n or j to go to the next uncovered block, b, p or k for the previous block. +

    +
    +
    +
    
    +
    +
    1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82  +  +  +1x +  +  +3x +  +3x +3x +3x +3x +  +  +3x +4105327x +4105327x +4105327x +4105327x +4105327x +  +  +3x +  +2x +  +  +1x +  +  +  +3x +198x +198x +  +  +  +  +2x +2x +2x +2x +2x +  +  +  +3x +3x +4102054x +3x +1025x +1025x +1025x +1025x +  +1025x +  +3x +3x +3x +2x +2x +  +3x +  +  +1x +1x +  +  +  +  +  +  +  +  +  +  +  +  +  + 
    // A Javascript implementaion of the "xor128" prng algorithm by
    +// George Marsaglia.  See http://www.jstatsoft.org/v08/i14/paper
    + 
    +(function(global, module, define) {
    + 
    +function XorGen(seed) {
    +  var me = this, strseed = '';
    + 
    +  me.x = 0;
    +  me.y = 0;
    +  me.z = 0;
    +  me.w = 0;
    + 
    +  // Set up generator function.
    +  me.next = function() {
    +    var t = me.x ^ (me.x << 11);
    +    me.x = me.y;
    +    me.y = me.z;
    +    me.z = me.w;
    +    return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);
    +  };
    + 
    +  if (seed === (seed | 0)) {
    +    // Integer seed.
    +    me.x = seed;
    +  } else {
    +    // String seed.
    +    strseed += seed;
    +  }
    + 
    +  // Mix in string seed, then discard an initial batch of 64 values.
    +  for (var k = 0; k < strseed.length + 64; k++) {
    +    me.x ^= strseed.charCodeAt(k) | 0;
    +    me.next();
    +  }
    +}
    + 
    +function copy(f, t) {
    +  t.x = f.x;
    +  t.y = f.y;
    +  t.z = f.z;
    +  t.w = f.w;
    +  return t;
    +}
    + 
    +function impl(seed, opts) {
    +  var xg = new XorGen(seed),
    +      state = opts && opts.state,
    +      prng = function() { return (xg.next() >>> 0) / 0x100000000; };
    +  prng.double = function() {
    +    do {
    +      var top = xg.next() >>> 11,
    +          bot = (xg.next() >>> 0) / 0x100000000,
    +          result = (top + bot) / (1 << 21);
    +    } while (result === 0);
    +    return result;
    +  };
    +  prng.int32 = xg.next;
    +  prng.quick = prng;
    +  if (state) {
    +    if (typeof(state) == 'object') copy(state, xg);
    +    prng.state = function() { return copy(xg, {}); }
    +  }
    +  return prng;
    +}
    + 
    +Eif (module && module.exports) {
    +  module.exports = impl;
    +} else if (define && define.amd) {
    +  define(function() { return impl; });
    +} else {
    +  this.xor128 = impl;
    +}
    + 
    +})(
    +  this,
    +  (typeof module) == 'object' && module,    // present in node.js
    +  (typeof define) == 'function' && define   // present with an AMD loader
    +);
    + 
    + 
    + 
    +
    +
    + + + + + + + + diff --git a/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xor4096.js.html b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xor4096.js.html new file mode 100644 index 0000000..a9b085b --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xor4096.js.html @@ -0,0 +1,507 @@ + + + + Code coverage report for seedrandom/lib/xor4096.js + + + + + + + +
    +
    +

    + All files / seedrandom/lib xor4096.js +

    +
    +
    + 92.68% + Statements + 76/82 +
    +
    + 65.71% + Branches + 23/35 +
    +
    + 90% + Functions + 9/10 +
    +
    + 94.52% + Lines + 69/73 +
    +
    +

    + Press n or j to go to the next uncovered block, b, p or k for the previous block. +

    +
    +
    +
    
    +
    +
    1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +  +  +3x +  +  +3x +4105129x +4105129x +  +4105129x +  +4105129x +4105129x +4105129x +4105129x +4105129x +4105129x +  +4105129x +4105129x +  +4105129x +  +  +  +3x +3x +  +2x +2x +  +  +1x +1x +1x +  +  +3x +  +480x +  +480x +480x +480x +480x +480x +480x +384x +384x +384x +  +  +  +3x +  +  +  +  +  +3x +3x +1536x +1536x +1536x +1536x +1536x +1536x +1536x +  +  +3x +3x +3x +  +  +3x +  +  +  +2x +2x +2x +2x +  +  +  +3x +3x +3x +4102054x +3x +1025x +1025x +1025x +1025x +  +1025x +  +3x +3x +3x +2x +2x +  +3x +  +  +1x +1x +  +  +  +  +  +  +  +  +  +  +  + 
    // A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.
    +//
    +// This fast non-cryptographic random number generator is designed for
    +// use in Monte-Carlo algorithms. It combines a long-period xorshift
    +// generator with a Weyl generator, and it passes all common batteries
    +// of stasticial tests for randomness while consuming only a few nanoseconds
    +// for each prng generated.  For background on the generator, see Brent's
    +// paper: "Some long-period random number generators using shifts and xors."
    +// http://arxiv.org/pdf/1004.3115v1.pdf
    +//
    +// Usage:
    +//
    +// var xor4096 = require('xor4096');
    +// random = xor4096(1);                        // Seed with int32 or string.
    +// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.
    +// assert.equal(random.int32(), 1806534897);   // signed int32, 32 bits.
    +//
    +// For nonzero numeric keys, this impelementation provides a sequence
    +// identical to that by Brent's xorgens 3 implementaion in C.  This
    +// implementation also provides for initalizing the generator with
    +// string seeds, or for saving and restoring the state of the generator.
    +//
    +// On Chrome, this prng benchmarks about 2.1 times slower than
    +// Javascript's built-in Math.random().
    + 
    +(function(global, module, define) {
    + 
    +function XorGen(seed) {
    +  var me = this;
    + 
    +  // Set up generator function.
    +  me.next = function() {
    +    var w = me.w,
    +        X = me.X, i = me.i, t, v;
    +    // Update Weyl generator.
    +    me.w = w = (w + 0x61c88647) | 0;
    +    // Update xor generator.
    +    v = X[(i + 34) & 127];
    +    t = X[i = ((i + 1) & 127)];
    +    v ^= v << 13;
    +    t ^= t << 17;
    +    v ^= v >>> 15;
    +    t ^= t >>> 12;
    +    // Update Xor generator array state.
    +    v = X[i] = v ^ t;
    +    me.i = i;
    +    // Result is the combination.
    +    return (v + (w ^ (w >>> 16))) | 0;
    +  };
    + 
    +  function init(me, seed) {
    +    var t, v, i, j, w, X = [], limit = 128;
    +    if (seed === (seed | 0)) {
    +      // Numeric seeds initialize v, which is used to generates X.
    +      v = seed;
    +      seed = null;
    +    } else {
    +      // String seeds are mixed into v and X one character at a time.
    +      seed = seed + '\0';
    +      v = 0;
    +      limit = Math.max(limit, seed.length);
    +    }
    +    // Initialize circular array and weyl value.
    +    for (i = 0, j = -32; j < limit; ++j) {
    +      // Put the unicode characters into the array, and shuffle them.
    +      if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);
    +      // After 32 shuffles, take v as the starting w value.
    +      if (j === 0) w = v;
    +      v ^= v << 10;
    +      v ^= v >>> 15;
    +      v ^= v << 4;
    +      v ^= v >>> 13;
    +      if (j >= 0) {
    +        w = (w + 0x61c88647) | 0;     // Weyl.
    +        t = (X[j & 127] ^= (v + w));  // Combine xor and weyl to init array.
    +        i = (0 == t) ? i + 1 : 0;     // Count zeroes.
    +      }
    +    }
    +    // We have detected all zeroes; make the key nonzero.
    +    Iif (i >= 128) {
    +      X[(seed && seed.length || 0) & 127] = -1;
    +    }
    +    // Run the generator 512 times to further mix the state before using it.
    +    // Factoring this as a function slows the main generator, so it is just
    +    // unrolled here.  The weyl generator is not advanced while warming up.
    +    i = 127;
    +    for (j = 4 * 128; j > 0; --j) {
    +      v = X[(i + 34) & 127];
    +      t = X[i = ((i + 1) & 127)];
    +      v ^= v << 13;
    +      t ^= t << 17;
    +      v ^= v >>> 15;
    +      t ^= t >>> 12;
    +      X[i] = v ^ t;
    +    }
    +    // Storing state as object members is faster than using closure variables.
    +    me.w = w;
    +    me.X = X;
    +    me.i = i;
    +  }
    + 
    +  init(me, seed);
    +}
    + 
    +function copy(f, t) {
    +  t.i = f.i;
    +  t.w = f.w;
    +  t.X = f.X.slice();
    +  return t;
    +};
    + 
    +function impl(seed, opts) {
    +  Iif (seed == null) seed = +(new Date);
    +  var xg = new XorGen(seed),
    +      state = opts && opts.state,
    +      prng = function() { return (xg.next() >>> 0) / 0x100000000; };
    +  prng.double = function() {
    +    do {
    +      var top = xg.next() >>> 11,
    +          bot = (xg.next() >>> 0) / 0x100000000,
    +          result = (top + bot) / (1 << 21);
    +    } while (result === 0);
    +    return result;
    +  };
    +  prng.int32 = xg.next;
    +  prng.quick = prng;
    +  if (state) {
    +    if (state.X) copy(state, xg);
    +    prng.state = function() { return copy(xg, {}); }
    +  }
    +  return prng;
    +}
    + 
    +Eif (module && module.exports) {
    +  module.exports = impl;
    +} else if (define && define.amd) {
    +  define(function() { return impl; });
    +} else {
    +  this.xor4096 = impl;
    +}
    + 
    +})(
    +  this,                                     // window object or global
    +  (typeof module) == 'object' && module,    // present in node.js
    +  (typeof define) == 'function' && define   // present with an AMD loader
    +);
    + 
    +
    +
    + + + + + + + + diff --git a/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xorshift7.js.html b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xorshift7.js.html new file mode 100644 index 0000000..e50230c --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xorshift7.js.html @@ -0,0 +1,360 @@ + + + + Code coverage report for seedrandom/lib/xorshift7.js + + + + + + + +
    +
    +

    + All files / seedrandom/lib xorshift7.js +

    +
    +
    + 92.42% + Statements + 61/66 +
    +
    + 73.08% + Branches + 19/26 +
    +
    + 90% + Functions + 9/10 +
    +
    + 94% + Lines + 47/50 +
    +
    +

    + Press n or j to go to the next uncovered block, b, p or k for the previous block. +

    +
    +
    +
    
    +
    +
    1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98  +  +  +  +  +1x +  +  +3x +  +  +3x +  +4105897x +4105897x +4105897x +4105897x +4105897x +4105897x +4105897x +4105897x +4105897x +  +  +  +3x +  +3x +  +2x +  +  +1x +1x +6x +  +  +  +  +16x +3x +3x +  +3x +3x +  +  +3x +768x +  +  +  +3x +  +  +  +2x +2x +2x +  +  +  +3x +3x +3x +4102054x +3x +1025x +1025x +1025x +1025x +  +1025x +  +3x +3x +3x +2x +2x +  +3x +  +  +1x +1x +  +  +  +  +  +  +  +  +  +  +  +  + 
    // A Javascript implementaion of the "xorshift7" algorithm by
    +// François Panneton and Pierre L'ecuyer:
    +// "On the Xorgshift Random Number Generators"
    +// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf
    + 
    +(function(global, module, define) {
    + 
    +function XorGen(seed) {
    +  var me = this;
    + 
    +  // Set up generator function.
    +  me.next = function() {
    +    // Update xor generator.
    +    var X = me.x, i = me.i, t, v, w;
    +    t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);
    +    t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);
    +    t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);
    +    t = X[(i + 4) & 7]; v ^= t ^ (t << 7);
    +    t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);
    +    X[i] = v;
    +    me.i = (i + 1) & 7;
    +    return v;
    +  };
    + 
    +  function init(me, seed) {
    +    var j, w, X = [];
    + 
    +    if (seed === (seed | 0)) {
    +      // Seed state array using a 32-bit integer.
    +      w = X[0] = seed;
    +    } else {
    +      // Seed state using a string.
    +      seed = '' + seed;
    +      for (j = 0; j < seed.length; ++j) {
    +        X[j & 7] = (X[j & 7] << 15) ^
    +            (seed.charCodeAt(j) + X[(j + 1) & 7] << 13);
    +      }
    +    }
    +    // Enforce an array length of 8, not all zeroes.
    +    while (X.length < 8) X.push(0);
    +    for (j = 0; j < 8 && X[j] === 0; ++j);
    +    if (j == 8) w = X[7] = -1; else w = X[j];
    + 
    +    me.x = X;
    +    me.i = 0;
    + 
    +    // Discard an initial 256 values.
    +    for (j = 256; j > 0; --j) {
    +      me.next();
    +    }
    +  }
    + 
    +  init(me, seed);
    +}
    + 
    +function copy(f, t) {
    +  t.x = f.x.slice();
    +  t.i = f.i;
    +  return t;
    +}
    + 
    +function impl(seed, opts) {
    +  Iif (seed == null) seed = +(new Date);
    +  var xg = new XorGen(seed),
    +      state = opts && opts.state,
    +      prng = function() { return (xg.next() >>> 0) / 0x100000000; };
    +  prng.double = function() {
    +    do {
    +      var top = xg.next() >>> 11,
    +          bot = (xg.next() >>> 0) / 0x100000000,
    +          result = (top + bot) / (1 << 21);
    +    } while (result === 0);
    +    return result;
    +  };
    +  prng.int32 = xg.next;
    +  prng.quick = prng;
    +  if (state) {
    +    if (state.x) copy(state, xg);
    +    prng.state = function() { return copy(xg, {}); }
    +  }
    +  return prng;
    +}
    + 
    +Eif (module && module.exports) {
    +  module.exports = impl;
    +} else if (define && define.amd) {
    +  define(function() { return impl; });
    +} else {
    +  this.xorshift7 = impl;
    +}
    + 
    +})(
    +  this,
    +  (typeof module) == 'object' && module,    // present in node.js
    +  (typeof define) == 'function' && define   // present with an AMD loader
    +);
    + 
    + 
    +
    +
    + + + + + + + + diff --git a/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xorwow.js.html b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xorwow.js.html new file mode 100644 index 0000000..3c8d5a7 --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/seedrandom/lib/xorwow.js.html @@ -0,0 +1,327 @@ + + + + Code coverage report for seedrandom/lib/xorwow.js + + + + + + + +
    +
    +

    + All files / seedrandom/lib xorwow.js +

    +
    +
    + 92.73% + Statements + 51/55 +
    +
    + 72.73% + Branches + 16/22 +
    +
    + 88.89% + Functions + 8/9 +
    +
    + 93.48% + Lines + 43/46 +
    +
    +

    + Press n or j to go to the next uncovered block, b, p or k for the previous block. +

    +
    +
    +
    
    +
    +
    1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87  +  +  +1x +  +  +3x +  +  +3x +4105327x +4105327x +4105327x +  +  +  +3x +3x +3x +3x +3x +  +3x +  +2x +  +  +1x +  +  +  +3x +198x +198x +3x +  +198x +  +  +  +  +2x +2x +2x +2x +2x +2x +2x +  +  +  +3x +3x +4102054x +3x +1025x +1025x +1025x +1025x +  +1025x +  +3x +3x +3x +2x +2x +  +3x +  +  +1x +1x +  +  +  +  +  +  +  +  +  +  +  +  +  + 
    // A Javascript implementaion of the "xorwow" prng algorithm by
    +// George Marsaglia.  See http://www.jstatsoft.org/v08/i14/paper
    + 
    +(function(global, module, define) {
    + 
    +function XorGen(seed) {
    +  var me = this, strseed = '';
    + 
    +  // Set up generator function.
    +  me.next = function() {
    +    var t = (me.x ^ (me.x >>> 2));
    +    me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v;
    +    return (me.d = (me.d + 362437 | 0)) +
    +       (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0;
    +  };
    + 
    +  me.x = 0;
    +  me.y = 0;
    +  me.z = 0;
    +  me.w = 0;
    +  me.v = 0;
    + 
    +  if (seed === (seed | 0)) {
    +    // Integer seed.
    +    me.x = seed;
    +  } else {
    +    // String seed.
    +    strseed += seed;
    +  }
    + 
    +  // Mix in string seed, then discard an initial batch of 64 values.
    +  for (var k = 0; k < strseed.length + 64; k++) {
    +    me.x ^= strseed.charCodeAt(k) | 0;
    +    if (k == strseed.length) {
    +      me.d = me.x << 10 ^ me.x >>> 4;
    +    }
    +    me.next();
    +  }
    +}
    + 
    +function copy(f, t) {
    +  t.x = f.x;
    +  t.y = f.y;
    +  t.z = f.z;
    +  t.w = f.w;
    +  t.v = f.v;
    +  t.d = f.d;
    +  return t;
    +}
    + 
    +function impl(seed, opts) {
    +  var xg = new XorGen(seed),
    +      state = opts && opts.state,
    +      prng = function() { return (xg.next() >>> 0) / 0x100000000; };
    +  prng.double = function() {
    +    do {
    +      var top = xg.next() >>> 11,
    +          bot = (xg.next() >>> 0) / 0x100000000,
    +          result = (top + bot) / (1 << 21);
    +    } while (result === 0);
    +    return result;
    +  };
    +  prng.int32 = xg.next;
    +  prng.quick = prng;
    +  if (state) {
    +    if (typeof(state) == 'object') copy(state, xg);
    +    prng.state = function() { return copy(xg, {}); }
    +  }
    +  return prng;
    +}
    + 
    +Eif (module && module.exports) {
    +  module.exports = impl;
    +} else if (define && define.amd) {
    +  define(function() { return impl; });
    +} else {
    +  this.xorwow = impl;
    +}
    + 
    +})(
    +  this,
    +  (typeof module) == 'object' && module,    // present in node.js
    +  (typeof define) == 'function' && define   // present with an AMD loader
    +);
    + 
    + 
    + 
    +
    +
    + + + + + + + + diff --git a/node_modules/seedrandom/coverage/lcov-report/seedrandom/seedrandom.js.html b/node_modules/seedrandom/coverage/lcov-report/seedrandom/seedrandom.js.html new file mode 100644 index 0000000..ca72564 --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/seedrandom/seedrandom.js.html @@ -0,0 +1,828 @@ + + + + Code coverage report for seedrandom/seedrandom.js + + + + + + + +
    +
    +

    + All files / seedrandom seedrandom.js +

    +
    +
    + 96% + Statements + 96/100 +
    +
    + 85.11% + Branches + 40/47 +
    +
    + 93.33% + Functions + 14/15 +
    +
    + 96.39% + Lines + 80/83 +
    +
    +

    + Press n or j to go to the next uncovered block, b, p or k for the previous block. +

    +
    +
    +
    
    +
    +
    1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +6x +  +  +  +  +6x +6x +6x +6x +6x +6x +6x +6x +  +  +  +  +  +  +  +23x +23x +  +  +23x +  +  +  +  +23x +  +  +  +23x +3694x +3694x +3694x +3694x +3917x +3917x +3917x +  +3694x +9249x +9249x +9249x +  +3694x +  +  +1025x +4100001x +23x +  +  +23x +  +  +23x +  +20x +  +4x +  +4x +  +  +  +  +20x +  +  +  +19x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +23x +23x +  +  +23x +  +  +23x +5888x +  +23x +5888x +5888x +  +  +  +23x +  +4108660x +4108660x +4108660x +16436073x +16436073x +  +4108660x +4108660x +  +  +  +  +  +  +  +  +  +  +  +4x +4x +4x +4x +  +  +  +  +  +  +  +32x +32x +4x +9x +  +  +32x +  +  +  +  +  +  +  +  +52x +52x +7735x +  +  +52x +  +  +  +  +  +  +  +  +4x +  +4x +  +3x +  +1x +1x +  +3x +  +1x +1x +1x +  +  +  +  +  +  +  +  +81x +  +  +  +  +  +  +  +  +  +6x +  +  +  +  +  +6x +6x +  +6x +6x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  + 
    /*
    +Copyright 2019 David Bau.
    + 
    +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.
    + 
    +*/
    + 
    +(function (global, pool, math) {
    +//
    +// The following constants are related to IEEE 754 limits.
    +//
    + 
    +var width = 256,        // each RC4 output is 0 <= x < 256
    +    chunks = 6,         // at least six RC4 outputs for each double
    +    digits = 52,        // there are 52 significant digits in a double
    +    rngname = 'random', // rngname: name for Math.random and Math.seedrandom
    +    startdenom = math.pow(width, chunks),
    +    significance = math.pow(2, digits),
    +    overflow = significance * 2,
    +    mask = width - 1,
    +    nodecrypto;         // node.js crypto module, initialized at the bottom.
    + 
    +//
    +// seedrandom()
    +// This is the seedrandom function described above.
    +//
    +function seedrandom(seed, options, callback) {
    +  var key = [];
    +  options = (options == true) ? { entropy: true } : (options || {});
    + 
    +  // Flatten the seed string or build one from local entropy if needed.
    +  var shortseed = mixkey(flatten(
    +    options.entropy ? [seed, tostring(pool)] :
    +    (seed == null) ? autoseed() : seed, 3), key);
    + 
    +  // Use the seed to initialize an ARC4 generator.
    +  var arc4 = new ARC4(key);
    + 
    +  // This function returns a random double in [0, 1) that contains
    +  // randomness in every bit of the mantissa of the IEEE 754 value.
    +  var prng = function() {
    +    var n = arc4.g(chunks),             // Start with a numerator n < 2 ^ 48
    +        d = startdenom,                 //   and denominator d = 2 ^ 48.
    +        x = 0;                          //   and no 'extra last byte'.
    +    while (n < significance) {          // Fill up all significant digits by
    +      n = (n + x) * width;              //   shifting numerator and
    +      d *= width;                       //   denominator and generating a
    +      x = arc4.g(1);                    //   new least-significant-byte.
    +    }
    +    while (n >= overflow) {             // To avoid rounding up, before adding
    +      n /= 2;                           //   last byte, shift everything
    +      d /= 2;                           //   right using integer math until
    +      x >>>= 1;                         //   we have exactly the desired bits.
    +    }
    +    return (n + x) / d;                 // Form the number within [0, 1).
    +  };
    + 
    +  prng.int32 = function() { return arc4.g(4) | 0; }
    +  prng.quick = function() { return arc4.g(4) / 0x100000000; }
    +  prng.double = prng;
    + 
    +  // Mix the randomness into accumulated entropy.
    +  mixkey(tostring(arc4.S), pool);
    + 
    +  // Calling convention: what to return as a function of prng, seed, is_math.
    +  return (options.pass || callback ||
    +      function(prng, seed, is_math_call, state) {
    +        if (state) {
    +          // Load the arc4 state from the given state if it has an S array.
    +          if (state.S) { copy(state, arc4); }
    +          // Only provide the .state method if requested via options.state.
    +          prng.state = function() { return copy(arc4, {}); }
    +        }
    + 
    +        // If called as a method of Math (Math.seedrandom()), mutate
    +        // Math.random because that is how seedrandom.js has worked since v1.0.
    +        if (is_math_call) { math[rngname] = prng; return seed; }
    + 
    +        // Otherwise, it is a newer calling convention, so return the
    +        // prng directly.
    +        else return prng;
    +      })(
    +  prng,
    +  shortseed,
    +  'global' in options ? options.global : (this == math),
    +  options.state);
    +}
    + 
    +//
    +// ARC4
    +//
    +// An ARC4 implementation.  The constructor takes a key in the form of
    +// an array of at most (width) integers that should be 0 <= x < (width).
    +//
    +// The g(count) method returns a pseudorandom integer that concatenates
    +// the next (count) outputs from ARC4.  Its return value is a number x
    +// that is in the range 0 <= x < (width ^ count).
    +//
    +function ARC4(key) {
    +  var t, keylen = key.length,
    +      me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
    + 
    +  // The empty key [] is treated as [0].
    +  if (!keylen) { key = [keylen++]; }
    + 
    +  // Set up S using the standard key scheduling algorithm.
    +  while (i < width) {
    +    s[i] = i++;
    +  }
    +  for (i = 0; i < width; i++) {
    +    s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
    +    s[j] = t;
    +  }
    + 
    +  // The "g" method returns the next (count) outputs as one number.
    +  (me.g = function(count) {
    +    // Using instance members instead of closure state nearly doubles speed.
    +    var t, r = 0,
    +        i = me.i, j = me.j, s = me.S;
    +    while (count--) {
    +      t = s[i = mask & (i + 1)];
    +      r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
    +    }
    +    me.i = i; me.j = j;
    +    return r;
    +    // For robust unpredictability, the function call below automatically
    +    // discards an initial batch of values.  This is called RC4-drop[256].
    +    // See http://google.com/search?q=rsa+fluhrer+response&btnI
    +  })(width);
    +}
    + 
    +//
    +// copy()
    +// Copies internal state of ARC4 to or from a plain object.
    +//
    +function copy(f, t) {
    +  t.i = f.i;
    +  t.j = f.j;
    +  t.S = f.S.slice();
    +  return t;
    +};
    + 
    +//
    +// flatten()
    +// Converts an object tree to nested arrays of strings.
    +//
    +function flatten(obj, depth) {
    +  var result = [], typ = (typeof obj), prop;
    +  if (depth && typ == 'object') {
    +    for (prop in obj) {
    +      try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
    +    }
    +  }
    +  return (result.length ? result : typ == 'string' ? obj : obj + '\0');
    +}
    + 
    +//
    +// mixkey()
    +// Mixes a string seed into a key that is an array of integers, and
    +// returns a shortened string seed that is equivalent to the result key.
    +//
    +function mixkey(seed, key) {
    +  var stringseed = seed + '', smear, j = 0;
    +  while (j < stringseed.length) {
    +    key[mask & j] =
    +      mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
    +  }
    +  return tostring(key);
    +}
    + 
    +//
    +// autoseed()
    +// Returns an object for autoseeding, using window.crypto and Node crypto
    +// module if available.
    +//
    +function autoseed() {
    +  try {
    +    var out;
    +    if (nodecrypto && (out = nodecrypto.randomBytes)) {
    +      // The use of 'out' to remember randomBytes makes tight minified code.
    +      out = out(width);
    +    } else {
    +      out = new Uint8Array(width);
    +      (global.crypto || global.msCrypto).getRandomValues(out);
    +    }
    +    return tostring(out);
    +  } catch (e) {
    +    var browser = global.navigator,
    +        plugins = browser && browser.plugins;
    +    return [+new Date, global, plugins, global.screen, tostring(pool)];
    +  }
    +}
    + 
    +//
    +// tostring()
    +// Converts an array of charcodes to a string
    +//
    +function tostring(a) {
    +  return String.fromCharCode.apply(0, a);
    +}
    + 
    +//
    +// When seedrandom.js is loaded, we immediately mix a few bits
    +// from the built-in RNG into the entropy pool.  Because we do
    +// not want to interfere with deterministic PRNG state later,
    +// seedrandom will not call math.random on its own again after
    +// initialization.
    +//
    +mixkey(math.random(), pool);
    + 
    +//
    +// Nodejs and AMD support: export the implementation as a module using
    +// either convention.
    +//
    +Eif ((typeof module) == 'object' && module.exports) {
    +  module.exports = seedrandom;
    +  // When in node.js, try using crypto package for autoseeding.
    +  try {
    +    nodecrypto = require('crypto');
    +  } catch (ex) {}
    +} else if ((typeof define) == 'function' && define.amd) {
    +  define(function() { return seedrandom; });
    +} else {
    +  // When included as a plain script, set up Math.seedrandom global.
    +  math['seed' + rngname] = seedrandom;
    +}
    + 
    + 
    +// End anonymous scope, and pass initial values.
    +})(
    +  // global: `self` in browsers (including strict mode and web workers),
    +  // otherwise `this` in Node and other environments
    +  (typeof self !== 'undefined') ? self : this,
    +  [],     // pool: entropy pool starts empty
    +  Math    // math: package containing random, pow, and seedrandom
    +);
    + 
    +
    +
    + + + + + + + + diff --git a/node_modules/seedrandom/coverage/lcov-report/sort-arrow-sprite.png b/node_modules/seedrandom/coverage/lcov-report/sort-arrow-sprite.png new file mode 100644 index 0000000..03f704a Binary files /dev/null and b/node_modules/seedrandom/coverage/lcov-report/sort-arrow-sprite.png differ diff --git a/node_modules/seedrandom/coverage/lcov-report/sorter.js b/node_modules/seedrandom/coverage/lcov-report/sorter.js new file mode 100644 index 0000000..16de10c --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov-report/sorter.js @@ -0,0 +1,170 @@ +/* eslint-disable */ +var addSorting = (function() { + 'use strict'; + var cols, + currentSort = { + index: 0, + desc: false + }; + + // returns the summary table element + function getTable() { + return document.querySelector('.coverage-summary'); + } + // returns the thead element of the summary table + function getTableHeader() { + return getTable().querySelector('thead tr'); + } + // returns the tbody element of the summary table + function getTableBody() { + return getTable().querySelector('tbody'); + } + // returns the th element for nth column + function getNthColumn(n) { + return getTableHeader().querySelectorAll('th')[n]; + } + + // loads all columns + function loadColumns() { + var colNodes = getTableHeader().querySelectorAll('th'), + colNode, + cols = [], + col, + i; + + for (i = 0; i < colNodes.length; i += 1) { + colNode = colNodes[i]; + col = { + key: colNode.getAttribute('data-col'), + sortable: !colNode.getAttribute('data-nosort'), + type: colNode.getAttribute('data-type') || 'string' + }; + cols.push(col); + if (col.sortable) { + col.defaultDescSort = col.type === 'number'; + colNode.innerHTML = + colNode.innerHTML + ''; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function(a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function(a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc + ? ' sorted-desc' + : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function() { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i = 0; i < cols.length; i += 1) { + if (cols[i].sortable) { + // add the click event handler on the th so users + // dont have to click on those tiny arrows + el = getNthColumn(i).querySelector('.sorter').parentElement; + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function() { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/node_modules/seedrandom/coverage/lcov.info b/node_modules/seedrandom/coverage/lcov.info new file mode 100644 index 0000000..bf8175d --- /dev/null +++ b/node_modules/seedrandom/coverage/lcov.info @@ -0,0 +1,799 @@ +TN: +SF:/home/davidbau/git/seedrandom/seedrandom.js +FN:25,(anonymous_0) +FN:44,seedrandom +FN:58,(anonymous_2) +FN:75,(anonymous_3) +FN:76,(anonymous_4) +FN:84,(anonymous_5) +FN:89,(anonymous_6) +FN:116,ARC4 +FN:133,(anonymous_8) +FN:153,copy +FN:164,flatten +FN:179,mixkey +FN:193,autoseed +FN:215,tostring +FN:239,(anonymous_14) +FNF:15 +FNH:14 +FNDA:6,(anonymous_0) +FNDA:23,seedrandom +FNDA:3694,(anonymous_2) +FNDA:1025,(anonymous_3) +FNDA:4100001,(anonymous_4) +FNDA:20,(anonymous_5) +FNDA:2,(anonymous_6) +FNDA:23,ARC4 +FNDA:4108660,(anonymous_8) +FNDA:4,copy +FNDA:32,flatten +FNDA:52,mixkey +FNDA:4,autoseed +FNDA:81,tostring +FNDA:0,(anonymous_14) +DA:25,6 +DA:30,6 +DA:31,6 +DA:32,6 +DA:33,6 +DA:34,6 +DA:35,6 +DA:36,6 +DA:37,6 +DA:45,23 +DA:46,23 +DA:49,23 +DA:54,23 +DA:58,23 +DA:59,3694 +DA:60,3694 +DA:61,3694 +DA:62,3694 +DA:63,3917 +DA:64,3917 +DA:65,3917 +DA:67,3694 +DA:68,9249 +DA:69,9249 +DA:70,9249 +DA:72,3694 +DA:75,1025 +DA:76,4100001 +DA:77,23 +DA:80,23 +DA:83,23 +DA:85,20 +DA:87,4 +DA:89,4 +DA:94,20 +DA:98,19 +DA:117,23 +DA:118,23 +DA:121,23 +DA:124,23 +DA:125,5888 +DA:127,23 +DA:128,5888 +DA:129,5888 +DA:133,23 +DA:135,4108660 +DA:136,4108660 +DA:137,4108660 +DA:138,16436073 +DA:139,16436073 +DA:141,4108660 +DA:142,4108660 +DA:154,4 +DA:155,4 +DA:156,4 +DA:157,4 +DA:165,32 +DA:166,32 +DA:167,4 +DA:168,9 +DA:171,32 +DA:180,52 +DA:181,52 +DA:182,7735 +DA:185,52 +DA:194,4 +DA:196,4 +DA:198,3 +DA:200,1 +DA:201,1 +DA:203,3 +DA:205,1 +DA:206,1 +DA:207,1 +DA:216,81 +DA:226,6 +DA:232,6 +DA:233,6 +DA:235,6 +DA:236,6 +DA:238,0 +DA:239,0 +DA:242,0 +LF:83 +LH:80 +BRDA:46,0,0,1 +BRDA:46,0,1,22 +BRDA:46,1,0,22 +BRDA:46,1,1,11 +BRDA:50,2,0,2 +BRDA:50,2,1,21 +BRDA:51,3,0,4 +BRDA:51,3,1,17 +BRDA:83,4,0,23 +BRDA:83,4,1,21 +BRDA:83,4,2,20 +BRDA:85,5,0,4 +BRDA:85,5,1,16 +BRDA:87,6,0,2 +BRDA:87,6,1,2 +BRDA:94,7,0,1 +BRDA:94,7,1,19 +BRDA:102,8,0,4 +BRDA:102,8,1,19 +BRDA:121,9,0,1 +BRDA:121,9,1,22 +BRDA:166,10,0,4 +BRDA:166,10,1,28 +BRDA:166,11,0,32 +BRDA:166,11,1,32 +BRDA:171,12,0,3 +BRDA:171,12,1,29 +BRDA:171,13,0,23 +BRDA:171,13,1,6 +BRDA:196,14,0,3 +BRDA:196,14,1,1 +BRDA:196,15,0,4 +BRDA:196,15,1,3 +BRDA:201,16,0,1 +BRDA:201,16,1,1 +BRDA:206,17,0,1 +BRDA:206,17,1,0 +BRDA:232,18,0,6 +BRDA:232,18,1,0 +BRDA:232,19,0,6 +BRDA:232,19,1,6 +BRDA:238,20,0,0 +BRDA:238,20,1,0 +BRDA:238,21,0,0 +BRDA:238,21,1,0 +BRDA:250,22,0,0 +BRDA:250,22,1,6 +BRF:47 +BRH:40 +end_of_record +TN: +SF:/home/davidbau/git/seedrandom/lib/alea.js +FN:28,(anonymous_0) +FN:30,Alea +FN:33,(anonymous_2) +FN:54,copy +FN:62,impl +FN:66,(anonymous_5) +FN:67,(anonymous_6) +FN:73,(anonymous_7) +FN:78,Mash +FN:81,(anonymous_9) +FN:103,(anonymous_10) +FNF:11 +FNH:10 +FNDA:1,(anonymous_0) +FNDA:3,Alea +FNDA:4105129,(anonymous_2) +FNDA:2,copy +FNDA:3,impl +FNDA:1025,(anonymous_5) +FNDA:1025,(anonymous_6) +FNDA:1,(anonymous_7) +FNDA:3,Mash +FNDA:18,(anonymous_9) +FNDA:0,(anonymous_10) +DA:28,1 +DA:31,3 +DA:33,3 +DA:34,4105129 +DA:35,4105129 +DA:36,4105129 +DA:37,4105129 +DA:41,3 +DA:42,3 +DA:43,3 +DA:44,3 +DA:45,3 +DA:46,3 +DA:47,3 +DA:48,3 +DA:49,3 +DA:50,3 +DA:51,3 +DA:55,2 +DA:56,2 +DA:57,2 +DA:58,2 +DA:59,2 +DA:63,3 +DA:64,3 +DA:65,3 +DA:66,1025 +DA:67,3 +DA:68,1025 +DA:70,3 +DA:71,3 +DA:72,2 +DA:73,2 +DA:75,3 +DA:79,3 +DA:81,3 +DA:82,18 +DA:83,18 +DA:84,33 +DA:85,33 +DA:86,33 +DA:87,33 +DA:88,33 +DA:89,33 +DA:90,33 +DA:91,33 +DA:93,18 +DA:96,3 +DA:100,1 +DA:101,1 +DA:102,0 +DA:103,0 +DA:105,0 +LF:53 +LH:50 +BRDA:46,0,0,1 +BRDA:46,0,1,2 +BRDA:48,1,0,3 +BRDA:48,1,1,0 +BRDA:50,2,0,0 +BRDA:50,2,1,3 +BRDA:64,3,0,3 +BRDA:64,3,1,2 +BRDA:71,4,0,2 +BRDA:71,4,1,1 +BRDA:72,5,0,1 +BRDA:72,5,1,1 +BRDA:100,6,0,1 +BRDA:100,6,1,0 +BRDA:100,7,0,1 +BRDA:100,7,1,1 +BRDA:102,8,0,0 +BRDA:102,8,1,0 +BRDA:102,9,0,0 +BRDA:102,9,1,0 +BRDA:110,10,0,1 +BRDA:110,10,1,1 +BRDA:111,11,0,1 +BRDA:111,11,1,0 +BRF:24 +BRH:16 +end_of_record +TN: +SF:/home/davidbau/git/seedrandom/lib/tychei.js +FN:5,(anonymous_0) +FN:7,XorGen +FN:11,(anonymous_2) +FN:60,copy +FN:68,impl +FN:71,(anonymous_5) +FN:72,(anonymous_6) +FN:84,(anonymous_7) +FN:92,(anonymous_8) +FNF:9 +FNH:8 +FNDA:1,(anonymous_0) +FNDA:3,XorGen +FNDA:4105195,(anonymous_2) +FNDA:2,copy +FNDA:3,impl +FNDA:4102054,(anonymous_5) +FNDA:1025,(anonymous_6) +FNDA:1,(anonymous_7) +FNDA:0,(anonymous_8) +DA:5,1 +DA:8,3 +DA:11,3 +DA:12,4105195 +DA:13,4105195 +DA:14,4105195 +DA:15,4105195 +DA:16,4105195 +DA:17,4105195 +DA:18,4105195 +DA:19,4105195 +DA:20,4105195 +DA:39,3 +DA:40,3 +DA:41,3 +DA:42,3 +DA:44,3 +DA:46,2 +DA:47,2 +DA:50,1 +DA:54,3 +DA:55,66 +DA:56,66 +DA:61,2 +DA:62,2 +DA:63,2 +DA:64,2 +DA:65,2 +DA:69,3 +DA:70,3 +DA:71,4102054 +DA:72,3 +DA:73,1025 +DA:74,1025 +DA:75,1025 +DA:76,1025 +DA:78,1025 +DA:80,3 +DA:81,3 +DA:82,3 +DA:83,2 +DA:84,2 +DA:86,3 +DA:89,1 +DA:90,1 +DA:91,0 +DA:92,0 +DA:94,0 +LF:48 +LH:45 +BRDA:44,0,0,2 +BRDA:44,0,1,1 +BRDA:70,1,0,3 +BRDA:70,1,1,2 +BRDA:82,2,0,2 +BRDA:82,2,1,1 +BRDA:83,3,0,1 +BRDA:83,3,1,1 +BRDA:89,4,0,1 +BRDA:89,4,1,0 +BRDA:89,5,0,1 +BRDA:89,5,1,1 +BRDA:91,6,0,0 +BRDA:91,6,1,0 +BRDA:91,7,0,0 +BRDA:91,7,1,0 +BRDA:99,8,0,1 +BRDA:99,8,1,1 +BRDA:100,9,0,1 +BRDA:100,9,1,0 +BRF:20 +BRH:14 +end_of_record +TN: +SF:/home/davidbau/git/seedrandom/lib/xor128.js +FN:4,(anonymous_0) +FN:6,XorGen +FN:15,(anonymous_2) +FN:38,copy +FN:46,impl +FN:49,(anonymous_5) +FN:50,(anonymous_6) +FN:62,(anonymous_7) +FN:70,(anonymous_8) +FNF:9 +FNH:8 +FNDA:1,(anonymous_0) +FNDA:3,XorGen +FNDA:4105327,(anonymous_2) +FNDA:2,copy +FNDA:3,impl +FNDA:4102054,(anonymous_5) +FNDA:1025,(anonymous_6) +FNDA:1,(anonymous_7) +FNDA:0,(anonymous_8) +DA:4,1 +DA:7,3 +DA:9,3 +DA:10,3 +DA:11,3 +DA:12,3 +DA:15,3 +DA:16,4105327 +DA:17,4105327 +DA:18,4105327 +DA:19,4105327 +DA:20,4105327 +DA:23,3 +DA:25,2 +DA:28,1 +DA:32,3 +DA:33,198 +DA:34,198 +DA:39,2 +DA:40,2 +DA:41,2 +DA:42,2 +DA:43,2 +DA:47,3 +DA:48,3 +DA:49,4102054 +DA:50,3 +DA:51,1025 +DA:52,1025 +DA:53,1025 +DA:54,1025 +DA:56,1025 +DA:58,3 +DA:59,3 +DA:60,3 +DA:61,2 +DA:62,2 +DA:64,3 +DA:67,1 +DA:68,1 +DA:69,0 +DA:70,0 +DA:72,0 +LF:43 +LH:40 +BRDA:23,0,0,2 +BRDA:23,0,1,1 +BRDA:48,1,0,3 +BRDA:48,1,1,2 +BRDA:60,2,0,2 +BRDA:60,2,1,1 +BRDA:61,3,0,1 +BRDA:61,3,1,1 +BRDA:67,4,0,1 +BRDA:67,4,1,0 +BRDA:67,5,0,1 +BRDA:67,5,1,1 +BRDA:69,6,0,0 +BRDA:69,6,1,0 +BRDA:69,7,0,0 +BRDA:69,7,1,0 +BRDA:77,8,0,1 +BRDA:77,8,1,1 +BRDA:78,9,0,1 +BRDA:78,9,1,0 +BRF:20 +BRH:14 +end_of_record +TN: +SF:/home/davidbau/git/seedrandom/lib/xor4096.js +FN:26,(anonymous_0) +FN:28,XorGen +FN:32,(anonymous_2) +FN:51,init +FN:105,copy +FN:112,impl +FN:116,(anonymous_6) +FN:117,(anonymous_7) +FN:129,(anonymous_8) +FN:137,(anonymous_9) +FNF:10 +FNH:9 +FNDA:1,(anonymous_0) +FNDA:3,XorGen +FNDA:4105129,(anonymous_2) +FNDA:3,init +FNDA:2,copy +FNDA:3,impl +FNDA:4102054,(anonymous_6) +FNDA:1025,(anonymous_7) +FNDA:1,(anonymous_8) +FNDA:0,(anonymous_9) +DA:26,1 +DA:29,3 +DA:32,3 +DA:33,4105129 +DA:34,4105129 +DA:36,4105129 +DA:38,4105129 +DA:39,4105129 +DA:40,4105129 +DA:41,4105129 +DA:42,4105129 +DA:43,4105129 +DA:45,4105129 +DA:46,4105129 +DA:48,4105129 +DA:52,3 +DA:53,3 +DA:55,2 +DA:56,2 +DA:59,1 +DA:60,1 +DA:61,1 +DA:64,3 +DA:66,480 +DA:68,480 +DA:69,480 +DA:70,480 +DA:71,480 +DA:72,480 +DA:73,480 +DA:74,384 +DA:75,384 +DA:76,384 +DA:80,3 +DA:81,0 +DA:86,3 +DA:87,3 +DA:88,1536 +DA:89,1536 +DA:90,1536 +DA:91,1536 +DA:92,1536 +DA:93,1536 +DA:94,1536 +DA:97,3 +DA:98,3 +DA:99,3 +DA:102,3 +DA:106,2 +DA:107,2 +DA:108,2 +DA:109,2 +DA:113,3 +DA:114,3 +DA:115,3 +DA:116,4102054 +DA:117,3 +DA:118,1025 +DA:119,1025 +DA:120,1025 +DA:121,1025 +DA:123,1025 +DA:125,3 +DA:126,3 +DA:127,3 +DA:128,2 +DA:129,2 +DA:131,3 +DA:134,1 +DA:135,1 +DA:136,0 +DA:137,0 +DA:139,0 +LF:73 +LH:69 +BRDA:53,0,0,2 +BRDA:53,0,1,1 +BRDA:66,1,0,160 +BRDA:66,1,1,320 +BRDA:68,2,0,3 +BRDA:68,2,1,477 +BRDA:73,3,0,384 +BRDA:73,3,1,96 +BRDA:76,4,0,0 +BRDA:76,4,1,384 +BRDA:80,5,0,0 +BRDA:80,5,1,3 +BRDA:81,6,0,0 +BRDA:81,6,1,0 +BRDA:81,6,2,0 +BRDA:113,7,0,0 +BRDA:113,7,1,3 +BRDA:115,8,0,3 +BRDA:115,8,1,2 +BRDA:127,9,0,2 +BRDA:127,9,1,1 +BRDA:128,10,0,1 +BRDA:128,10,1,1 +BRDA:134,11,0,1 +BRDA:134,11,1,0 +BRDA:134,12,0,1 +BRDA:134,12,1,1 +BRDA:136,13,0,0 +BRDA:136,13,1,0 +BRDA:136,14,0,0 +BRDA:136,14,1,0 +BRDA:144,15,0,1 +BRDA:144,15,1,1 +BRDA:145,16,0,1 +BRDA:145,16,1,0 +BRF:35 +BRH:23 +end_of_record +TN: +SF:/home/davidbau/git/seedrandom/lib/xorshift7.js +FN:6,(anonymous_0) +FN:8,XorGen +FN:12,(anonymous_2) +FN:25,init +FN:56,copy +FN:62,impl +FN:66,(anonymous_6) +FN:67,(anonymous_7) +FN:79,(anonymous_8) +FN:87,(anonymous_9) +FNF:10 +FNH:9 +FNDA:1,(anonymous_0) +FNDA:3,XorGen +FNDA:4105897,(anonymous_2) +FNDA:3,init +FNDA:2,copy +FNDA:3,impl +FNDA:4102054,(anonymous_6) +FNDA:1025,(anonymous_7) +FNDA:1,(anonymous_8) +FNDA:0,(anonymous_9) +DA:6,1 +DA:9,3 +DA:12,3 +DA:14,4105897 +DA:15,4105897 +DA:16,4105897 +DA:17,4105897 +DA:18,4105897 +DA:19,4105897 +DA:20,4105897 +DA:21,4105897 +DA:22,4105897 +DA:26,3 +DA:28,3 +DA:30,2 +DA:33,1 +DA:34,1 +DA:35,6 +DA:40,16 +DA:41,3 +DA:42,3 +DA:44,3 +DA:45,3 +DA:48,3 +DA:49,768 +DA:53,3 +DA:57,2 +DA:58,2 +DA:59,2 +DA:63,3 +DA:64,3 +DA:65,3 +DA:66,4102054 +DA:67,3 +DA:68,1025 +DA:69,1025 +DA:70,1025 +DA:71,1025 +DA:73,1025 +DA:75,3 +DA:76,3 +DA:77,3 +DA:78,2 +DA:79,2 +DA:81,3 +DA:84,1 +DA:85,1 +DA:86,0 +DA:87,0 +DA:89,0 +LF:50 +LH:47 +BRDA:28,0,0,2 +BRDA:28,0,1,1 +BRDA:41,1,0,19 +BRDA:41,1,1,17 +BRDA:42,2,0,2 +BRDA:42,2,1,1 +BRDA:63,3,0,0 +BRDA:63,3,1,3 +BRDA:65,4,0,3 +BRDA:65,4,1,2 +BRDA:77,5,0,2 +BRDA:77,5,1,1 +BRDA:78,6,0,1 +BRDA:78,6,1,1 +BRDA:84,7,0,1 +BRDA:84,7,1,0 +BRDA:84,8,0,1 +BRDA:84,8,1,1 +BRDA:86,9,0,0 +BRDA:86,9,1,0 +BRDA:86,10,0,0 +BRDA:86,10,1,0 +BRDA:94,11,0,1 +BRDA:94,11,1,1 +BRDA:95,12,0,1 +BRDA:95,12,1,0 +BRF:26 +BRH:19 +end_of_record +TN: +SF:/home/davidbau/git/seedrandom/lib/xorwow.js +FN:4,(anonymous_0) +FN:6,XorGen +FN:10,(anonymous_2) +FN:41,copy +FN:51,impl +FN:54,(anonymous_5) +FN:55,(anonymous_6) +FN:67,(anonymous_7) +FN:75,(anonymous_8) +FNF:9 +FNH:8 +FNDA:1,(anonymous_0) +FNDA:3,XorGen +FNDA:4105327,(anonymous_2) +FNDA:2,copy +FNDA:3,impl +FNDA:4102054,(anonymous_5) +FNDA:1025,(anonymous_6) +FNDA:1,(anonymous_7) +FNDA:0,(anonymous_8) +DA:4,1 +DA:7,3 +DA:10,3 +DA:11,4105327 +DA:12,4105327 +DA:13,4105327 +DA:17,3 +DA:18,3 +DA:19,3 +DA:20,3 +DA:21,3 +DA:23,3 +DA:25,2 +DA:28,1 +DA:32,3 +DA:33,198 +DA:34,198 +DA:35,3 +DA:37,198 +DA:42,2 +DA:43,2 +DA:44,2 +DA:45,2 +DA:46,2 +DA:47,2 +DA:48,2 +DA:52,3 +DA:53,3 +DA:54,4102054 +DA:55,3 +DA:56,1025 +DA:57,1025 +DA:58,1025 +DA:59,1025 +DA:61,1025 +DA:63,3 +DA:64,3 +DA:65,3 +DA:66,2 +DA:67,2 +DA:69,3 +DA:72,1 +DA:73,1 +DA:74,0 +DA:75,0 +DA:77,0 +LF:46 +LH:43 +BRDA:23,0,0,2 +BRDA:23,0,1,1 +BRDA:34,1,0,3 +BRDA:34,1,1,195 +BRDA:53,2,0,3 +BRDA:53,2,1,2 +BRDA:65,3,0,2 +BRDA:65,3,1,1 +BRDA:66,4,0,1 +BRDA:66,4,1,1 +BRDA:72,5,0,1 +BRDA:72,5,1,0 +BRDA:72,6,0,1 +BRDA:72,6,1,1 +BRDA:74,7,0,0 +BRDA:74,7,1,0 +BRDA:74,8,0,0 +BRDA:74,8,1,0 +BRDA:82,9,0,1 +BRDA:82,9,1,1 +BRDA:83,10,0,1 +BRDA:83,10,1,0 +BRF:22 +BRH:16 +end_of_record diff --git a/node_modules/seedrandom/index.js b/node_modules/seedrandom/index.js new file mode 100644 index 0000000..513669a --- /dev/null +++ b/node_modules/seedrandom/index.js @@ -0,0 +1,60 @@ +// A library of seedable RNGs implemented in Javascript. +// +// Usage: +// +// var seedrandom = require('seedrandom'); +// var random = seedrandom(1); // or any seed. +// var x = random(); // 0 <= x < 1. Every bit is random. +// var x = random.quick(); // 0 <= x < 1. 32 bits of randomness. + +// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe. +// Period: ~2^116 +// Reported to pass all BigCrush tests. +var alea = require('./lib/alea'); + +// xor128, a pure xor-shift generator by George Marsaglia. +// Period: 2^128-1. +// Reported to fail: MatrixRank and LinearComp. +var xor128 = require('./lib/xor128'); + +// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl. +// Period: 2^192-2^32 +// Reported to fail: CollisionOver, SimpPoker, and LinearComp. +var xorwow = require('./lib/xorwow'); + +// xorshift7, by François Panneton and Pierre L'ecuyer, takes +// a different approach: it adds robustness by allowing more shifts +// than Marsaglia's original three. It is a 7-shift generator +// with 256 bits, that passes BigCrush with no systmatic failures. +// Period 2^256-1. +// No systematic BigCrush failures reported. +var xorshift7 = require('./lib/xorshift7'); + +// xor4096, by Richard Brent, is a 4096-bit xor-shift with a +// very long period that also adds a Weyl generator. It also passes +// BigCrush with no systematic failures. Its long period may +// be useful if you have many generators and need to avoid +// collisions. +// Period: 2^4128-2^32. +// No systematic BigCrush failures reported. +var xor4096 = require('./lib/xor4096'); + +// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random +// number generator derived from ChaCha, a modern stream cipher. +// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf +// Period: ~2^127 +// No systematic BigCrush failures reported. +var tychei = require('./lib/tychei'); + +// The original ARC4-based prng included in this library. +// Period: ~2^1600 +var sr = require('./seedrandom'); + +sr.alea = alea; +sr.xor128 = xor128; +sr.xorwow = xorwow; +sr.xorshift7 = xorshift7; +sr.xor4096 = xor4096; +sr.tychei = tychei; + +module.exports = sr; diff --git a/node_modules/seedrandom/lib/alea.js b/node_modules/seedrandom/lib/alea.js new file mode 100644 index 0000000..478b956 --- /dev/null +++ b/node_modules/seedrandom/lib/alea.js @@ -0,0 +1,114 @@ +// A port of an algorithm by Johannes Baagøe , 2010 +// http://baagoe.com/en/RandomMusings/javascript/ +// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror +// Original work is under MIT license - + +// Copyright (C) 2010 by Johannes Baagøe +// +// 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. + + + +(function(global, module, define) { + +function Alea(seed) { + var me = this, mash = Mash(); + + me.next = function() { + var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32 + me.s0 = me.s1; + me.s1 = me.s2; + return me.s2 = t - (me.c = t | 0); + }; + + // Apply the seeding algorithm from Baagoe. + me.c = 1; + me.s0 = mash(' '); + me.s1 = mash(' '); + me.s2 = mash(' '); + me.s0 -= mash(seed); + if (me.s0 < 0) { me.s0 += 1; } + me.s1 -= mash(seed); + if (me.s1 < 0) { me.s1 += 1; } + me.s2 -= mash(seed); + if (me.s2 < 0) { me.s2 += 1; } + mash = null; +} + +function copy(f, t) { + t.c = f.c; + t.s0 = f.s0; + t.s1 = f.s1; + t.s2 = f.s2; + return t; +} + +function impl(seed, opts) { + var xg = new Alea(seed), + state = opts && opts.state, + prng = xg.next; + prng.int32 = function() { return (xg.next() * 0x100000000) | 0; } + prng.double = function() { + return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 + }; + prng.quick = prng; + if (state) { + if (typeof(state) == 'object') copy(state, xg); + prng.state = function() { return copy(xg, {}); } + } + return prng; +} + +function Mash() { + var n = 0xefc8249d; + + var mash = function(data) { + data = String(data); + for (var i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + var h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000; // 2^32 + } + return (n >>> 0) * 2.3283064365386963e-10; // 2^-32 + }; + + return mash; +} + + +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.alea = impl; +} + +})( + this, + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); + + diff --git a/node_modules/seedrandom/lib/alea.min.js b/node_modules/seedrandom/lib/alea.min.js new file mode 100644 index 0000000..be30a46 --- /dev/null +++ b/node_modules/seedrandom/lib/alea.min.js @@ -0,0 +1 @@ +!function(n,t,e){function u(n){var t=this,e=function(){var s=4022871197;return function(n){n=String(n);for(var t=0;t>>0,s=(e*=s)>>>0,s+=4294967296*(e-=s)}return 2.3283064365386963e-10*(s>>>0)}}();t.next=function(){var n=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=n-(t.c=0|n)},t.c=1,t.s0=e(" "),t.s1=e(" "),t.s2=e(" "),t.s0-=e(n),t.s0<0&&(t.s0+=1),t.s1-=e(n),t.s1<0&&(t.s1+=1),t.s2-=e(n),t.s2<0&&(t.s2+=1),e=null}function o(n,t){return t.c=n.c,t.s0=n.s0,t.s1=n.s1,t.s2=n.s2,t}function s(n,t){var e=new u(n),s=t&&t.state,r=e.next;return r.int32=function(){return 4294967296*e.next()|0},r.double=function(){return r()+11102230246251565e-32*(2097152*r()|0)},r.quick=r,s&&("object"==typeof s&&o(s,e),r.state=function(){return o(e,{})}),r}t&&t.exports?t.exports=s:e&&e.amd?e(function(){return s}):this.alea=s}(0,"object"==typeof module&&module,"function"==typeof define&&define); \ No newline at end of file diff --git a/node_modules/seedrandom/lib/crypto.js b/node_modules/seedrandom/lib/crypto.js new file mode 100644 index 0000000..18ee91f --- /dev/null +++ b/node_modules/seedrandom/lib/crypto.js @@ -0,0 +1,11 @@ +// mimic a subset of node's crypto API for the browser + +function randomBytes(width) { + var out = new Uint8Array(width); + (global.crypto || global.msCrypto).getRandomValues(out); + return out; +} + +module.exports = { + randomBytes: randomBytes +} diff --git a/node_modules/seedrandom/lib/tychei.js b/node_modules/seedrandom/lib/tychei.js new file mode 100644 index 0000000..3d0ddd4 --- /dev/null +++ b/node_modules/seedrandom/lib/tychei.js @@ -0,0 +1,103 @@ +// A Javascript implementaion of the "Tyche-i" prng algorithm by +// Samuel Neves and Filipe Araujo. +// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf + +(function(global, module, define) { + +function XorGen(seed) { + var me = this, strseed = ''; + + // Set up generator function. + me.next = function() { + var b = me.b, c = me.c, d = me.d, a = me.a; + b = (b << 25) ^ (b >>> 7) ^ c; + c = (c - d) | 0; + d = (d << 24) ^ (d >>> 8) ^ a; + a = (a - b) | 0; + me.b = b = (b << 20) ^ (b >>> 12) ^ c; + me.c = c = (c - d) | 0; + me.d = (d << 16) ^ (c >>> 16) ^ a; + return me.a = (a - b) | 0; + }; + + /* The following is non-inverted tyche, which has better internal + * bit diffusion, but which is about 25% slower than tyche-i in JS. + me.next = function() { + var a = me.a, b = me.b, c = me.c, d = me.d; + a = (me.a + me.b | 0) >>> 0; + d = me.d ^ a; d = d << 16 ^ d >>> 16; + c = me.c + d | 0; + b = me.b ^ c; b = b << 12 ^ d >>> 20; + me.a = a = a + b | 0; + d = d ^ a; me.d = d = d << 8 ^ d >>> 24; + me.c = c = c + d | 0; + b = b ^ c; + return me.b = (b << 7 ^ b >>> 25); + } + */ + + me.a = 0; + me.b = 0; + me.c = 2654435769 | 0; + me.d = 1367130551; + + if (seed === Math.floor(seed)) { + // Integer seed. + me.a = (seed / 0x100000000) | 0; + me.b = seed | 0; + } else { + // String seed. + strseed += seed; + } + + // Mix in string seed, then discard an initial batch of 64 values. + for (var k = 0; k < strseed.length + 20; k++) { + me.b ^= strseed.charCodeAt(k) | 0; + me.next(); + } +} + +function copy(f, t) { + t.a = f.a; + t.b = f.b; + t.c = f.c; + t.d = f.d; + return t; +}; + +function impl(seed, opts) { + var xg = new XorGen(seed), + state = opts && opts.state, + prng = function() { return (xg.next() >>> 0) / 0x100000000; }; + prng.double = function() { + do { + var top = xg.next() >>> 11, + bot = (xg.next() >>> 0) / 0x100000000, + result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof(state) == 'object') copy(state, xg); + prng.state = function() { return copy(xg, {}); } + } + return prng; +} + +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.tychei = impl; +} + +})( + this, + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); + + diff --git a/node_modules/seedrandom/lib/tychei.min.js b/node_modules/seedrandom/lib/tychei.min.js new file mode 100644 index 0000000..fa24abb --- /dev/null +++ b/node_modules/seedrandom/lib/tychei.min.js @@ -0,0 +1 @@ +!function(t,n,e){function u(t){var r=this,n="";r.next=function(){var t=r.b,n=r.c,e=r.d,o=r.a;return t=t<<25^t>>>7^n,n=n-e|0,e=e<<24^e>>>8^o,o=o-t|0,r.b=t=t<<20^t>>>12^n,r.c=n=n-e|0,r.d=e<<16^n>>>16^o,r.a=o-t|0},r.a=0,r.b=0,r.c=-1640531527,r.d=1367130551,t===Math.floor(t)?(r.a=t/4294967296|0,r.b=0|t):n+=t;for(var e=0;e>>0)/4294967296}var o=new u(t),r=n&&n.state;return e.double=function(){do{var t=((o.next()>>>11)+(o.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},e.int32=o.next,e.quick=e,r&&("object"==typeof r&&c(r,o),e.state=function(){return c(o,{})}),e}n&&n.exports?n.exports=o:e&&e.amd?e(function(){return o}):this.tychei=o}(0,"object"==typeof module&&module,"function"==typeof define&&define); \ No newline at end of file diff --git a/node_modules/seedrandom/lib/xor128.js b/node_modules/seedrandom/lib/xor128.js new file mode 100644 index 0000000..c461934 --- /dev/null +++ b/node_modules/seedrandom/lib/xor128.js @@ -0,0 +1,81 @@ +// A Javascript implementaion of the "xor128" prng algorithm by +// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper + +(function(global, module, define) { + +function XorGen(seed) { + var me = this, strseed = ''; + + me.x = 0; + me.y = 0; + me.z = 0; + me.w = 0; + + // Set up generator function. + me.next = function() { + var t = me.x ^ (me.x << 11); + me.x = me.y; + me.y = me.z; + me.z = me.w; + return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8); + }; + + if (seed === (seed | 0)) { + // Integer seed. + me.x = seed; + } else { + // String seed. + strseed += seed; + } + + // Mix in string seed, then discard an initial batch of 64 values. + for (var k = 0; k < strseed.length + 64; k++) { + me.x ^= strseed.charCodeAt(k) | 0; + me.next(); + } +} + +function copy(f, t) { + t.x = f.x; + t.y = f.y; + t.z = f.z; + t.w = f.w; + return t; +} + +function impl(seed, opts) { + var xg = new XorGen(seed), + state = opts && opts.state, + prng = function() { return (xg.next() >>> 0) / 0x100000000; }; + prng.double = function() { + do { + var top = xg.next() >>> 11, + bot = (xg.next() >>> 0) / 0x100000000, + result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof(state) == 'object') copy(state, xg); + prng.state = function() { return copy(xg, {}); } + } + return prng; +} + +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.xor128 = impl; +} + +})( + this, + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); + + diff --git a/node_modules/seedrandom/lib/xor128.min.js b/node_modules/seedrandom/lib/xor128.min.js new file mode 100644 index 0000000..bd60553 --- /dev/null +++ b/node_modules/seedrandom/lib/xor128.min.js @@ -0,0 +1 @@ +!function(t,n,e){function u(t){var n=this,e="";n.x=0,n.y=0,n.z=0,n.w=0,n.next=function(){var t=n.x^n.x<<11;return n.x=n.y,n.y=n.z,n.z=n.w,n.w^=n.w>>>19^t^t>>>8},t===(0|t)?n.x=t:e+=t;for(var o=0;o>>0)/4294967296}var o=new u(t),r=n&&n.state;return e.double=function(){do{var t=((o.next()>>>11)+(o.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},e.int32=o.next,e.quick=e,r&&("object"==typeof r&&i(r,o),e.state=function(){return i(o,{})}),e}n&&n.exports?n.exports=o:e&&e.amd?e(function(){return o}):this.xor128=o}(0,"object"==typeof module&&module,"function"==typeof define&&define); \ No newline at end of file diff --git a/node_modules/seedrandom/lib/xor4096.js b/node_modules/seedrandom/lib/xor4096.js new file mode 100644 index 0000000..6adf19f --- /dev/null +++ b/node_modules/seedrandom/lib/xor4096.js @@ -0,0 +1,146 @@ +// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm. +// +// This fast non-cryptographic random number generator is designed for +// use in Monte-Carlo algorithms. It combines a long-period xorshift +// generator with a Weyl generator, and it passes all common batteries +// of stasticial tests for randomness while consuming only a few nanoseconds +// for each prng generated. For background on the generator, see Brent's +// paper: "Some long-period random number generators using shifts and xors." +// http://arxiv.org/pdf/1004.3115v1.pdf +// +// Usage: +// +// var xor4096 = require('xor4096'); +// random = xor4096(1); // Seed with int32 or string. +// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits. +// assert.equal(random.int32(), 1806534897); // signed int32, 32 bits. +// +// For nonzero numeric keys, this impelementation provides a sequence +// identical to that by Brent's xorgens 3 implementaion in C. This +// implementation also provides for initalizing the generator with +// string seeds, or for saving and restoring the state of the generator. +// +// On Chrome, this prng benchmarks about 2.1 times slower than +// Javascript's built-in Math.random(). + +(function(global, module, define) { + +function XorGen(seed) { + var me = this; + + // Set up generator function. + me.next = function() { + var w = me.w, + X = me.X, i = me.i, t, v; + // Update Weyl generator. + me.w = w = (w + 0x61c88647) | 0; + // Update xor generator. + v = X[(i + 34) & 127]; + t = X[i = ((i + 1) & 127)]; + v ^= v << 13; + t ^= t << 17; + v ^= v >>> 15; + t ^= t >>> 12; + // Update Xor generator array state. + v = X[i] = v ^ t; + me.i = i; + // Result is the combination. + return (v + (w ^ (w >>> 16))) | 0; + }; + + function init(me, seed) { + var t, v, i, j, w, X = [], limit = 128; + if (seed === (seed | 0)) { + // Numeric seeds initialize v, which is used to generates X. + v = seed; + seed = null; + } else { + // String seeds are mixed into v and X one character at a time. + seed = seed + '\0'; + v = 0; + limit = Math.max(limit, seed.length); + } + // Initialize circular array and weyl value. + for (i = 0, j = -32; j < limit; ++j) { + // Put the unicode characters into the array, and shuffle them. + if (seed) v ^= seed.charCodeAt((j + 32) % seed.length); + // After 32 shuffles, take v as the starting w value. + if (j === 0) w = v; + v ^= v << 10; + v ^= v >>> 15; + v ^= v << 4; + v ^= v >>> 13; + if (j >= 0) { + w = (w + 0x61c88647) | 0; // Weyl. + t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array. + i = (0 == t) ? i + 1 : 0; // Count zeroes. + } + } + // We have detected all zeroes; make the key nonzero. + if (i >= 128) { + X[(seed && seed.length || 0) & 127] = -1; + } + // Run the generator 512 times to further mix the state before using it. + // Factoring this as a function slows the main generator, so it is just + // unrolled here. The weyl generator is not advanced while warming up. + i = 127; + for (j = 4 * 128; j > 0; --j) { + v = X[(i + 34) & 127]; + t = X[i = ((i + 1) & 127)]; + v ^= v << 13; + t ^= t << 17; + v ^= v >>> 15; + t ^= t >>> 12; + X[i] = v ^ t; + } + // Storing state as object members is faster than using closure variables. + me.w = w; + me.X = X; + me.i = i; + } + + init(me, seed); +} + +function copy(f, t) { + t.i = f.i; + t.w = f.w; + t.X = f.X.slice(); + return t; +}; + +function impl(seed, opts) { + if (seed == null) seed = +(new Date); + var xg = new XorGen(seed), + state = opts && opts.state, + prng = function() { return (xg.next() >>> 0) / 0x100000000; }; + prng.double = function() { + do { + var top = xg.next() >>> 11, + bot = (xg.next() >>> 0) / 0x100000000, + result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (state.X) copy(state, xg); + prng.state = function() { return copy(xg, {}); } + } + return prng; +} + +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.xor4096 = impl; +} + +})( + this, // window object or global + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); diff --git a/node_modules/seedrandom/lib/xor4096.min.js b/node_modules/seedrandom/lib/xor4096.min.js new file mode 100644 index 0000000..fee9f8a --- /dev/null +++ b/node_modules/seedrandom/lib/xor4096.min.js @@ -0,0 +1 @@ +!function(n,t,e){function o(n){var o=this;o.next=function(){var n,t,e=o.w,r=o.X,i=o.i;return o.w=e=e+1640531527|0,t=r[i+34&127],n=r[i=i+1&127],t^=t<<13,n^=n<<17,t^=t>>>15,n^=n>>>12,t=r[i]=t^n,o.i=i,t+(e^e>>>16)|0},function(n,t){var e,r,i,o,u,f=[],c=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,c=Math.max(c,t.length)),i=0,o=-32;o>>15,r^=r<<4,r^=r>>>13,0<=o&&(u=u+1640531527|0,i=0==(e=f[127&o]^=r+u)?i+1:0);for(128<=i&&(f[127&(t&&t.length||0)]=-1),i=127,o=512;0>>15,e^=e>>>12,f[i]=r^e;n.w=u,n.X=f,n.i=i}(o,n)}function u(n,t){return t.i=n.i,t.w=n.w,t.X=n.X.slice(),t}function r(n,t){null==n&&(n=+new Date);function e(){return(r.next()>>>0)/4294967296}var r=new o(n),i=t&&t.state;return e.double=function(){do{var n=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===n);return n},e.int32=r.next,e.quick=e,i&&(i.X&&u(i,r),e.state=function(){return u(r,{})}),e}t&&t.exports?t.exports=r:e&&e.amd?e(function(){return r}):this.xor4096=r}(0,"object"==typeof module&&module,"function"==typeof define&&define); \ No newline at end of file diff --git a/node_modules/seedrandom/lib/xorshift7.js b/node_modules/seedrandom/lib/xorshift7.js new file mode 100644 index 0000000..b7e5151 --- /dev/null +++ b/node_modules/seedrandom/lib/xorshift7.js @@ -0,0 +1,97 @@ +// A Javascript implementaion of the "xorshift7" algorithm by +// François Panneton and Pierre L'ecuyer: +// "On the Xorgshift Random Number Generators" +// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf + +(function(global, module, define) { + +function XorGen(seed) { + var me = this; + + // Set up generator function. + me.next = function() { + // Update xor generator. + var X = me.x, i = me.i, t, v, w; + t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24); + t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10); + t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3); + t = X[(i + 4) & 7]; v ^= t ^ (t << 7); + t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9); + X[i] = v; + me.i = (i + 1) & 7; + return v; + }; + + function init(me, seed) { + var j, w, X = []; + + if (seed === (seed | 0)) { + // Seed state array using a 32-bit integer. + w = X[0] = seed; + } else { + // Seed state using a string. + seed = '' + seed; + for (j = 0; j < seed.length; ++j) { + X[j & 7] = (X[j & 7] << 15) ^ + (seed.charCodeAt(j) + X[(j + 1) & 7] << 13); + } + } + // Enforce an array length of 8, not all zeroes. + while (X.length < 8) X.push(0); + for (j = 0; j < 8 && X[j] === 0; ++j); + if (j == 8) w = X[7] = -1; else w = X[j]; + + me.x = X; + me.i = 0; + + // Discard an initial 256 values. + for (j = 256; j > 0; --j) { + me.next(); + } + } + + init(me, seed); +} + +function copy(f, t) { + t.x = f.x.slice(); + t.i = f.i; + return t; +} + +function impl(seed, opts) { + if (seed == null) seed = +(new Date); + var xg = new XorGen(seed), + state = opts && opts.state, + prng = function() { return (xg.next() >>> 0) / 0x100000000; }; + prng.double = function() { + do { + var top = xg.next() >>> 11, + bot = (xg.next() >>> 0) / 0x100000000, + result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (state.x) copy(state, xg); + prng.state = function() { return copy(xg, {}); } + } + return prng; +} + +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.xorshift7 = impl; +} + +})( + this, + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); + diff --git a/node_modules/seedrandom/lib/xorshift7.min.js b/node_modules/seedrandom/lib/xorshift7.min.js new file mode 100644 index 0000000..c6db5f6 --- /dev/null +++ b/node_modules/seedrandom/lib/xorshift7.min.js @@ -0,0 +1 @@ +!function(n,t,e){function o(n){var i=this;i.next=function(){var n,t,e=i.x,r=i.i;return n=e[r],t=(n^=n>>>7)^n<<24,t^=(n=e[r+1&7])^n>>>10,t^=(n=e[r+3&7])^n>>>3,t^=(n=e[r+4&7])^n<<7,n=e[r+7&7],t^=(n^=n<<13)^n<<9,e[r]=t,i.i=r+1&7,t},function(n,t){var e,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,e=0;e>>0)/4294967296}var r=new o(n),i=t&&t.state;return e.double=function(){do{var n=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===n);return n},e.int32=r.next,e.quick=e,i&&(i.x&&u(i,r),e.state=function(){return u(r,{})}),e}t&&t.exports?t.exports=r:e&&e.amd?e(function(){return r}):this.xorshift7=r}(0,"object"==typeof module&&module,"function"==typeof define&&define); \ No newline at end of file diff --git a/node_modules/seedrandom/lib/xorwow.js b/node_modules/seedrandom/lib/xorwow.js new file mode 100644 index 0000000..79d5e44 --- /dev/null +++ b/node_modules/seedrandom/lib/xorwow.js @@ -0,0 +1,86 @@ +// A Javascript implementaion of the "xorwow" prng algorithm by +// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper + +(function(global, module, define) { + +function XorGen(seed) { + var me = this, strseed = ''; + + // Set up generator function. + me.next = function() { + var t = (me.x ^ (me.x >>> 2)); + me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v; + return (me.d = (me.d + 362437 | 0)) + + (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0; + }; + + me.x = 0; + me.y = 0; + me.z = 0; + me.w = 0; + me.v = 0; + + if (seed === (seed | 0)) { + // Integer seed. + me.x = seed; + } else { + // String seed. + strseed += seed; + } + + // Mix in string seed, then discard an initial batch of 64 values. + for (var k = 0; k < strseed.length + 64; k++) { + me.x ^= strseed.charCodeAt(k) | 0; + if (k == strseed.length) { + me.d = me.x << 10 ^ me.x >>> 4; + } + me.next(); + } +} + +function copy(f, t) { + t.x = f.x; + t.y = f.y; + t.z = f.z; + t.w = f.w; + t.v = f.v; + t.d = f.d; + return t; +} + +function impl(seed, opts) { + var xg = new XorGen(seed), + state = opts && opts.state, + prng = function() { return (xg.next() >>> 0) / 0x100000000; }; + prng.double = function() { + do { + var top = xg.next() >>> 11, + bot = (xg.next() >>> 0) / 0x100000000, + result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof(state) == 'object') copy(state, xg); + prng.state = function() { return copy(xg, {}); } + } + return prng; +} + +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.xorwow = impl; +} + +})( + this, + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); + + diff --git a/node_modules/seedrandom/lib/xorwow.min.js b/node_modules/seedrandom/lib/xorwow.min.js new file mode 100644 index 0000000..be1c626 --- /dev/null +++ b/node_modules/seedrandom/lib/xorwow.min.js @@ -0,0 +1 @@ +!function(t,n,e){function u(t){var n=this,e="";n.next=function(){var t=n.x^n.x>>>2;return n.x=n.y,n.y=n.z,n.z=n.w,n.w=n.v,(n.d=n.d+362437|0)+(n.v=n.v^n.v<<4^t^t<<1)|0},n.x=0,n.y=0,n.z=0,n.w=0,t===((n.v=0)|t)?n.x=t:e+=t;for(var o=0;o>>4),n.next()}function x(t,n){return n.x=t.x,n.y=t.y,n.z=t.z,n.w=t.w,n.v=t.v,n.d=t.d,n}function o(t,n){function e(){return(o.next()>>>0)/4294967296}var o=new u(t),r=n&&n.state;return e.double=function(){do{var t=((o.next()>>>11)+(o.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},e.int32=o.next,e.quick=e,r&&("object"==typeof r&&x(r,o),e.state=function(){return x(o,{})}),e}n&&n.exports?n.exports=o:e&&e.amd?e(function(){return o}):this.xorwow=o}(0,"object"==typeof module&&module,"function"==typeof define&&define); \ No newline at end of file diff --git a/node_modules/seedrandom/package.json b/node_modules/seedrandom/package.json new file mode 100644 index 0000000..86aad13 --- /dev/null +++ b/node_modules/seedrandom/package.json @@ -0,0 +1,60 @@ +{ + "name": "seedrandom", + "version": "3.0.5", + "description": "Seeded random number generator for Javascript.", + "main": "index.js", + "jsdelivr": "seedrandom.min.js", + "unpkg": "seedrandom.min.js", + "keywords": [ + "seed", + "random", + "crypto" + ], + "scripts": { + "test": "grunt travis" + }, + "repository": { + "type": "git", + "url": "git://github.com/davidbau/seedrandom.git" + }, + "author": "David Bau", + "license": "MIT", + "bugs": { + "url": "https://github.com/davidbau/seedrandom/issues" + }, + "homepage": "http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html", + "config": { + "blanket": { + "pattern": [ + "seedrandom.js", + "lib/alea.js", + "lib/xor128.js", + "lib/xorwow.js", + "lib/xorshift7.js", + "lib/tychei.js", + "lib/xor4096.js" + ] + } + }, + "browser": { + "crypto": false + }, + "devDependencies": { + "blanket": "latest", + "coveralls": "latest", + "grunt": "latest", + "grunt-browserify": "latest", + "grunt-release": "davidbau/grunt-release", + "grunt-cli": "latest", + "grunt-contrib-connect": "latest", + "grunt-contrib-copy": "latest", + "grunt-contrib-qunit": "latest", + "grunt-contrib-uglify": "latest", + "grunt-mocha-nyc": "latest", + "mocha": "latest", + "nyc": "latest", + "proxyquire": "latest", + "qunit": "latest", + "requirejs": "latest" + } +} diff --git a/node_modules/seedrandom/seedrandom.js b/node_modules/seedrandom/seedrandom.js new file mode 100644 index 0000000..12d7ee1 --- /dev/null +++ b/node_modules/seedrandom/seedrandom.js @@ -0,0 +1,253 @@ +/* +Copyright 2019 David Bau. + +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. + +*/ + +(function (global, pool, math) { +// +// The following constants are related to IEEE 754 limits. +// + +var width = 256, // each RC4 output is 0 <= x < 256 + chunks = 6, // at least six RC4 outputs for each double + digits = 52, // there are 52 significant digits in a double + rngname = 'random', // rngname: name for Math.random and Math.seedrandom + startdenom = math.pow(width, chunks), + significance = math.pow(2, digits), + overflow = significance * 2, + mask = width - 1, + nodecrypto; // node.js crypto module, initialized at the bottom. + +// +// seedrandom() +// This is the seedrandom function described above. +// +function seedrandom(seed, options, callback) { + var key = []; + options = (options == true) ? { entropy: true } : (options || {}); + + // Flatten the seed string or build one from local entropy if needed. + var shortseed = mixkey(flatten( + options.entropy ? [seed, tostring(pool)] : + (seed == null) ? autoseed() : seed, 3), key); + + // Use the seed to initialize an ARC4 generator. + var arc4 = new ARC4(key); + + // This function returns a random double in [0, 1) that contains + // randomness in every bit of the mantissa of the IEEE 754 value. + var prng = function() { + var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48 + d = startdenom, // and denominator d = 2 ^ 48. + x = 0; // and no 'extra last byte'. + while (n < significance) { // Fill up all significant digits by + n = (n + x) * width; // shifting numerator and + d *= width; // denominator and generating a + x = arc4.g(1); // new least-significant-byte. + } + while (n >= overflow) { // To avoid rounding up, before adding + n /= 2; // last byte, shift everything + d /= 2; // right using integer math until + x >>>= 1; // we have exactly the desired bits. + } + return (n + x) / d; // Form the number within [0, 1). + }; + + prng.int32 = function() { return arc4.g(4) | 0; } + prng.quick = function() { return arc4.g(4) / 0x100000000; } + prng.double = prng; + + // Mix the randomness into accumulated entropy. + mixkey(tostring(arc4.S), pool); + + // Calling convention: what to return as a function of prng, seed, is_math. + return (options.pass || callback || + function(prng, seed, is_math_call, state) { + if (state) { + // Load the arc4 state from the given state if it has an S array. + if (state.S) { copy(state, arc4); } + // Only provide the .state method if requested via options.state. + prng.state = function() { return copy(arc4, {}); } + } + + // If called as a method of Math (Math.seedrandom()), mutate + // Math.random because that is how seedrandom.js has worked since v1.0. + if (is_math_call) { math[rngname] = prng; return seed; } + + // Otherwise, it is a newer calling convention, so return the + // prng directly. + else return prng; + })( + prng, + shortseed, + 'global' in options ? options.global : (this == math), + options.state); +} + +// +// ARC4 +// +// An ARC4 implementation. The constructor takes a key in the form of +// an array of at most (width) integers that should be 0 <= x < (width). +// +// The g(count) method returns a pseudorandom integer that concatenates +// the next (count) outputs from ARC4. Its return value is a number x +// that is in the range 0 <= x < (width ^ count). +// +function ARC4(key) { + var t, keylen = key.length, + me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; + + // The empty key [] is treated as [0]. + if (!keylen) { key = [keylen++]; } + + // Set up S using the standard key scheduling algorithm. + while (i < width) { + s[i] = i++; + } + for (i = 0; i < width; i++) { + s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))]; + s[j] = t; + } + + // The "g" method returns the next (count) outputs as one number. + (me.g = function(count) { + // Using instance members instead of closure state nearly doubles speed. + var t, r = 0, + i = me.i, j = me.j, s = me.S; + while (count--) { + t = s[i = mask & (i + 1)]; + r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))]; + } + me.i = i; me.j = j; + return r; + // For robust unpredictability, the function call below automatically + // discards an initial batch of values. This is called RC4-drop[256]. + // See http://google.com/search?q=rsa+fluhrer+response&btnI + })(width); +} + +// +// copy() +// Copies internal state of ARC4 to or from a plain object. +// +function copy(f, t) { + t.i = f.i; + t.j = f.j; + t.S = f.S.slice(); + return t; +}; + +// +// flatten() +// Converts an object tree to nested arrays of strings. +// +function flatten(obj, depth) { + var result = [], typ = (typeof obj), prop; + if (depth && typ == 'object') { + for (prop in obj) { + try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} + } + } + return (result.length ? result : typ == 'string' ? obj : obj + '\0'); +} + +// +// mixkey() +// Mixes a string seed into a key that is an array of integers, and +// returns a shortened string seed that is equivalent to the result key. +// +function mixkey(seed, key) { + var stringseed = seed + '', smear, j = 0; + while (j < stringseed.length) { + key[mask & j] = + mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++)); + } + return tostring(key); +} + +// +// autoseed() +// Returns an object for autoseeding, using window.crypto and Node crypto +// module if available. +// +function autoseed() { + try { + var out; + if (nodecrypto && (out = nodecrypto.randomBytes)) { + // The use of 'out' to remember randomBytes makes tight minified code. + out = out(width); + } else { + out = new Uint8Array(width); + (global.crypto || global.msCrypto).getRandomValues(out); + } + return tostring(out); + } catch (e) { + var browser = global.navigator, + plugins = browser && browser.plugins; + return [+new Date, global, plugins, global.screen, tostring(pool)]; + } +} + +// +// tostring() +// Converts an array of charcodes to a string +// +function tostring(a) { + return String.fromCharCode.apply(0, a); +} + +// +// When seedrandom.js is loaded, we immediately mix a few bits +// from the built-in RNG into the entropy pool. Because we do +// not want to interfere with deterministic PRNG state later, +// seedrandom will not call math.random on its own again after +// initialization. +// +mixkey(math.random(), pool); + +// +// Nodejs and AMD support: export the implementation as a module using +// either convention. +// +if ((typeof module) == 'object' && module.exports) { + module.exports = seedrandom; + // When in node.js, try using crypto package for autoseeding. + try { + nodecrypto = require('crypto'); + } catch (ex) {} +} else if ((typeof define) == 'function' && define.amd) { + define(function() { return seedrandom; }); +} else { + // When included as a plain script, set up Math.seedrandom global. + math['seed' + rngname] = seedrandom; +} + + +// End anonymous scope, and pass initial values. +})( + // global: `self` in browsers (including strict mode and web workers), + // otherwise `this` in Node and other environments + (typeof self !== 'undefined') ? self : this, + [], // pool: entropy pool starts empty + Math // math: package containing random, pow, and seedrandom +); diff --git a/node_modules/seedrandom/seedrandom.min.js b/node_modules/seedrandom/seedrandom.min.js new file mode 100644 index 0000000..56e1afc --- /dev/null +++ b/node_modules/seedrandom/seedrandom.min.js @@ -0,0 +1 @@ +!function(f,a,c){var s,l=256,p="random",d=c.pow(l,6),g=c.pow(2,52),y=2*g,h=l-1;function n(n,t,r){function e(){for(var n=u.g(6),t=d,r=0;n>>=1;return(n+r)/t}var o=[],i=j(function n(t,r){var e,o=[],i=typeof t;if(r&&"object"==i)for(e in t)try{o.push(n(t[e],r-1))}catch(n){}return o.length?o:"string"==i?t:t+"\0"}((t=1==t?{entropy:!0}:t||{}).entropy?[n,S(a)]:null==n?function(){try{var n;return s&&(n=s.randomBytes)?n=n(l):(n=new Uint8Array(l),(f.crypto||f.msCrypto).getRandomValues(n)),S(n)}catch(n){var t=f.navigator,r=t&&t.plugins;return[+new Date,f,r,f.screen,S(a)]}}():n,3),o),u=new m(o);return e.int32=function(){return 0|u.g(4)},e.quick=function(){return u.g(4)/4294967296},e.double=e,j(S(u.S),a),(t.pass||r||function(n,t,r,e){return e&&(e.S&&v(e,u),n.state=function(){return v(u,{})}),r?(c[p]=n,t):n})(e,i,"global"in t?t.global:this==c,t.state)}function m(n){var t,r=n.length,u=this,e=0,o=u.i=u.j=0,i=u.S=[];for(r||(n=[r++]);e dist/tinyemitter.js -s TinyEmitter && echo 'Bundled'", + "minify": "node_modules/.bin/uglifyjs dist/tinyemitter.js -o dist/tinyemitter.min.js -m && echo 'Minified'", + "build": "npm test && npm run bundle && npm run minify", + "size": "node_modules/.bin/uglifyjs index.js -o minified.js -m && ls -l && rm minified.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/scottcorgan/tiny-emitter.git" + }, + "keywords": [ + "event", + "emitter", + "pubsub", + "tiny", + "events", + "bind" + ], + "author": "Scott Corgan", + "license": "MIT", + "bugs": { + "url": "https://github.com/scottcorgan/tiny-emitter/issues" + }, + "devDependencies": { + "@tap-format/spec": "0.2.0", + "browserify": "11.2.0", + "tape": "4.2.1", + "testling": "1.7.1", + "uglify-js": "2.5.0" + }, + "testling": { + "files": [ + "test/index.js" + ], + "browsers": [ + "iexplore/10.0", + "iexplore/9.0", + "firefox/16..latest", + "chrome/22..latest", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/tiny-emitter/test/index.js b/node_modules/tiny-emitter/test/index.js new file mode 100644 index 0000000..7f95f62 --- /dev/null +++ b/node_modules/tiny-emitter/test/index.js @@ -0,0 +1,217 @@ +var Emitter = require('../index'); +var emitter = require('../instance'); +var test = require('tape'); + +test('subscribes to an event', function (t) { + var emitter = new Emitter(); + emitter.on('test', function () {}); + + t.equal(emitter.e.test.length, 1, 'subscribed to event'); + t.end(); +}); + +test('subscribes to an event with context', function (t) { + var emitter = new Emitter(); + var context = { + contextValue: true + }; + + emitter.on('test', function () { + t.ok(this.contextValue, 'is in context'); + t.end(); + }, context); + + emitter.emit('test'); +}); + +test('subscibes only once to an event', function (t) { + var emitter = new Emitter(); + + emitter.once('test', function () { + t.notOk(emitter.e.test, 'removed event from list'); + t.end(); + }); + + emitter.emit('test'); +}); + +test('keeps context when subscribed only once', function (t) { + var emitter = new Emitter(); + var context = { + contextValue: true + }; + + emitter.once('test', function () { + t.ok(this.contextValue, 'is in context'); + t.notOk(emitter.e.test, 'not subscribed anymore'); + t.end(); + }, context); + + emitter.emit('test'); +}); + +test('emits an event', function (t) { + var emitter = new Emitter(); + + emitter.on('test', function () { + t.ok(true, 'triggered event'); + t.end(); + }); + + emitter.emit('test'); +}); + +test('passes all arguments to event listener', function (t) { + var emitter = new Emitter(); + + emitter.on('test', function (arg1, arg2) { + t.equal(arg1, 'arg1', 'passed the first argument'); + t.equal(arg2, 'arg2', 'passed the second argument'); + t.end(); + }); + + emitter.emit('test', 'arg1', 'arg2'); +}); + +test('unsubscribes from all events with name', function (t) { + var emitter = new Emitter(); + emitter.on('test', function () { + t.fail('should not get called'); + }); + emitter.off('test'); + emitter.emit('test') + + process.nextTick(function () { + t.end(); + }); +}); + +test('unsubscribes single event with name and callback', function (t) { + var emitter = new Emitter(); + var fn = function () { + t.fail('should not get called'); + } + + emitter.on('test', fn); + emitter.off('test', fn); + emitter.emit('test') + + process.nextTick(function () { + t.end(); + }); +}); + +// Test added by https://github.com/lazd +// From PR: https://github.com/scottcorgan/tiny-emitter/pull/6 +test('unsubscribes single event with name and callback when subscribed twice', function (t) { + var emitter = new Emitter(); + var fn = function () { + t.fail('should not get called'); + }; + + emitter.on('test', fn); + emitter.on('test', fn); + + emitter.off('test', fn); + emitter.emit('test'); + + process.nextTick(function () { + t.notOk(emitter.e['test'], 'removes all events'); + t.end(); + }); +}); + +test('unsubscribes single event with name and callback when subscribed twice out of order', function (t) { + var emitter = new Emitter(); + var calls = 0; + var fn = function () { + t.fail('should not get called'); + }; + var fn2 = function () { + calls++; + }; + + emitter.on('test', fn); + emitter.on('test', fn2); + emitter.on('test', fn); + emitter.off('test', fn); + emitter.emit('test'); + + process.nextTick(function () { + t.equal(calls, 1, 'callback was called'); + t.end(); + }); +}); + +test('removes an event inside another event', function (t) { + var emitter = new Emitter(); + + emitter.on('test', function () { + t.equal(emitter.e.test.length, 1, 'event is still in list'); + + emitter.off('test'); + + t.notOk(emitter.e.test, 0, 'event is gone from list'); + t.end(); + }); + + emitter.emit('test'); +}); + +test('event is emitted even if unsubscribed in the event callback', function (t) { + var emitter = new Emitter(); + var calls = 0; + var fn = function () { + calls += 1; + emitter.off('test', fn); + }; + + emitter.on('test', fn); + + emitter.on('test', function () { + calls += 1; + }); + + emitter.on('test', function () { + calls += 1; + }); + + process.nextTick(function () { + t.equal(calls, 3, 'all callbacks were called'); + t.end(); + }); + + emitter.emit('test'); +}); + +test('calling off before any events added does nothing', function (t) { + var emitter = new Emitter(); + emitter.off('test', function () {}); + t.end(); +}); + +test('emitting event that has not been subscribed to yet', function (t) { + var emitter = new Emitter(); + + emitter.emit('some-event', 'some message'); + t.end(); +}); + +test('unsubscribes single event with name and callback which was subscribed once', function (t) { + var emitter = new Emitter(); + var fn = function () { + t.fail('event not unsubscribed'); + } + + emitter.once('test', fn); + emitter.off('test', fn); + emitter.emit('test'); + + t.end(); +}); + +test('exports an instance', function (t) { + t.ok(emitter, 'exports an instance') + t.ok(emitter instanceof Emitter, 'an instance of the Emitter class'); + t.end(); +}); diff --git a/node_modules/tiny-emitter/yarn.lock b/node_modules/tiny-emitter/yarn.lock new file mode 100644 index 0000000..730a024 --- /dev/null +++ b/node_modules/tiny-emitter/yarn.lock @@ -0,0 +1,1857 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@tap-format/exit@0.2.0": + version "0.2.0" + resolved "https://registry.yarnpkg.com/@tap-format/exit/-/exit-0.2.0.tgz#b58736bc55d30802c012c5adfca51b47040310cd" + dependencies: + ramda "^0.18.0" + rx "^4.0.7" + +"@tap-format/failures@0.2.0": + version "0.2.0" + resolved "https://registry.yarnpkg.com/@tap-format/failures/-/failures-0.2.0.tgz#bb6f5edc3bc3c57c62885bc7c214cc7abdfc2a07" + dependencies: + chalk "^1.1.1" + diff "^2.2.1" + figures "^1.4.0" + ramda "^0.18.0" + rx "^4.0.7" + +"@tap-format/parser@0.2.0": + version "0.2.0" + resolved "https://registry.yarnpkg.com/@tap-format/parser/-/parser-0.2.0.tgz#bdc1d95e694781157593283bb3c3fec132a3115d" + dependencies: + duplexer "^0.1.1" + js-yaml "^3.4.6" + ramda "^0.18.0" + readable-stream "^2.0.4" + rx "^4.0.7" + rx-node "^1.0.1" + split "^1.0.0" + +"@tap-format/results@0.2.0": + version "0.2.0" + resolved "https://registry.yarnpkg.com/@tap-format/results/-/results-0.2.0.tgz#192d64ac41f146fa2722db1c0a22ed80478f54fd" + dependencies: + chalk "^1.1.1" + hirestime "^1.0.6" + pretty-ms "^2.1.0" + rx "^4.0.7" + +"@tap-format/spec@0.2.0": + version "0.2.0" + resolved "https://registry.yarnpkg.com/@tap-format/spec/-/spec-0.2.0.tgz#93f7d2f0dcefe526b4776800b9bd7f80db5aaec7" + dependencies: + "@tap-format/exit" "0.2.0" + "@tap-format/failures" "0.2.0" + "@tap-format/parser" "0.2.0" + "@tap-format/results" "0.2.0" + chalk "^1.1.1" + figures "^1.4.0" + rx "^4.0.7" + +Base64@~0.2.0: + version "0.2.1" + resolved "https://registry.yarnpkg.com/Base64/-/Base64-0.2.1.tgz#ba3a4230708e186705065e66babdd4c35cf60028" + +JSONStream@^1.0.3: + version "1.3.2" + resolved "https://registry.yarnpkg.com/JSONStream/-/JSONStream-1.3.2.tgz#c102371b6ec3a7cf3b847ca00c20bb0fce4c6dea" + dependencies: + jsonparse "^1.2.0" + through ">=2.2.7 <3" + +JSONStream@~0.6.4: + version "0.6.4" + resolved "https://registry.yarnpkg.com/JSONStream/-/JSONStream-0.6.4.tgz#4b2c8063f8f512787b2375f7ee9db69208fa2dcb" + dependencies: + jsonparse "0.0.5" + through "~2.2.7" + +JSONStream@~0.7.1: + version "0.7.4" + resolved "https://registry.yarnpkg.com/JSONStream/-/JSONStream-0.7.4.tgz#734290e41511eea7c2cfe151fbf9a563a97b9786" + dependencies: + jsonparse "0.0.5" + through ">=2.2.7 <3" + +acorn-node@^1.2.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/acorn-node/-/acorn-node-1.3.0.tgz#5f86d73346743810ef1269b901dbcbded020861b" + dependencies: + acorn "^5.4.1" + xtend "^4.0.1" + +acorn@^2.7.0: + version "2.7.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-2.7.0.tgz#ab6e7d9d886aaca8b085bc3312b79a198433f0e7" + +acorn@^4.0.3: + version "4.0.13" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-4.0.13.tgz#105495ae5361d697bd195c825192e1ad7f253787" + +acorn@^5.2.1, acorn@^5.4.1: + version "5.4.1" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-5.4.1.tgz#fdc58d9d17f4a4e98d102ded826a9b9759125102" + +amdefine@>=0.0.4: + version "1.0.1" + resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5" + +ansi-regex@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" + +ansi-styles@^2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" + +argparse@^1.0.7: + version "1.0.10" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" + dependencies: + sprintf-js "~1.0.2" + +asn1.js@^4.0.0: + version "4.10.1" + resolved "https://registry.yarnpkg.com/asn1.js/-/asn1.js-4.10.1.tgz#b9c2bf5805f1e64aadeed6df3a2bfafb5a73f5a0" + dependencies: + bn.js "^4.0.0" + inherits "^2.0.1" + minimalistic-assert "^1.0.0" + +assert@~1.1.0: + version "1.1.2" + resolved "https://registry.yarnpkg.com/assert/-/assert-1.1.2.tgz#adaa04c46bb58c6dd1f294da3eb26e6228eb6e44" + dependencies: + util "0.10.3" + +assert@~1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/assert/-/assert-1.3.0.tgz#03939a622582a812cc202320a0b9a56c9b815849" + dependencies: + util "0.10.3" + +astw@^2.0.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/astw/-/astw-2.2.0.tgz#7bd41784d32493987aeb239b6b4e1c57a873b917" + dependencies: + acorn "^4.0.3" + +async@~0.2.6: + version "0.2.10" + resolved "https://registry.yarnpkg.com/async/-/async-0.2.10.tgz#b6bbe0b0674b9d719708ca38de8c237cb526c3d1" + +balanced-match@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" + +base64-js@0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-0.0.2.tgz#024f0f72afa25b75f9c0ee73cd4f55ec1bed9784" + +base64-js@0.0.8, base64-js@~0.0.4: + version "0.0.8" + resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-0.0.8.tgz#1101e9544f4a76b1bc3b26d452ca96d7a35e7978" + +bn.js@^4.0.0, bn.js@^4.1.0, bn.js@^4.1.1, bn.js@^4.4.0: + version "4.11.8" + resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-4.11.8.tgz#2cde09eb5ee341f484746bb0309b3253b1b1442f" + +bops@0.0.6: + version "0.0.6" + resolved "https://registry.yarnpkg.com/bops/-/bops-0.0.6.tgz#082d1d55fa01e60dbdc2ebc2dba37f659554cf3a" + dependencies: + base64-js "0.0.2" + to-utf8 "0.0.1" + +bouncy@~3.2.0: + version "3.2.2" + resolved "https://registry.yarnpkg.com/bouncy/-/bouncy-3.2.2.tgz#82ab4ad7beae05890eed54b9af3c45394b185dc7" + dependencies: + optimist "~0.3.5" + through "~2.3.4" + +brace-expansion@^1.0.0, brace-expansion@^1.1.7: + version "1.1.11" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" + dependencies: + balanced-match "^1.0.0" + concat-map "0.0.1" + +brorand@^1.0.1: + version "1.1.0" + resolved "https://registry.yarnpkg.com/brorand/-/brorand-1.1.0.tgz#12c25efe40a45e3c323eb8675a0a0ce57b22371f" + +browser-launcher@~0.3.2: + version "0.3.5" + resolved "https://registry.yarnpkg.com/browser-launcher/-/browser-launcher-0.3.5.tgz#d9a3663fa064d8155044991c00e61dbcb6730a16" + dependencies: + headless "~0.1.3" + merge "~1.0.0" + minimist "0.0.5" + mkdirp "~0.3.3" + plist "0.2.1" + xtend "^4.0.0" + +browser-pack@^5.0.0: + version "5.0.1" + resolved "https://registry.yarnpkg.com/browser-pack/-/browser-pack-5.0.1.tgz#4197719b20c6e0aaa09451c5111e53efb6fbc18d" + dependencies: + JSONStream "^1.0.3" + combine-source-map "~0.6.1" + defined "^1.0.0" + through2 "^1.0.0" + umd "^3.0.0" + +browser-pack@~2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/browser-pack/-/browser-pack-2.0.1.tgz#5d1c527f56c582677411c4db2a128648ff6bf150" + dependencies: + JSONStream "~0.6.4" + combine-source-map "~0.3.0" + through "~2.3.4" + +browser-resolve@^1.7.0, browser-resolve@^1.7.1: + version "1.11.2" + resolved "https://registry.yarnpkg.com/browser-resolve/-/browser-resolve-1.11.2.tgz#8ff09b0a2c421718a1051c260b32e48f442938ce" + dependencies: + resolve "1.1.7" + +browser-resolve@~1.2.1, browser-resolve@~1.2.4: + version "1.2.4" + resolved "https://registry.yarnpkg.com/browser-resolve/-/browser-resolve-1.2.4.tgz#59ae7820a82955ecd32f5fb7c468ac21c4723806" + dependencies: + resolve "0.6.3" + +browserify-aes@^1.0.0, browserify-aes@^1.0.4: + version "1.1.1" + resolved "https://registry.yarnpkg.com/browserify-aes/-/browserify-aes-1.1.1.tgz#38b7ab55edb806ff2dcda1a7f1620773a477c49f" + dependencies: + buffer-xor "^1.0.3" + cipher-base "^1.0.0" + create-hash "^1.1.0" + evp_bytestokey "^1.0.3" + inherits "^2.0.1" + safe-buffer "^5.0.1" + +browserify-cipher@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/browserify-cipher/-/browserify-cipher-1.0.0.tgz#9988244874bf5ed4e28da95666dcd66ac8fc363a" + dependencies: + browserify-aes "^1.0.4" + browserify-des "^1.0.0" + evp_bytestokey "^1.0.0" + +browserify-des@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/browserify-des/-/browserify-des-1.0.0.tgz#daa277717470922ed2fe18594118a175439721dd" + dependencies: + cipher-base "^1.0.1" + des.js "^1.0.0" + inherits "^2.0.1" + +browserify-rsa@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/browserify-rsa/-/browserify-rsa-4.0.1.tgz#21e0abfaf6f2029cf2fafb133567a701d4135524" + dependencies: + bn.js "^4.1.0" + randombytes "^2.0.1" + +browserify-sign@^4.0.0: + version "4.0.4" + resolved "https://registry.yarnpkg.com/browserify-sign/-/browserify-sign-4.0.4.tgz#aa4eb68e5d7b658baa6bf6a57e630cbd7a93d298" + dependencies: + bn.js "^4.1.1" + browserify-rsa "^4.0.0" + create-hash "^1.1.0" + create-hmac "^1.1.2" + elliptic "^6.0.0" + inherits "^2.0.1" + parse-asn1 "^5.0.0" + +browserify-zlib@~0.1.2: + version "0.1.4" + resolved "https://registry.yarnpkg.com/browserify-zlib/-/browserify-zlib-0.1.4.tgz#bb35f8a519f600e0fa6b8485241c979d0141fb2d" + dependencies: + pako "~0.2.0" + +browserify@11.2.0: + version "11.2.0" + resolved "https://registry.yarnpkg.com/browserify/-/browserify-11.2.0.tgz#a11bb9dd209d79572b813f7eeeaf828a5f5c0e4e" + dependencies: + JSONStream "^1.0.3" + assert "~1.3.0" + browser-pack "^5.0.0" + browser-resolve "^1.7.1" + browserify-zlib "~0.1.2" + buffer "^3.0.0" + builtins "~0.0.3" + commondir "0.0.1" + concat-stream "~1.4.1" + console-browserify "^1.1.0" + constants-browserify "~0.0.1" + crypto-browserify "^3.0.0" + defined "^1.0.0" + deps-sort "^1.3.7" + domain-browser "~1.1.0" + duplexer2 "~0.0.2" + events "~1.0.0" + glob "^4.0.5" + has "^1.0.0" + htmlescape "^1.1.0" + https-browserify "~0.0.0" + inherits "~2.0.1" + insert-module-globals "^6.4.1" + isarray "0.0.1" + labeled-stream-splicer "^1.0.0" + module-deps "^3.7.11" + os-browserify "~0.1.1" + parents "^1.0.1" + path-browserify "~0.0.0" + process "~0.11.0" + punycode "^1.3.2" + querystring-es3 "~0.2.0" + read-only-stream "^1.1.1" + readable-stream "^2.0.2" + resolve "^1.1.4" + shasum "^1.0.0" + shell-quote "~0.0.1" + stream-browserify "^2.0.0" + stream-http "^1.2.0" + string_decoder "~0.10.0" + subarg "^1.0.0" + syntax-error "^1.1.1" + through2 "^1.0.0" + timers-browserify "^1.0.1" + tty-browserify "~0.0.0" + url "~0.10.1" + util "~0.10.1" + vm-browserify "~0.0.1" + xtend "^4.0.0" + +browserify@3.x.x: + version "3.46.1" + resolved "https://registry.yarnpkg.com/browserify/-/browserify-3.46.1.tgz#2c2e4a7f2f408178e78c223b5b57b37c2185ad8e" + dependencies: + JSONStream "~0.7.1" + assert "~1.1.0" + browser-pack "~2.0.0" + browser-resolve "~1.2.1" + browserify-zlib "~0.1.2" + buffer "~2.1.4" + builtins "~0.0.3" + commondir "0.0.1" + concat-stream "~1.4.1" + console-browserify "~1.0.1" + constants-browserify "~0.0.1" + crypto-browserify "~1.0.9" + deep-equal "~0.1.0" + defined "~0.0.0" + deps-sort "~0.1.1" + derequire "~0.8.0" + domain-browser "~1.1.0" + duplexer "~0.1.1" + events "~1.0.0" + glob "~3.2.8" + http-browserify "~1.3.1" + https-browserify "~0.0.0" + inherits "~2.0.1" + insert-module-globals "~6.0.0" + module-deps "~2.0.0" + os-browserify "~0.1.1" + parents "~0.0.1" + path-browserify "~0.0.0" + process "^0.7.0" + punycode "~1.2.3" + querystring-es3 "0.2.0" + resolve "~0.6.1" + shallow-copy "0.0.1" + shell-quote "~0.0.1" + stream-browserify "~0.1.0" + stream-combiner "~0.0.2" + string_decoder "~0.0.0" + subarg "0.0.1" + syntax-error "~1.1.0" + through2 "~0.4.1" + timers-browserify "~1.0.1" + tty-browserify "~0.0.0" + umd "~2.0.0" + url "~0.10.1" + util "~0.10.1" + vm-browserify "~0.0.1" + xtend "^3.0.0" + +buffer-xor@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/buffer-xor/-/buffer-xor-1.0.3.tgz#26e61ed1422fb70dd42e6e36729ed51d855fe8d9" + +buffer@^3.0.0: + version "3.6.0" + resolved "https://registry.yarnpkg.com/buffer/-/buffer-3.6.0.tgz#a72c936f77b96bf52f5f7e7b467180628551defb" + dependencies: + base64-js "0.0.8" + ieee754 "^1.1.4" + isarray "^1.0.0" + +buffer@~2.1.4: + version "2.1.13" + resolved "https://registry.yarnpkg.com/buffer/-/buffer-2.1.13.tgz#c88838ebf79f30b8b4a707788470bea8a62c2355" + dependencies: + base64-js "~0.0.4" + ieee754 "~1.1.1" + +builtin-status-codes@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/builtin-status-codes/-/builtin-status-codes-1.0.0.tgz#30637ee262978ac07174e16d7f82f0ad06e085ad" + +builtins@~0.0.3: + version "0.0.7" + resolved "https://registry.yarnpkg.com/builtins/-/builtins-0.0.7.tgz#355219cd6cf18dbe7c01cc7fd2dce765cfdc549a" + +callsite@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/callsite/-/callsite-1.0.0.tgz#280398e5d664bd74038b6f0905153e6e8af1bc20" + +camelcase@^1.0.2: + version "1.2.1" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39" + +chalk@^1.1.1: + version "1.1.3" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" + dependencies: + ansi-styles "^2.2.1" + escape-string-regexp "^1.0.2" + has-ansi "^2.0.0" + strip-ansi "^3.0.0" + supports-color "^2.0.0" + +cipher-base@^1.0.0, cipher-base@^1.0.1, cipher-base@^1.0.3: + version "1.0.4" + resolved "https://registry.yarnpkg.com/cipher-base/-/cipher-base-1.0.4.tgz#8760e4ecc272f4c363532f926d874aae2c1397de" + dependencies: + inherits "^2.0.1" + safe-buffer "^5.0.1" + +combine-source-map@~0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/combine-source-map/-/combine-source-map-0.3.0.tgz#d9e74f593d9cd43807312cb5d846d451efaa9eb7" + dependencies: + convert-source-map "~0.3.0" + inline-source-map "~0.3.0" + source-map "~0.1.31" + +combine-source-map@~0.6.1: + version "0.6.1" + resolved "https://registry.yarnpkg.com/combine-source-map/-/combine-source-map-0.6.1.tgz#9b4a09c316033d768e0f11e029fa2730e079ad96" + dependencies: + convert-source-map "~1.1.0" + inline-source-map "~0.5.0" + lodash.memoize "~3.0.3" + source-map "~0.4.2" + +commondir@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/commondir/-/commondir-0.0.1.tgz#89f00fdcd51b519c578733fec563e6a6da7f5be2" + +concat-map@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" + +concat-stream@~0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-0.1.1.tgz#d7f4e278b90cfc4f0f3ef77fe4c03b40eb3f7900" + +concat-stream@~1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.0.1.tgz#018b18bc1c7d073a2dc82aa48442341a2c4dd79f" + dependencies: + bops "0.0.6" + +concat-stream@~1.4.1, concat-stream@~1.4.5: + version "1.4.10" + resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.4.10.tgz#acc3bbf5602cb8cc980c6ac840fa7d8603e3ef36" + dependencies: + inherits "~2.0.1" + readable-stream "~1.1.9" + typedarray "~0.0.5" + +console-browserify@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/console-browserify/-/console-browserify-1.1.0.tgz#f0241c45730a9fc6323b206dbf38edc741d0bb10" + dependencies: + date-now "^0.1.4" + +console-browserify@~1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/console-browserify/-/console-browserify-1.0.3.tgz#d3898d2c3a93102f364197f8874b4f92b5286a8e" + +constants-browserify@~0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/constants-browserify/-/constants-browserify-0.0.1.tgz#92577db527ba6c4cf0a4568d84bc031f441e21f2" + +convert-source-map@~0.3.0: + version "0.3.5" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-0.3.5.tgz#f1d802950af7dd2631a1febe0596550c86ab3190" + +convert-source-map@~1.1.0: + version "1.1.3" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.1.3.tgz#4829c877e9fe49b3161f3bf3673888e204699860" + +core-util-is@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" + +create-ecdh@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/create-ecdh/-/create-ecdh-4.0.0.tgz#888c723596cdf7612f6498233eebd7a35301737d" + dependencies: + bn.js "^4.1.0" + elliptic "^6.0.0" + +create-hash@^1.1.0, create-hash@^1.1.2: + version "1.1.3" + resolved "https://registry.yarnpkg.com/create-hash/-/create-hash-1.1.3.tgz#606042ac8b9262750f483caddab0f5819172d8fd" + dependencies: + cipher-base "^1.0.1" + inherits "^2.0.1" + ripemd160 "^2.0.0" + sha.js "^2.4.0" + +create-hmac@^1.1.0, create-hmac@^1.1.2, create-hmac@^1.1.4: + version "1.1.6" + resolved "https://registry.yarnpkg.com/create-hmac/-/create-hmac-1.1.6.tgz#acb9e221a4e17bdb076e90657c42b93e3726cf06" + dependencies: + cipher-base "^1.0.3" + create-hash "^1.1.0" + inherits "^2.0.1" + ripemd160 "^2.0.0" + safe-buffer "^5.0.1" + sha.js "^2.4.8" + +crypto-browserify@^3.0.0: + version "3.12.0" + resolved "https://registry.yarnpkg.com/crypto-browserify/-/crypto-browserify-3.12.0.tgz#396cf9f3137f03e4b8e532c58f698254e00f80ec" + dependencies: + browserify-cipher "^1.0.0" + browserify-sign "^4.0.0" + create-ecdh "^4.0.0" + create-hash "^1.1.0" + create-hmac "^1.1.0" + diffie-hellman "^5.0.0" + inherits "^2.0.1" + pbkdf2 "^3.0.3" + public-encrypt "^4.0.0" + randombytes "^2.0.0" + randomfill "^1.0.3" + +crypto-browserify@~1.0.9: + version "1.0.9" + resolved "https://registry.yarnpkg.com/crypto-browserify/-/crypto-browserify-1.0.9.tgz#cc5449685dfb85eb11c9828acc7cb87ab5bbfcc0" + +date-now@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/date-now/-/date-now-0.1.4.tgz#eaf439fd4d4848ad74e5cc7dbef200672b9e345b" + +decamelize@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" + +deep-equal@~0.0.0: + version "0.0.0" + resolved "https://registry.yarnpkg.com/deep-equal/-/deep-equal-0.0.0.tgz#99679d3bbd047156fcd450d3d01eeb9068691e83" + +deep-equal@~0.1.0: + version "0.1.2" + resolved "https://registry.yarnpkg.com/deep-equal/-/deep-equal-0.1.2.tgz#b246c2b80a570a47c11be1d9bd1070ec878b87ce" + +deep-equal@~1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/deep-equal/-/deep-equal-1.0.1.tgz#f5d260292b660e084eff4cdbc9f08ad3247448b5" + +define-properties@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.2.tgz#83a73f2fea569898fb737193c8f873caf6d45c94" + dependencies: + foreach "^2.0.5" + object-keys "^1.0.8" + +defined@^1.0.0, defined@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/defined/-/defined-1.0.0.tgz#c98d9bcef75674188e110969151199e39b1fa693" + +defined@~0.0.0: + version "0.0.0" + resolved "https://registry.yarnpkg.com/defined/-/defined-0.0.0.tgz#f35eea7d705e933baf13b2f03b3f83d921403b3e" + +deps-sort@^1.3.7: + version "1.3.9" + resolved "https://registry.yarnpkg.com/deps-sort/-/deps-sort-1.3.9.tgz#29dfff53e17b36aecae7530adbbbf622c2ed1a71" + dependencies: + JSONStream "^1.0.3" + shasum "^1.0.0" + subarg "^1.0.0" + through2 "^1.0.0" + +deps-sort@~0.1.1: + version "0.1.2" + resolved "https://registry.yarnpkg.com/deps-sort/-/deps-sort-0.1.2.tgz#daa2fb614a17c9637d801e2f55339ae370f3611a" + dependencies: + JSONStream "~0.6.4" + minimist "~0.0.1" + through "~2.3.4" + +derequire@~0.8.0: + version "0.8.0" + resolved "https://registry.yarnpkg.com/derequire/-/derequire-0.8.0.tgz#c1f7f1da2cede44adede047378f03f444e9c4c0d" + dependencies: + esprima-fb "^3001.1.0-dev-harmony-fb" + esrefactor "~0.1.0" + estraverse "~1.5.0" + +des.js@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/des.js/-/des.js-1.0.0.tgz#c074d2e2aa6a8a9a07dbd61f9a15c2cd83ec8ecc" + dependencies: + inherits "^2.0.1" + minimalistic-assert "^1.0.0" + +detective@^4.0.0: + version "4.7.1" + resolved "https://registry.yarnpkg.com/detective/-/detective-4.7.1.tgz#0eca7314338442febb6d65da54c10bb1c82b246e" + dependencies: + acorn "^5.2.1" + defined "^1.0.0" + +detective@~3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/detective/-/detective-3.1.0.tgz#77782444ab752b88ca1be2e9d0a0395f1da25eed" + dependencies: + escodegen "~1.1.0" + esprima-fb "3001.1.0-dev-harmony-fb" + +diff@^2.2.1: + version "2.2.3" + resolved "https://registry.yarnpkg.com/diff/-/diff-2.2.3.tgz#60eafd0d28ee906e4e8ff0a52c1229521033bf99" + +diffie-hellman@^5.0.0: + version "5.0.2" + resolved "https://registry.yarnpkg.com/diffie-hellman/-/diffie-hellman-5.0.2.tgz#b5835739270cfe26acf632099fded2a07f209e5e" + dependencies: + bn.js "^4.1.0" + miller-rabin "^4.0.0" + randombytes "^2.0.0" + +domain-browser@~1.1.0: + version "1.1.7" + resolved "https://registry.yarnpkg.com/domain-browser/-/domain-browser-1.1.7.tgz#867aa4b093faa05f1de08c06f4d7b21fdf8698bc" + +duplexer2@0.0.2, duplexer2@~0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/duplexer2/-/duplexer2-0.0.2.tgz#c614dcf67e2fb14995a91711e5a617e8a60a31db" + dependencies: + readable-stream "~1.1.9" + +duplexer@^0.1.1, duplexer@~0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" + +ecstatic@~0.4.5: + version "0.4.13" + resolved "https://registry.yarnpkg.com/ecstatic/-/ecstatic-0.4.13.tgz#9cb6eaffe211b9c84efb3f553cde2c3002717b29" + dependencies: + ent "0.0.x" + mime "1.2.x" + optimist "~0.3.5" + +elliptic@^6.0.0: + version "6.4.0" + resolved "https://registry.yarnpkg.com/elliptic/-/elliptic-6.4.0.tgz#cac9af8762c85836187003c8dfe193e5e2eae5df" + dependencies: + bn.js "^4.4.0" + brorand "^1.0.1" + hash.js "^1.0.0" + hmac-drbg "^1.0.0" + inherits "^2.0.1" + minimalistic-assert "^1.0.0" + minimalistic-crypto-utils "^1.0.0" + +ent@0.0.x, ent@~0.0.5: + version "0.0.7" + resolved "https://registry.yarnpkg.com/ent/-/ent-0.0.7.tgz#835d4e7f9e7a8d4921c692e9010ec976da5e9949" + +es-abstract@^1.5.0: + version "1.10.0" + resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.10.0.tgz#1ecb36c197842a00d8ee4c2dfd8646bb97d60864" + dependencies: + es-to-primitive "^1.1.1" + function-bind "^1.1.1" + has "^1.0.1" + is-callable "^1.1.3" + is-regex "^1.0.4" + +es-to-primitive@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.1.1.tgz#45355248a88979034b6792e19bb81f2b7975dd0d" + dependencies: + is-callable "^1.1.1" + is-date-object "^1.0.1" + is-symbol "^1.0.1" + +escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" + +escodegen@~1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.1.0.tgz#c663923f6e20aad48d0c0fa49f31c6d4f49360cf" + dependencies: + esprima "~1.0.4" + estraverse "~1.5.0" + esutils "~1.0.0" + optionalDependencies: + source-map "~0.1.30" + +escope@~0.0.13: + version "0.0.16" + resolved "https://registry.yarnpkg.com/escope/-/escope-0.0.16.tgz#418c7a0afca721dafe659193fd986283e746538f" + dependencies: + estraverse ">= 0.0.2" + +esprima-fb@3001.1.0-dev-harmony-fb, esprima-fb@^3001.1.0-dev-harmony-fb: + version "3001.1.0-dev-harmony-fb" + resolved "https://registry.yarnpkg.com/esprima-fb/-/esprima-fb-3001.0001.0000-dev-harmony-fb.tgz#b77d37abcd38ea0b77426bb8bc2922ce6b426411" + +esprima@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.0.tgz#4499eddcd1110e0b218bacf2fa7f7f59f55ca804" + +esprima@~1.0.2, esprima@~1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-1.0.4.tgz#9f557e08fc3b4d26ece9dd34f8fbf476b62585ad" + +esrefactor@~0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/esrefactor/-/esrefactor-0.1.0.tgz#d142795a282339ab81e936b5b7a21b11bf197b13" + dependencies: + escope "~0.0.13" + esprima "~1.0.2" + estraverse "~0.0.4" + +"estraverse@>= 0.0.2": + version "4.2.0" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.2.0.tgz#0dee3fed31fcd469618ce7342099fc1afa0bdb13" + +estraverse@~0.0.4: + version "0.0.4" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-0.0.4.tgz#01a0932dfee574684a598af5a67c3bf9b6428db2" + +estraverse@~1.5.0: + version "1.5.1" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-1.5.1.tgz#867a3e8e58a9f84618afb6c2ddbcd916b7cbaf71" + +esutils@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/esutils/-/esutils-1.0.0.tgz#8151d358e20c8acc7fb745e7472c0025fe496570" + +events@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/events/-/events-1.0.2.tgz#75849dcfe93d10fb057c30055afdbd51d06a8e24" + +evp_bytestokey@^1.0.0, evp_bytestokey@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz#7fcbdb198dc71959432efe13842684e0525acb02" + dependencies: + md5.js "^1.3.4" + safe-buffer "^5.1.1" + +figures@^1.4.0: + version "1.7.0" + resolved "https://registry.yarnpkg.com/figures/-/figures-1.7.0.tgz#cbe1e3affcf1cd44b80cadfed28dc793a9701d2e" + dependencies: + escape-string-regexp "^1.0.5" + object-assign "^4.1.0" + +foreach@^2.0.5: + version "2.0.5" + resolved "https://registry.yarnpkg.com/foreach/-/foreach-2.0.5.tgz#0bee005018aeb260d0a3af3ae658dd0136ec1b99" + +function-bind@^1.0.2, function-bind@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" + +function-bind@~1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.0.2.tgz#c2873b69c5e6d7cefae47d2555172926c8c2e05e" + +glob@^4.0.5: + version "4.5.3" + resolved "https://registry.yarnpkg.com/glob/-/glob-4.5.3.tgz#c6cb73d3226c1efef04de3c56d012f03377ee15f" + dependencies: + inflight "^1.0.4" + inherits "2" + minimatch "^2.0.1" + once "^1.3.0" + +glob@~3.2.1, glob@~3.2.8: + version "3.2.11" + resolved "https://registry.yarnpkg.com/glob/-/glob-3.2.11.tgz#4a973f635b9190f715d10987d5c00fd2815ebe3d" + dependencies: + inherits "2" + minimatch "0.3" + +glob@~5.0.3: + version "5.0.15" + resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1" + dependencies: + inflight "^1.0.4" + inherits "2" + minimatch "2 || 3" + once "^1.3.0" + path-is-absolute "^1.0.0" + +has-ansi@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" + dependencies: + ansi-regex "^2.0.0" + +has@^1.0.0, has@^1.0.1, has@~1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/has/-/has-1.0.1.tgz#8461733f538b0837c9361e39a9ab9e9704dc2f28" + dependencies: + function-bind "^1.0.2" + +hash-base@^2.0.0: + version "2.0.2" + resolved "https://registry.yarnpkg.com/hash-base/-/hash-base-2.0.2.tgz#66ea1d856db4e8a5470cadf6fce23ae5244ef2e1" + dependencies: + inherits "^2.0.1" + +hash-base@^3.0.0: + version "3.0.4" + resolved "https://registry.yarnpkg.com/hash-base/-/hash-base-3.0.4.tgz#5fc8686847ecd73499403319a6b0a3f3f6ae4918" + dependencies: + inherits "^2.0.1" + safe-buffer "^5.0.1" + +hash.js@^1.0.0, hash.js@^1.0.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/hash.js/-/hash.js-1.1.3.tgz#340dedbe6290187151c1ea1d777a3448935df846" + dependencies: + inherits "^2.0.3" + minimalistic-assert "^1.0.0" + +headless@~0.1.3: + version "0.1.7" + resolved "https://registry.yarnpkg.com/headless/-/headless-0.1.7.tgz#6e62fae668947f88184d5c156ede7c5695a7e9c8" + +hirestime@^1.0.6: + version "1.0.7" + resolved "https://registry.yarnpkg.com/hirestime/-/hirestime-1.0.7.tgz#2d5271ea84356cec3f25da8c56a9402f8fc0a700" + +hmac-drbg@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1" + dependencies: + hash.js "^1.0.3" + minimalistic-assert "^1.0.0" + minimalistic-crypto-utils "^1.0.1" + +htmlescape@^1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/htmlescape/-/htmlescape-1.1.1.tgz#3a03edc2214bca3b66424a3e7959349509cb0351" + +http-browserify@~1.3.1: + version "1.3.2" + resolved "https://registry.yarnpkg.com/http-browserify/-/http-browserify-1.3.2.tgz#b562c34479349a690d7a6597df495aefa8c604f5" + dependencies: + Base64 "~0.2.0" + inherits "~2.0.1" + +https-browserify@~0.0.0: + version "0.0.1" + resolved "https://registry.yarnpkg.com/https-browserify/-/https-browserify-0.0.1.tgz#3f91365cabe60b77ed0ebba24b454e3e09d95a82" + +ieee754@^1.1.4, ieee754@~1.1.1: + version "1.1.8" + resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.1.8.tgz#be33d40ac10ef1926701f6f08a2d86fbfd1ad3e4" + +indexof@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/indexof/-/indexof-0.0.1.tgz#82dc336d232b9062179d05ab3293a66059fd435d" + +inflight@^1.0.4: + version "1.0.6" + resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + dependencies: + once "^1.3.0" + wrappy "1" + +inherits@2, inherits@^2.0.1, inherits@^2.0.3, inherits@~2.0.1, inherits@~2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" + +inherits@2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.1.tgz#b17d08d326b4423e568eff719f91b0b1cbdf69f1" + +inline-source-map@~0.3.0: + version "0.3.1" + resolved "https://registry.yarnpkg.com/inline-source-map/-/inline-source-map-0.3.1.tgz#a528b514e689fce90db3089e870d92f527acb5eb" + dependencies: + source-map "~0.3.0" + +inline-source-map@~0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/inline-source-map/-/inline-source-map-0.5.0.tgz#4a4c5dd8e4fb5e9b3cda60c822dfadcaee66e0af" + dependencies: + source-map "~0.4.0" + +insert-module-globals@^6.4.1: + version "6.6.3" + resolved "https://registry.yarnpkg.com/insert-module-globals/-/insert-module-globals-6.6.3.tgz#20638e29a30f9ed1ca2e3a825fbc2cba5246ddfc" + dependencies: + JSONStream "^1.0.3" + combine-source-map "~0.6.1" + concat-stream "~1.4.1" + is-buffer "^1.1.0" + lexical-scope "^1.2.0" + process "~0.11.0" + through2 "^1.0.0" + xtend "^4.0.0" + +insert-module-globals@~6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/insert-module-globals/-/insert-module-globals-6.0.0.tgz#ee8aeb9dee16819e33aa14588a558824af0c15dc" + dependencies: + JSONStream "~0.7.1" + concat-stream "~1.4.1" + lexical-scope "~1.1.0" + process "~0.6.0" + through "~2.3.4" + xtend "^3.0.0" + +is-buffer@^1.1.0: + version "1.1.6" + resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" + +is-callable@^1.1.1, is-callable@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.1.3.tgz#86eb75392805ddc33af71c92a0eedf74ee7604b2" + +is-date-object@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16" + +is-finite@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-finite/-/is-finite-1.0.2.tgz#cc6677695602be550ef11e8b4aa6305342b6d0aa" + dependencies: + number-is-nan "^1.0.0" + +is-regex@^1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.0.4.tgz#5517489b547091b0930e095654ced25ee97e9491" + dependencies: + has "^1.0.1" + +is-symbol@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.1.tgz#3cc59f00025194b6ab2e38dbae6689256b660572" + +isarray@0.0.1, isarray@~0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" + +isarray@^1.0.0, isarray@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" + +js-yaml@^3.4.6: + version "3.10.0" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.10.0.tgz#2e78441646bd4682e963f22b6e92823c309c62dc" + dependencies: + argparse "^1.0.7" + esprima "^4.0.0" + +json-stable-stringify@~0.0.0: + version "0.0.1" + resolved "https://registry.yarnpkg.com/json-stable-stringify/-/json-stable-stringify-0.0.1.tgz#611c23e814db375527df851193db59dd2af27f45" + dependencies: + jsonify "~0.0.0" + +jsonify@~0.0.0: + version "0.0.0" + resolved "https://registry.yarnpkg.com/jsonify/-/jsonify-0.0.0.tgz#2c74b6ee41d93ca51b7b5aaee8f503631d252a73" + +jsonparse@0.0.5: + version "0.0.5" + resolved "https://registry.yarnpkg.com/jsonparse/-/jsonparse-0.0.5.tgz#330542ad3f0a654665b778f3eb2d9a9fa507ac64" + +jsonparse@^1.2.0: + version "1.3.1" + resolved "https://registry.yarnpkg.com/jsonparse/-/jsonparse-1.3.1.tgz#3f4dae4a91fac315f71062f8521cc239f1366280" + +labeled-stream-splicer@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/labeled-stream-splicer/-/labeled-stream-splicer-1.0.2.tgz#4615331537784981e8fd264e1f3a434c4e0ddd65" + dependencies: + inherits "^2.0.1" + isarray "~0.0.1" + stream-splicer "^1.1.0" + +lexical-scope@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/lexical-scope/-/lexical-scope-1.2.0.tgz#fcea5edc704a4b3a8796cdca419c3a0afaf22df4" + dependencies: + astw "^2.0.0" + +lexical-scope@~1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/lexical-scope/-/lexical-scope-1.1.1.tgz#debac1067435f1359d90fcfd9e94bcb2ee47b2bf" + dependencies: + astw "^2.0.0" + +lodash.memoize@~3.0.3: + version "3.0.4" + resolved "https://registry.yarnpkg.com/lodash.memoize/-/lodash.memoize-3.0.4.tgz#2dcbd2c287cbc0a55cc42328bd0c736150d53e3f" + +lru-cache@2: + version "2.7.3" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-2.7.3.tgz#6d4524e8b955f95d4f5b58851ce21dd72fb4e952" + +md5.js@^1.3.4: + version "1.3.4" + resolved "https://registry.yarnpkg.com/md5.js/-/md5.js-1.3.4.tgz#e9bdbde94a20a5ac18b04340fc5764d5b09d901d" + dependencies: + hash-base "^3.0.0" + inherits "^2.0.1" + +merge@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/merge/-/merge-1.0.0.tgz#b443ab46d837c491e6222056ab0f7933ecb3568f" + +miller-rabin@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/miller-rabin/-/miller-rabin-4.0.1.tgz#f080351c865b0dc562a8462966daa53543c78a4d" + dependencies: + bn.js "^4.0.0" + brorand "^1.0.1" + +mime@1.2.x: + version "1.2.11" + resolved "https://registry.yarnpkg.com/mime/-/mime-1.2.11.tgz#58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10" + +minimalistic-assert@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.0.tgz#702be2dda6b37f4836bcb3f5db56641b64a1d3d3" + +minimalistic-crypto-utils@^1.0.0, minimalistic-crypto-utils@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz#f6c00c1c0b082246e5c4d99dfb8c7c083b2b582a" + +minimatch@0.3: + version "0.3.0" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-0.3.0.tgz#275d8edaac4f1bb3326472089e7949c8394699dd" + dependencies: + lru-cache "2" + sigmund "~1.0.0" + +"minimatch@2 || 3": + version "3.0.4" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" + dependencies: + brace-expansion "^1.1.7" + +minimatch@^2.0.1: + version "2.0.10" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-2.0.10.tgz#8d087c39c6b38c001b97fca7ce6d0e1e80afbac7" + dependencies: + brace-expansion "^1.0.0" + +minimist@0.0.5: + version "0.0.5" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.5.tgz#d7aa327bcecf518f9106ac6b8f003fa3bcea8566" + +minimist@^1.1.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" + +minimist@~0.0.1, minimist@~0.0.7, minimist@~0.0.9: + version "0.0.10" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf" + +mkdirp@~0.3.3: + version "0.3.5" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.3.5.tgz#de3e5f8961c88c787ee1368df849ac4413eca8d7" + +module-deps@^3.7.11: + version "3.9.1" + resolved "https://registry.yarnpkg.com/module-deps/-/module-deps-3.9.1.tgz#ea75caf9199090d25b0d5512b5acacb96e7f87f3" + dependencies: + JSONStream "^1.0.3" + browser-resolve "^1.7.0" + concat-stream "~1.4.5" + defined "^1.0.0" + detective "^4.0.0" + duplexer2 "0.0.2" + inherits "^2.0.1" + parents "^1.0.0" + readable-stream "^1.1.13" + resolve "^1.1.3" + stream-combiner2 "~1.0.0" + subarg "^1.0.0" + through2 "^1.0.0" + xtend "^4.0.0" + +module-deps@~2.0.0: + version "2.0.6" + resolved "https://registry.yarnpkg.com/module-deps/-/module-deps-2.0.6.tgz#b999321c73ac33580f00712c0f3075fdca42563f" + dependencies: + JSONStream "~0.7.1" + browser-resolve "~1.2.4" + concat-stream "~1.4.5" + detective "~3.1.0" + duplexer2 "0.0.2" + inherits "~2.0.1" + minimist "~0.0.9" + parents "0.0.2" + readable-stream "^1.0.27-1" + resolve "~0.6.3" + stream-combiner "~0.1.0" + through2 "~0.4.1" + +number-is-nan@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" + +object-assign@^4.1.0: + version "4.1.1" + resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" + +object-inspect@~0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-0.1.3.tgz#d05a65c2e34fe8225d9fda2e484e4e47b7e2f490" + dependencies: + tape "~1.0.4" + +object-inspect@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.0.2.tgz#a97885b553e575eb4009ebc09bdda9b1cd21979a" + +object-keys@^1.0.4, object-keys@^1.0.8: + version "1.0.11" + resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.0.11.tgz#c54601778ad560f1142ce0e01bcca8b56d13426d" + +object-keys@~0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-0.4.0.tgz#28a6aae7428dd2c3a92f3d95f21335dd204e0336" + +once@^1.3.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + dependencies: + wrappy "1" + +optimist@~0.3.5: + version "0.3.7" + resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.3.7.tgz#c90941ad59e4273328923074d2cf2e7cbc6ec0d9" + dependencies: + wordwrap "~0.0.2" + +optimist@~0.5.2: + version "0.5.2" + resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.5.2.tgz#85c8c1454b3315e4a78947e857b1df033450bfbc" + dependencies: + wordwrap "~0.0.2" + +ordered-emitter@~0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/ordered-emitter/-/ordered-emitter-0.1.1.tgz#aa20bdafbdcc1631834a350f68b4ef8eb34eed7b" + +os-browserify@~0.1.1: + version "0.1.2" + resolved "https://registry.yarnpkg.com/os-browserify/-/os-browserify-0.1.2.tgz#49ca0293e0b19590a5f5de10c7f265a617d8fe54" + +pako@~0.2.0: + version "0.2.9" + resolved "https://registry.yarnpkg.com/pako/-/pako-0.2.9.tgz#f3f7522f4ef782348da8161bad9ecfd51bf83a75" + +parents@0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/parents/-/parents-0.0.2.tgz#67147826e497d40759aaf5ba4c99659b6034d302" + +parents@^1.0.0, parents@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/parents/-/parents-1.0.1.tgz#fedd4d2bf193a77745fe71e371d73c3307d9c751" + dependencies: + path-platform "~0.11.15" + +parents@~0.0.1: + version "0.0.3" + resolved "https://registry.yarnpkg.com/parents/-/parents-0.0.3.tgz#fa212f024d9fa6318dbb6b4ce676c8be493b9c43" + dependencies: + path-platform "^0.0.1" + +parse-asn1@^5.0.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/parse-asn1/-/parse-asn1-5.1.0.tgz#37c4f9b7ed3ab65c74817b5f2480937fbf97c712" + dependencies: + asn1.js "^4.0.0" + browserify-aes "^1.0.0" + create-hash "^1.1.0" + evp_bytestokey "^1.0.0" + pbkdf2 "^3.0.3" + +parse-ms@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/parse-ms/-/parse-ms-1.0.1.tgz#56346d4749d78f23430ca0c713850aef91aa361d" + +path-browserify@~0.0.0: + version "0.0.0" + resolved "https://registry.yarnpkg.com/path-browserify/-/path-browserify-0.0.0.tgz#a0b870729aae214005b7d5032ec2cbbb0fb4451a" + +path-is-absolute@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" + +path-parse@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.5.tgz#3c1adf871ea9cd6c9431b6ea2bd74a0ff055c4c1" + +path-platform@^0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/path-platform/-/path-platform-0.0.1.tgz#b5585d7c3c463d89aa0060d86611cf1afd617e2a" + +path-platform@~0.11.15: + version "0.11.15" + resolved "https://registry.yarnpkg.com/path-platform/-/path-platform-0.11.15.tgz#e864217f74c36850f0852b78dc7bf7d4a5721bf2" + +pbkdf2@^3.0.3: + version "3.0.14" + resolved "https://registry.yarnpkg.com/pbkdf2/-/pbkdf2-3.0.14.tgz#a35e13c64799b06ce15320f459c230e68e73bade" + dependencies: + create-hash "^1.1.2" + create-hmac "^1.1.4" + ripemd160 "^2.0.1" + safe-buffer "^5.0.1" + sha.js "^2.4.8" + +plist@0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/plist/-/plist-0.2.1.tgz#f3a3de07885d773e66d8a96782f1bec28cf2b2d0" + dependencies: + sax "0.1.x" + +plur@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/plur/-/plur-1.0.0.tgz#db85c6814f5e5e5a3b49efc28d604fec62975156" + +pretty-ms@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-2.1.0.tgz#4257c256df3fb0b451d6affaab021884126981dc" + dependencies: + is-finite "^1.0.1" + parse-ms "^1.0.0" + plur "^1.0.0" + +process-nextick-args@~2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa" + +process@^0.7.0: + version "0.7.0" + resolved "https://registry.yarnpkg.com/process/-/process-0.7.0.tgz#c52208161a34adf3812344ae85d3e6150469389d" + +process@~0.11.0: + version "0.11.10" + resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" + +process@~0.5.1: + version "0.5.2" + resolved "https://registry.yarnpkg.com/process/-/process-0.5.2.tgz#1638d8a8e34c2f440a91db95ab9aeb677fc185cf" + +process@~0.6.0: + version "0.6.0" + resolved "https://registry.yarnpkg.com/process/-/process-0.6.0.tgz#7dd9be80ffaaedd4cb628f1827f1cbab6dc0918f" + +public-encrypt@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/public-encrypt/-/public-encrypt-4.0.0.tgz#39f699f3a46560dd5ebacbca693caf7c65c18cc6" + dependencies: + bn.js "^4.1.0" + browserify-rsa "^4.0.0" + create-hash "^1.1.0" + parse-asn1 "^5.0.0" + randombytes "^2.0.1" + +punycode@1.3.2: + version "1.3.2" + resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.3.2.tgz#9653a036fb7c1ee42342f2325cceefea3926c48d" + +punycode@^1.3.2: + version "1.4.1" + resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" + +punycode@~1.2.3: + version "1.2.4" + resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.2.4.tgz#54008ac972aec74175def9cba6df7fa9d3918740" + +querystring-es3@0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/querystring-es3/-/querystring-es3-0.2.0.tgz#c365a08a69c443accfeb3a9deab35e3f0abaa476" + +querystring-es3@~0.2.0: + version "0.2.1" + resolved "https://registry.yarnpkg.com/querystring-es3/-/querystring-es3-0.2.1.tgz#9ec61f79049875707d69414596fd907a4d711e73" + +querystring@0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/querystring/-/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620" + +ramda@^0.18.0: + version "0.18.0" + resolved "https://registry.yarnpkg.com/ramda/-/ramda-0.18.0.tgz#c6e3c5d4b9ab1f7906727fdeeb039152a85d4db3" + +randombytes@^2.0.0, randombytes@^2.0.1, randombytes@^2.0.5: + version "2.0.6" + resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.0.6.tgz#d302c522948588848a8d300c932b44c24231da80" + dependencies: + safe-buffer "^5.1.0" + +randomfill@^1.0.3: + version "1.0.4" + resolved "https://registry.yarnpkg.com/randomfill/-/randomfill-1.0.4.tgz#c92196fc86ab42be983f1bf31778224931d61458" + dependencies: + randombytes "^2.0.5" + safe-buffer "^5.1.0" + +read-only-stream@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/read-only-stream/-/read-only-stream-1.1.1.tgz#5da77c799ed1388d3ef88a18471bb5924f8a0ba1" + dependencies: + readable-stream "^1.0.31" + readable-wrap "^1.0.0" + +"readable-stream@>=1.1.13-1 <1.2.0-0", readable-stream@^1.0.27-1, readable-stream@^1.0.31, readable-stream@^1.1.13, readable-stream@^1.1.13-1, readable-stream@~1.1.9: + version "1.1.14" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.14.tgz#7cf4c54ef648e3813084c636dd2079e166c081d9" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "0.0.1" + string_decoder "~0.10.x" + +readable-stream@^2.0.2, readable-stream@^2.0.4: + version "2.3.4" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.4.tgz#c946c3f47fa7d8eabc0b6150f4a12f69a4574071" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.3" + isarray "~1.0.0" + process-nextick-args "~2.0.0" + safe-buffer "~5.1.1" + string_decoder "~1.0.3" + util-deprecate "~1.0.1" + +readable-stream@~1.0.17: + version "1.0.34" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.0.34.tgz#125820e34bc842d2f2aaafafe4c2916ee32c157c" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "0.0.1" + string_decoder "~0.10.x" + +readable-wrap@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/readable-wrap/-/readable-wrap-1.0.0.tgz#3b5a211c631e12303a54991c806c17e7ae206bff" + dependencies: + readable-stream "^1.1.13-1" + +resolve@0.6.3, resolve@~0.6.1, resolve@~0.6.3: + version "0.6.3" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-0.6.3.tgz#dd957982e7e736debdf53b58a4dd91754575dd46" + +resolve@1.1.7: + version "1.1.7" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" + +resolve@^1.1.3, resolve@^1.1.4: + version "1.5.0" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.5.0.tgz#1f09acce796c9a762579f31b2c1cc4c3cddf9f36" + dependencies: + path-parse "^1.0.5" + +resolve@~0.3.0: + version "0.3.1" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-0.3.1.tgz#34c63447c664c70598d1c9b126fc43b2a24310a4" + +resolve@~0.4.0: + version "0.4.3" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-0.4.3.tgz#dcadad202e7cacc2467e3a38800211f42f9c13df" + +resumer@~0.0.0: + version "0.0.0" + resolved "https://registry.yarnpkg.com/resumer/-/resumer-0.0.0.tgz#f1e8f461e4064ba39e82af3cdc2a8c893d076759" + dependencies: + through "~2.3.4" + +rfile@~1.0, rfile@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/rfile/-/rfile-1.0.0.tgz#59708cf90ca1e74c54c3cfc5c36fdb9810435261" + dependencies: + callsite "~1.0.0" + resolve "~0.3.0" + +ripemd160@^2.0.0, ripemd160@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/ripemd160/-/ripemd160-2.0.1.tgz#0f4584295c53a3628af7e6d79aca21ce57d1c6e7" + dependencies: + hash-base "^2.0.0" + inherits "^2.0.1" + +ruglify@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/ruglify/-/ruglify-1.0.0.tgz#dc8930e2a9544a274301cc9972574c0d0986b675" + dependencies: + rfile "~1.0" + uglify-js "~2.2" + +rx-node@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/rx-node/-/rx-node-1.0.2.tgz#151240725a79e857360ab06cc626799965e094de" + dependencies: + rx "*" + +rx@*, rx@^4.0.7: + version "4.1.0" + resolved "https://registry.yarnpkg.com/rx/-/rx-4.1.0.tgz#a5f13ff79ef3b740fe30aa803fb09f98805d4782" + +safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@~5.1.0, safe-buffer@~5.1.1: + version "5.1.1" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853" + +sax@0.1.x: + version "0.1.5" + resolved "https://registry.yarnpkg.com/sax/-/sax-0.1.5.tgz#d1829a6120fa01665eb4dbff6c43f29fd6d61471" + +sha.js@^2.4.0, sha.js@^2.4.8, sha.js@~2.4.4: + version "2.4.10" + resolved "https://registry.yarnpkg.com/sha.js/-/sha.js-2.4.10.tgz#b1fde5cd7d11a5626638a07c604ab909cfa31f9b" + dependencies: + inherits "^2.0.1" + safe-buffer "^5.0.1" + +shallow-copy@0.0.1, shallow-copy@~0.0.0: + version "0.0.1" + resolved "https://registry.yarnpkg.com/shallow-copy/-/shallow-copy-0.0.1.tgz#415f42702d73d810330292cc5ee86eae1a11a170" + +shasum@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/shasum/-/shasum-1.0.2.tgz#e7012310d8f417f4deb5712150e5678b87ae565f" + dependencies: + json-stable-stringify "~0.0.0" + sha.js "~2.4.4" + +shell-quote@~0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/shell-quote/-/shell-quote-0.0.1.tgz#1a41196f3c0333c482323593d6886ecf153dd986" + +shell-quote@~1.3.1: + version "1.3.3" + resolved "https://registry.yarnpkg.com/shell-quote/-/shell-quote-1.3.3.tgz#07b8826f427c052511e8b5627639e172596e8e4b" + +sigmund@~1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/sigmund/-/sigmund-1.0.1.tgz#3ff21f198cad2175f9f3b781853fd94d0d19b590" + +source-map@0.1.34: + version "0.1.34" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.1.34.tgz#a7cfe89aec7b1682c3b198d0acfb47d7d090566b" + dependencies: + amdefine ">=0.0.4" + +source-map@~0.1.30, source-map@~0.1.31, source-map@~0.1.7: + version "0.1.43" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.1.43.tgz#c24bc146ca517c1471f5dacbe2571b2b7f9e3346" + dependencies: + amdefine ">=0.0.4" + +source-map@~0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.3.0.tgz#8586fb9a5a005e5b501e21cd18b6f21b457ad1f9" + dependencies: + amdefine ">=0.0.4" + +source-map@~0.4.0, source-map@~0.4.2: + version "0.4.4" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b" + dependencies: + amdefine ">=0.0.4" + +source-map@~0.5.1: + version "0.5.7" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" + +split@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/split/-/split-1.0.1.tgz#605bd9be303aa59fb35f9229fbea0ddec9ea07d9" + dependencies: + through "2" + +split@~0.1.2: + version "0.1.2" + resolved "https://registry.yarnpkg.com/split/-/split-0.1.2.tgz#f0710744c453d551fc7143ead983da6014e336cc" + dependencies: + through "1" + +sprintf-js@~1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + +stream-browserify@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/stream-browserify/-/stream-browserify-2.0.1.tgz#66266ee5f9bdb9940a4e4514cafb43bb71e5c9db" + dependencies: + inherits "~2.0.1" + readable-stream "^2.0.2" + +stream-browserify@~0.1.0: + version "0.1.3" + resolved "https://registry.yarnpkg.com/stream-browserify/-/stream-browserify-0.1.3.tgz#95cf1b369772e27adaf46352265152689c6c4be9" + dependencies: + inherits "~2.0.1" + process "~0.5.1" + +stream-combiner2@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/stream-combiner2/-/stream-combiner2-1.0.2.tgz#ba72a6b50cbfabfa950fc8bc87604bd01eb60671" + dependencies: + duplexer2 "~0.0.2" + through2 "~0.5.1" + +stream-combiner@~0.0.2: + version "0.0.4" + resolved "https://registry.yarnpkg.com/stream-combiner/-/stream-combiner-0.0.4.tgz#4d5e433c185261dde623ca3f44c586bcf5c4ad14" + dependencies: + duplexer "~0.1.1" + +stream-combiner@~0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/stream-combiner/-/stream-combiner-0.1.0.tgz#0dc389a3c203f8f4d56368f95dde52eb9269b5be" + dependencies: + duplexer "~0.1.1" + through "~2.3.4" + +stream-http@^1.2.0: + version "1.7.1" + resolved "https://registry.yarnpkg.com/stream-http/-/stream-http-1.7.1.tgz#d3d2a6e14c36a38b9dafb199aee7bbc570519978" + dependencies: + builtin-status-codes "^1.0.0" + foreach "^2.0.5" + indexof "0.0.1" + inherits "^2.0.1" + object-keys "^1.0.4" + xtend "^4.0.0" + +stream-splicer@^1.1.0: + version "1.3.2" + resolved "https://registry.yarnpkg.com/stream-splicer/-/stream-splicer-1.3.2.tgz#3c0441be15b9bf4e226275e6dc83964745546661" + dependencies: + indexof "0.0.1" + inherits "^2.0.1" + isarray "~0.0.1" + readable-stream "^1.1.13-1" + readable-wrap "^1.0.0" + through2 "^1.0.0" + +string.prototype.trim@^1.1.1: + version "1.1.2" + resolved "https://registry.yarnpkg.com/string.prototype.trim/-/string.prototype.trim-1.1.2.tgz#d04de2c89e137f4d7d206f086b5ed2fae6be8cea" + dependencies: + define-properties "^1.1.2" + es-abstract "^1.5.0" + function-bind "^1.0.2" + +string_decoder@~0.0.0: + version "0.0.1" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.0.1.tgz#f5472d0a8d1650ec823752d24e6fd627b39bf141" + +string_decoder@~0.10.0, string_decoder@~0.10.x: + version "0.10.31" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94" + +string_decoder@~1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.0.3.tgz#0fc67d7c141825de94282dd536bec6b9bce860ab" + dependencies: + safe-buffer "~5.1.0" + +strip-ansi@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" + dependencies: + ansi-regex "^2.0.0" + +subarg@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/subarg/-/subarg-0.0.1.tgz#3d56b07dacfbc45bbb63f7672b43b63e46368e3a" + dependencies: + minimist "~0.0.7" + +subarg@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/subarg/-/subarg-1.0.0.tgz#f62cf17581e996b48fc965699f54c06ae268b8d2" + dependencies: + minimist "^1.1.0" + +supports-color@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" + +syntax-error@^1.1.1: + version "1.4.0" + resolved "https://registry.yarnpkg.com/syntax-error/-/syntax-error-1.4.0.tgz#2d9d4ff5c064acb711594a3e3b95054ad51d907c" + dependencies: + acorn-node "^1.2.0" + +syntax-error@~1.1.0: + version "1.1.6" + resolved "https://registry.yarnpkg.com/syntax-error/-/syntax-error-1.1.6.tgz#b4549706d386cc1c1dc7c2423f18579b6cade710" + dependencies: + acorn "^2.7.0" + +tap-finished@~0.0.0: + version "0.0.1" + resolved "https://registry.yarnpkg.com/tap-finished/-/tap-finished-0.0.1.tgz#08b5b543fdc04830290c6c561279552e71c4bd67" + dependencies: + tap-parser "~0.2.0" + through "~2.3.4" + +tap-parser@~0.2.0: + version "0.2.1" + resolved "https://registry.yarnpkg.com/tap-parser/-/tap-parser-0.2.1.tgz#8e1e823f2114ee21d032e2f31e4fb642a296f50b" + dependencies: + split "~0.1.2" + +tape@4.2.1: + version "4.2.1" + resolved "https://registry.yarnpkg.com/tape/-/tape-4.2.1.tgz#1a0ed63cc86bfaa84ebb3bb311f09d8520416216" + dependencies: + deep-equal "~1.0.0" + defined "~1.0.0" + function-bind "~1.0.2" + glob "~5.0.3" + has "~1.0.1" + inherits "~2.0.1" + object-inspect "~1.0.0" + resumer "~0.0.0" + string.prototype.trim "^1.1.1" + through "~2.3.4" + +tape@~1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/tape/-/tape-1.0.4.tgz#e2e8e5c6dd3f00fdc2a5e4514f62fc221e59f9c4" + dependencies: + deep-equal "~0.0.0" + defined "~0.0.0" + jsonify "~0.0.0" + through "~2.3.4" + +testling@1.7.1: + version "1.7.1" + resolved "https://registry.yarnpkg.com/testling/-/testling-1.7.1.tgz#bfcfa877c8b15dd28d920692c03d8d64ca47874e" + dependencies: + bouncy "~3.2.0" + browser-launcher "~0.3.2" + browserify "3.x.x" + concat-stream "~1.0.0" + ecstatic "~0.4.5" + ent "~0.0.5" + glob "~3.2.1" + jsonify "~0.0.0" + object-inspect "~0.1.3" + optimist "~0.5.2" + resolve "~0.4.0" + shallow-copy "~0.0.0" + shell-quote "~1.3.1" + tap-finished "~0.0.0" + win-spawn "~2.0.0" + xhr-write-stream "~0.1.2" + +through2@^1.0.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/through2/-/through2-1.1.1.tgz#0847cbc4449f3405574dbdccd9bb841b83ac3545" + dependencies: + readable-stream ">=1.1.13-1 <1.2.0-0" + xtend ">=4.0.0 <4.1.0-0" + +through2@~0.4.1: + version "0.4.2" + resolved "https://registry.yarnpkg.com/through2/-/through2-0.4.2.tgz#dbf5866031151ec8352bb6c4db64a2292a840b9b" + dependencies: + readable-stream "~1.0.17" + xtend "~2.1.1" + +through2@~0.5.1: + version "0.5.1" + resolved "https://registry.yarnpkg.com/through2/-/through2-0.5.1.tgz#dfdd012eb9c700e2323fd334f38ac622ab372da7" + dependencies: + readable-stream "~1.0.17" + xtend "~3.0.0" + +through@1: + version "1.1.2" + resolved "https://registry.yarnpkg.com/through/-/through-1.1.2.tgz#344a5425a3773314ca7e0eb6512fbafaf76c0bfe" + +through@2, "through@>=2.2.7 <3", through@~2.3.4: + version "2.3.8" + resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" + +through@~2.2.7: + version "2.2.7" + resolved "https://registry.yarnpkg.com/through/-/through-2.2.7.tgz#6e8e21200191d4eb6a99f6f010df46aa1c6eb2bd" + +timers-browserify@^1.0.1: + version "1.4.2" + resolved "https://registry.yarnpkg.com/timers-browserify/-/timers-browserify-1.4.2.tgz#c9c58b575be8407375cb5e2462dacee74359f41d" + dependencies: + process "~0.11.0" + +timers-browserify@~1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/timers-browserify/-/timers-browserify-1.0.3.tgz#ffba70c9c12eed916fd67318e629ac6f32295551" + dependencies: + process "~0.5.1" + +to-utf8@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/to-utf8/-/to-utf8-0.0.1.tgz#d17aea72ff2fba39b9e43601be7b3ff72e089852" + +tty-browserify@~0.0.0: + version "0.0.1" + resolved "https://registry.yarnpkg.com/tty-browserify/-/tty-browserify-0.0.1.tgz#3f05251ee17904dfd0677546670db9651682b811" + +typedarray@~0.0.5: + version "0.0.6" + resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" + +uglify-js@2.5.0: + version "2.5.0" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.5.0.tgz#4ab5d65a4730ecb7a4fb62d3f499e2054d98fba1" + dependencies: + async "~0.2.6" + source-map "~0.5.1" + uglify-to-browserify "~1.0.0" + yargs "~3.5.4" + +uglify-js@~2.2: + version "2.2.5" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.2.5.tgz#a6e02a70d839792b9780488b7b8b184c095c99c7" + dependencies: + optimist "~0.3.5" + source-map "~0.1.7" + +uglify-js@~2.4.0: + version "2.4.24" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.4.24.tgz#fad5755c1e1577658bb06ff9ab6e548c95bebd6e" + dependencies: + async "~0.2.6" + source-map "0.1.34" + uglify-to-browserify "~1.0.0" + yargs "~3.5.4" + +uglify-to-browserify@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7" + +umd@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/umd/-/umd-3.0.1.tgz#8ae556e11011f63c2596708a8837259f01b3d60e" + +umd@~2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/umd/-/umd-2.0.0.tgz#749683b0d514728ae0e1b6195f5774afc0ad4f8f" + dependencies: + rfile "~1.0.0" + ruglify "~1.0.0" + through "~2.3.4" + uglify-js "~2.4.0" + +url@~0.10.1: + version "0.10.3" + resolved "https://registry.yarnpkg.com/url/-/url-0.10.3.tgz#021e4d9c7705f21bbf37d03ceb58767402774c64" + dependencies: + punycode "1.3.2" + querystring "0.2.0" + +util-deprecate@~1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + +util@0.10.3, util@~0.10.1: + version "0.10.3" + resolved "https://registry.yarnpkg.com/util/-/util-0.10.3.tgz#7afb1afe50805246489e3db7fe0ed379336ac0f9" + dependencies: + inherits "2.0.1" + +vm-browserify@~0.0.1: + version "0.0.4" + resolved "https://registry.yarnpkg.com/vm-browserify/-/vm-browserify-0.0.4.tgz#5d7ea45bbef9e4a6ff65f95438e0a87c357d5a73" + dependencies: + indexof "0.0.1" + +win-spawn@~2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/win-spawn/-/win-spawn-2.0.0.tgz#397a29130ec98d0aa0bc86baa4621393effd0b07" + +window-size@0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" + +wordwrap@0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f" + +wordwrap@~0.0.2: + version "0.0.3" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" + +wrappy@1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + +xhr-write-stream@~0.1.2: + version "0.1.2" + resolved "https://registry.yarnpkg.com/xhr-write-stream/-/xhr-write-stream-0.1.2.tgz#e357848e0d039b411fdd5b3bf81be47ee5ce26aa" + dependencies: + concat-stream "~0.1.0" + ordered-emitter "~0.1.0" + +"xtend@>=4.0.0 <4.1.0-0", xtend@^4.0.0, xtend@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af" + +xtend@^3.0.0, xtend@~3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-3.0.0.tgz#5cce7407baf642cba7becda568111c493f59665a" + +xtend@~2.1.1: + version "2.1.2" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-2.1.2.tgz#6efecc2a4dad8e6962c4901b337ce7ba87b5d28b" + dependencies: + object-keys "~0.4.0" + +yargs@~3.5.4: + version "3.5.4" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.5.4.tgz#d8aff8f665e94c34bd259bdebd1bfaf0ddd35361" + dependencies: + camelcase "^1.0.2" + decamelize "^1.0.0" + window-size "0.1.0" + wordwrap "0.0.2" diff --git a/node_modules/typed-function/.github/dependabot.yml b/node_modules/typed-function/.github/dependabot.yml new file mode 100644 index 0000000..04d8cbc --- /dev/null +++ b/node_modules/typed-function/.github/dependabot.yml @@ -0,0 +1,26 @@ +version: 2 +updates: +- package-ecosystem: npm + directory: "/" + schedule: + interval: weekly + time: "04:00" + open-pull-requests-limit: 10 + ignore: + - dependency-name: uglify-js + versions: + - 3.12.5 + - 3.12.6 + - 3.12.8 + - 3.13.0 + - 3.13.1 + - 3.13.2 + - 3.13.3 + - dependency-name: mocha + versions: + - 8.3.0 + - 8.3.1 + - 8.3.2 + - dependency-name: brace-expansion + versions: + - 2.0.1 diff --git a/node_modules/typed-function/.github/workflows/ci-test.yaml b/node_modules/typed-function/.github/workflows/ci-test.yaml new file mode 100644 index 0000000..408a390 --- /dev/null +++ b/node_modules/typed-function/.github/workflows/ci-test.yaml @@ -0,0 +1,31 @@ +# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions + +name: Node.js CI + +on: + push: + branches: [ develop, master ] + pull_request: + branches: [ develop, master ] + +jobs: + build: + + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [12.x, 14.x, 16.x] + # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ + + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v2 + with: + node-version: ${{ matrix.node-version }} + cache: 'npm' + - run: npm ci + - run: npm run build --if-present + - run: npm test diff --git a/node_modules/typed-function/HISTORY.md b/node_modules/typed-function/HISTORY.md new file mode 100644 index 0000000..a67c1b3 --- /dev/null +++ b/node_modules/typed-function/HISTORY.md @@ -0,0 +1,240 @@ +# History + + +## 2022-03-11, version 2.1.0 + +- Implemented configurable callbacks `typed.createError` and `typed.onMismatch`. + Thanks @gwhitney. + + +## 2020-07-03, version 2.0.0 + +- Drop official support for node.js 6 and 8, though no breaking changes + at this point. +- Implemented support for recursion using the `this` keyword. Thanks @nickewing. + + +## 2019-08-22, version 1.1.1 + +- Fix #15: passing `null` to an `Object` parameter throws wrong error. + + +## 2018-07-28, version 1.1.0 + +- Implemented support for creating typed functions from a plain function + having a property `signature`. +- Implemented providing a name when merging multiple typed functions. + + +## 2018-07-04, version 1.0.4 + +- By default, `addType` will insert new types before the `Object` test + since the `Object` test also matches arrays and classes. +- Upgraded `devDependencies`. + + +## 2018-03-17, version 1.0.3 + +- Dropped usage of ES6 feature `Array.find`, so typed-function is + directly usable on any ES5 compatible JavaScript engine (like IE11). + + +## 2018-03-17, version 1.0.2 + +- Fixed typed-function not working on browsers that don't allow + setting the `name` property of a function. + + +## 2018-02-21, version 1.0.1 + +- Upgraded dev dependencies. + + +## 2018-02-20, version 1.0.0 + +Version 1.0.0 is rewritten from scratch. The API is the same, +though generated error messages may differ slightly. + +Version 1.0.0 no longer uses `eval` under the hood to achieve good +performance. This reduces security risks and makes typed-functions +easier to debug. + +Type `Object` is no longer treated specially from other types. This +means that the test for `Object` must not give false positives for +types like `Array`, `Date`, or class instances. + +In version 1.0.0, support for browsers like IE9, IE10 is dropped, +though typed-function can still work when using es5 and es6 polyfills. + + +## 2018-01-24, version 0.10.7 + +- Fixed the field `data.actual` in a `TypeError` message containing + the type index instead of the actual type of the argument. + + +## 2017-11-18, version 0.10.6 + +- Fixed a security issue allowing to execute arbitrary JavaScript + code via a specially prepared function name of a typed function. + Thanks Masato Kinugawa. + + +## 2016-11-18, version 0.10.5 + +- Fixed the use of multi-layered use of `any` type. See #8. + + +## 2016-04-09, version 0.10.4 + +- Typed functions can only inherit names from other typed functions and no + longer from regular JavaScript functions since these names are unreliable: + they can be manipulated by minifiers and browsers. + + +## 2015-10-07, version 0.10.3 + +- Reverted the fix of v0.10.2 until the introduced issue with variable + arguments is fixed too. Added unit test for the latter case. + + +## 2015-10-04, version 0.10.2 + +- Fixed support for using `any` multiple times in a single signture. + Thanks @luke-gumbley. + + +## 2015-07-27, version 0.10.1 + +- Fixed functions `addType` and `addConversion` not being robust against + replaced arrays `typed.types` and `typed.conversions`. + + +## 2015-07-26, version 0.10.0 + +- Dropped support for the following construction signatures in order to simplify + the API: + - `typed(signature: string, fn: function)` + - `typed(name: string, signature: string, fn: function)` +- Implemented convenience methods `typed.addType` and `typed.addConversion`. +- Changed the casing of the type `'function'` to `'Function'`. Breaking change. +- `typed.types` is now an ordered Array containing objects + `{name: string, test: function}`. Breaking change. +- List with expected types in error messages no longer includes converted types. + + +## 2015-05-17, version 0.9.0 + +- `typed.types` is now an ordered Array containing objects + `{type: string, test: function}` instead of an object. Breaking change. +- `typed-function` now allows merging typed functions with duplicate signatures + when they point to the same function. + + +## 2015-05-16, version 0.8.3 + +- Function `typed.find` now throws an error instead of returning `null` when a + signature is not found. +- Fixed: the attached signatures no longer contains signatures with conversions. + + +## 2015-05-09, version 0.8.2 + +- Fixed function `typed.convert` not handling the case where the value already + has the requested type. Thanks @rjbaucells. + + +## 2015-05-09, version 0.8.1 + +- Implemented option `typed.ignore` to ignore/filter signatures of a typed + function. + + +## 2015-05-09, version 0.8.0 + +- Implemented function `create` to create a new instance of typed-function. +- Implemented a utility function `convert(value, type)` (#1). +- Implemented a simple `typed.find` function to find the implementation of a + specific function signature. +- Extended the error messages to denote the function name, like `"Too many + arguments in function foo (...)"`. + + +## 2015-04-17, version 0.7.0 + +- Performance improvements. + + +## 2015-03-08, version 0.6.3 + +- Fixed generated internal Signature and Param objects not being cleaned up + after the typed function has been generated. + + +## 2015-02-26, version 0.6.2 + +- Fixed a bug sometimes not ordering the handling of any type arguments last. +- Fixed a bug sometimes not choosing the signature with the lowest number of + conversions. + + +## 2015-02-07, version 0.6.1 + +- Large code refactoring. +- Fixed bugs related to any type parameters. + + +## 2015-01-16, version 0.6.0 + +- Removed the configuration option `minify` + (it's not clear yet whether minifying really improves the performance). +- Internal code simplifications. +- Bug fixes. + + +## 2015-01-07, version 0.5.0 + +- Implemented support for merging typed functions. +- Typed functions inherit the name of the function in case of one signature. +- Fixed a bug where a regular argument was not matched when there was a + signature with variable arguments too. +- Slightly changed the error messages. + + +## 2014-12-17, version 0.4.0 + +- Introduced new constructor options, create a typed function as + `typed([name,] signature, fn)` or `typed([name,] signatures)`. +- Support for multiple types per parameter like `number | string, number'`. +- Support for variable parameters like `sting, ...number'`. +- Changed any type notation `'*'` to `'any'`. +- Implemented detailed error messages. +- Implemented option `typed.config.minify`. + + +## 2014-11-05, version 0.3.1 + +- Renamed module to `typed-function`. + + +## 2014-11-05, version 0.3.0 + +- Implemented support for any type arguments (denoted with `*`). + + +## 2014-10-23, version 0.2.0 + +- Implemented support for named functions. +- Implemented support for type conversions. +- Implemented support for custom types. +- Library packaged as UMD, usable with CommonJS (node.js), AMD, and browser globals. + + +## 2014-10-21, version 0.1.0 + +- Implemented support for functions with zero, one, or multiple arguments. + + +## 2014-10-19, version 0.0.1 + +- First release (no functionality yet) diff --git a/node_modules/typed-function/LICENSE b/node_modules/typed-function/LICENSE new file mode 100644 index 0000000..3e0d27f --- /dev/null +++ b/node_modules/typed-function/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2018 Jos de Jong + +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. diff --git a/node_modules/typed-function/README.md b/node_modules/typed-function/README.md new file mode 100644 index 0000000..8fdc6b8 --- /dev/null +++ b/node_modules/typed-function/README.md @@ -0,0 +1,480 @@ +# typed-function + +[![Version](https://img.shields.io/npm/v/typed-function.svg)](https://www.npmjs.com/package/typed-function) +[![Downloads](https://img.shields.io/npm/dm/typed-function.svg)](https://www.npmjs.com/package/typed-function) +[![Build Status](https://github.com/josdejong/typed-function/workflows/Node.js%20CI/badge.svg)](https://github.com/josdejong/typed-function/actions) + +Move type checking logic and type conversions outside of your function in a +flexible, organized way. Automatically throw informative errors in case of +wrong input arguments. + + +## Features + +typed-function has the following features: + +- Runtime type-checking of input arguments. +- Automatic type conversion of arguments. +- Compose typed functions with multiple signatures. +- Supports union types, any type, and variable arguments. +- Detailed error messaging. + +Supported environments: node.js, Chrome, Firefox, Safari, Opera, IE11+. + + +## Why? + +In JavaScript, functions can be called with any number and any type of arguments. +When writing a function, the easiest way is to just assume that the function +will be called with the correct input. This leaves the function's behavior on +invalid input undefined. The function may throw some error, or worse, +it may silently fail or return wrong results. Typical errors are +*TypeError: undefined is not a function* or *TypeError: Cannot call method +'request' of undefined*. These error messages are not very helpful. It can be +hard to debug them, as they can be the result of a series of nested function +calls manipulating and propagating invalid or incomplete data. + +Often, JavaScript developers add some basic type checking where it is important, +using checks like `typeof fn === 'function'`, `date instanceof Date`, and +`Array.isArray(arr)`. For functions supporting multiple signatures, +the type checking logic can grow quite a bit, and distract from the actual +logic of the function. + +For functions dealing with a considerable amount of type checking and conversion +logic, or functions facing a public API, it can be very useful to use the +`typed-function` module to handle the type-checking logic. This way: + +- Users of the function get useful and consistent error messages when using + the function wrongly. +- The function cannot silently fail or silently give wrong results due to + invalid input. +- Correct type of input is assured inside the function. The function's code + becomes easier to understand as it only contains the actual function logic. + Lower level utility functions called by the type-checked function can + possibly be kept simpler as they don't need to do additional type checking. + +It's important however not to *overuse* type checking: + +- Locking down the type of input that a function accepts can unnecessarily + limit its flexibility. Keep functions as flexible and forgiving as possible, + follow the + [robustness principle](http://en.wikipedia.org/wiki/Robustness_principle) + here: "be liberal in what you accept and conservative in what you send" + (Postel's law). +- There is no need to apply type checking to *all* functions. It may be + enough to apply type checking to one tier of public facing functions. +- There is a performance penalty involved for all type checking, so applying + it everywhere can unnecessarily worsen the performance. + + +## Load + +Install via npm: + + npm install typed-function + + +## Usage + +Here are some usage examples. More examples are available in the +[/examples](/examples) folder. + +```js +var typed = require('typed-function'); + +// create a typed function +var fn1 = typed({ + 'number, string': function (a, b) { + return 'a is a number, b is a string'; + } +}); + +// create a typed function with multiple types per argument (type union) +var fn2 = typed({ + 'string, number | boolean': function (a, b) { + return 'a is a string, b is a number or a boolean'; + } +}); + +// create a typed function with any type argument +var fn3 = typed({ + 'string, any': function (a, b) { + return 'a is a string, b can be anything'; + } +}); + +// create a typed function with multiple signatures +var fn4 = typed({ + 'number': function (a) { + return 'a is a number'; + }, + 'number, boolean': function (a, b) { + return 'a is a number, b is a boolean'; + }, + 'number, number': function (a, b) { + return 'a is a number, b is a number'; + } +}); + +// create a typed function from a plain function with signature +function fnPlain(a, b) { + return 'a is a number, b is a string'; +} +fnPlain.signature = 'number, string'; +var fn5 = typed(fnPlain); + +// use the functions +console.log(fn1(2, 'foo')); // outputs 'a is a number, b is a string' +console.log(fn4(2)); // outputs 'a is a number' + +// calling the function with a non-supported type signature will throw an error +try { + fn2('hello', 'world'); +} +catch (err) { + console.log(err.toString()); + // outputs: TypeError: Unexpected type of argument. + // Expected: number or boolean, actual: string, index: 1. +} +``` + + +## Types + +typed-function has the following built-in types: + +- `null` +- `boolean` +- `number` +- `string` +- `Function` +- `Array` +- `Date` +- `RegExp` +- `Object` + +The following type expressions are supported: + +- Multiple arguments: `string, number, Function` +- Union types: `number | string` +- Variable arguments: `...number` +- Any type: `any` + + +## API + +### Construction + +A typed function can be constructed in two ways: + +- Create from an object with one or multiple signatures: + + ``` + typed(signatures: Object.) : function + typed(name: string, signatures: Object.) : function + ``` + +- Merge multiple typed functions into a new typed function: + + ``` + typed(functions: ...function) : function + typed(name: string, functions: ...function) : function + ``` + + Each function in `functions` can be either a typed function created before, + or a plain function having a `signature` property. + + +### Methods + +- `typed.convert(value: *, type: string) : *` + + Convert a value to another type. Only applicable when conversions have + been defined in `typed.conversions` (see section [Properties](#properties)). + Example: + + ```js + typed.conversions.push({ + from: 'number', + to: 'string', + convert: function (x) { + return +x; + }); + + var str = typed.convert(2.3, 'string'); // '2.3' + ``` + +- `typed.create() : function` + + Create a new, isolated instance of typed-function. Example: + + ```js + var typed = require('typed-function'); // default instance + var typed2 = typed.create(); // a second instance + ``` + + This would allow you, for example, to have two different type hierarchies + for different purposes. + +- `typed.find(fn: typed-function, signature: string | Array) : function | null` + + Find a specific signature from a typed function. The function currently + only finds exact matching signatures. + + For example: + + ```js + var fn = typed(...); + var f = typed.find(fn, ['number', 'string']); + var f = typed.find(fn, 'number, string'); + ``` + +- `typed.addType(type: {name: string, test: function} [, beforeObjectTest=true]): void` + + Add a new type. A type object contains a name and a test function. + The order of the types determines in which order function arguments are + type-checked, so for performance it's important to put the most used types + first. All types are added to the Array `typed.types`. + + Example: + + ```js + function Person(...) { + ... + } + + Person.prototype.isPerson = true; + + typed.addType({ + name: 'Person', + test: function (x) { + return x && x.isPerson === true; + } + }); + ``` + + By default, the new type will be inserted before the `Object` test + because the `Object` test also matches arrays and classes and hence + `typed-function` would never reach the new type. When `beforeObjectTest` + is `false`, the new type will be added at the end of all tests. + +- `typed.addConversion(conversion: {from: string, to: string, convert: function}) : void` + + Add a new conversion. Conversions are added to the Array `typed.conversions`. + + ```js + typed.addConversion({ + from: 'boolean', + to: 'number', + convert: function (x) { + return +x; + }); + ``` + + Note that any typed functions created before this conversion is added will + not have their arguments undergo this new conversion automatically, so it is + best to add all of your desired automatic conversions before defining any + typed functions. + +- `typed.createError(name: string, args: Array., signatures: Array.): TypeError` + + Generates a custom error object reporting the problem with calling + the typed function of the given `name` with the given `signatures` on the + actual arguments `args`. Note the error object has an extra property `data` + giving the details of the problem. This method is primarily useful in + writing your own handler for a type mismatch (see the `typed.onMismatch` + property below), in case you have tried to recover but end up deciding + you want to throw the error that the default handler would have. + +### Properties + +- `typed.types: Array.<{name: string, test: function}>` + + Array with types. Each object contains a type name and a test function. + The order of the types determines in which order function arguments are + type-checked, so for performance it's important to put the most used types + first. Custom types can be added like: + + ```js + function Person(...) { + ... + } + + Person.prototype.isPerson = true; + + typed.types.push({ + name: 'Person', + test: function (x) { + return x && x.isPerson === true; + } + }); + ``` + +- `typed.conversions: Array.<{from: string, to: string, convert: function}>` + + An Array with built-in conversions. Empty by default. Can be used to define + conversions from `boolean` to `number`. For example: + + ```js + typed.conversions.push({ + from: 'boolean', + to: 'number', + convert: function (x) { + return +x; + }); + ``` + + Also note the `addConversion()` method above for simply adding a single + conversion at a time. + +- `typed.ignore: Array.` + + An Array with names of types to be ignored when creating a typed function. + This can be useful to filter signatures when creating a typed function. + For example: + + ```js + // a set with signatures maybe loaded from somewhere + var signatures = { + 'number': function () {...}, + 'string': function () {...} + } + + // we want to ignore a specific type + typed.ignore = ['string']; + + // the created function fn will only contain the 'number' signature + var fn = typed('fn', signatures); + ``` + +- `typed.onMismatch: function` + + The handler called when a typed-function call fails to match with any + of its signatures. The handler is called with three arguments: the name + of the typed function being called, the actual argument list, and an array + of the signatures for the typed function being called. (Each signature is + an object with property 'signature' giving the actual signature and\ + property 'fn' giving the raw function for that signature.) The default + value of `onMismatch` is `typed.throwMismatchError`. + + This can be useful if you have a collection of functions and have common + behavior for any invalid call. For example, you might just want to log + the problem and continue: + + ``` + const myErrorLog = []; + typed.onMismatch = (name, args, signatures) => { + myErrorLog.push(`Invalid call of ${name} with ${args.length} arguments.`); + return null; + }; + typed.sqrt(9); // assuming definition as above, will return 3 + typed.sqrt([]); // no error will be thrown; will return null. + console.log(`There have been ${myErrorLog.length} invalid calls.`) + ``` + + Note that there is only one `onMismatch` handler at a time; assigning a + new value discards the previous handler. To restore the default behavior, + just assign `typed.onMismatch = typed.throwMismatchError`. + + Finally note that this handler fires whenever _any_ typed function call + does not match any of its signatures. You can in effect define such a + "handler" for a single typed function by simply specifying an implementation + for the `...` signature: + + ``` + const lenOrNothing = typed({ + string: s => s.length, + '...': () => 0 + }); + console.log(lenOrNothing('Hello, world!')) // Output: 13 + console.log(lenOrNothing(57, 'varieties')) // Output: 0 + ``` + +### Recursion + +The `this` keyword can be used to self-reference the typed-function: + +```js +var sqrt = typed({ + 'number': function (value) { + return Math.sqrt(value); + }, + 'string': function (value) { + // on the following line we self reference the typed-function using "this" + return this(parseInt(value, 10)); + } +}); + +// use the typed function +console.log(sqrt('9')); // output: 3 +``` + + +### Output + +The functions generated with `typed({...})` have: + +- A function `toString`. Returns well readable code which can be used to see + what the function exactly does. Mostly for debugging purposes. +- A property `signatures`, which holds a map with the (normalized) + signatures as key and the original sub-functions as value. +- A property `name` containing the name of the typed function, if it was + assigned one at creation, or an empty string. + + +## Roadmap + +### Version 2 + +- Be able to turn off exception throwing. +- Extend function signatures: + - Optional arguments like `'[number], array'` or like `number=, array` + - Nullable arguments like `'?Object'` +- Create a good benchmark, to get insight in the overhead. +- Allow conversions to fail (for example string to number is not always + possible). Call this `fallible` or `optional`? + +### Version 3 + +- Extend function signatures: + - Constants like `'"linear" | "cubic"'`, `'0..10'`, etc. + - Object definitions like `'{name: string, age: number}'` + - Object definitions like `'Object.'` + - Array definitions like `'Array.'` +- Improve performance of both generating a typed function as well as + the performance and memory footprint of a typed function. + + +## Test + +To test the library, run: + + npm test + + +## Minify + +To generate the minified version of the library, run: + + npm run minify + + +## Publish + +1. Describe the changes in `HISTORY.md` +2. Increase the version number in `package.json` +3. Test and build: + ``` + npm install + npm run build + npm test + ``` +4. Verify whether the bundle and minified bundle works correctly by opening + `./test/browser.html` and `./test/browser.min.html` in your browser. +5. Commit the changes +6. Merge `develop` into `master`, and push `master` +7. Create a git tag, and pus this +8. publish the library: + ``` + npm publish + ``` diff --git a/node_modules/typed-function/benchmark/benchmark.js b/node_modules/typed-function/benchmark/benchmark.js new file mode 100644 index 0000000..9decd06 --- /dev/null +++ b/node_modules/typed-function/benchmark/benchmark.js @@ -0,0 +1,71 @@ +// +// typed-function benchmark +// +// WARNING: be careful, these are micro-benchmarks, which can only be used +// to get an indication of the performance. Real performance and +// bottlenecks should be assessed in real world applications, +// not in micro-benchmarks. +// +// Before running, make sure you've installed the needed packages which +// are defined in the devDependencies of the project. +// +// To create a bundle: +// +// browserify -o benchmark/benchmark.bundle.js benchmark/benchmark.js +// + +'use strict'; + +var assert = require('assert'); +var Benchmark = require('benchmark'); +var padRight = require('pad-right'); +var typed = require('../typed-function'); + +// expose on window when using bundled in a browser +if (typeof window !== 'undefined') { + window['Benchmark'] = Benchmark; +} + +function add(x, y) { + return x + y; +} + +var signatures = { + 'number, number': add, + 'boolean, boolean': add, + 'Date, Date': add, + 'string, string': add +}; + +var addTyped = typed('add', signatures); + +assert(add(2,3), 5); +assert(addTyped(2,3), 5); +assert(addTyped('hello', 'world'), 'helloworld'); +assert.throws(function () { addTyped(1) }, /TypeError/) +assert.throws(function () { addTyped(1,2,3) }, /TypeError/) + +var result = 0; +var suite = new Benchmark.Suite(); +suite + .add(pad('typed add'), function() { + result += addTyped(result, 4); + result += addTyped(String(result), 'world').length; + }) + .add(pad('native add'), function() { + result += add(result, 4); + result += add(String(result), 'world').length; + }) + .on('cycle', function(event) { + console.log(String(event.target)); + }) + .on('complete', function() { + if (result > Infinity) { + console.log() + } + }) + .run(); + +function pad (text) { + return padRight(text, 20, ' '); +} diff --git a/node_modules/typed-function/examples/any_type.js b/node_modules/typed-function/examples/any_type.js new file mode 100644 index 0000000..127b263 --- /dev/null +++ b/node_modules/typed-function/examples/any_type.js @@ -0,0 +1,12 @@ +var typed = require('../typed-function'); + +// create a typed function with an any type argument +var log = typed({ + 'string, any': function (event, data) { + console.log('event: ' + event + ', data: ' + JSON.stringify(data)); + } +}); + +// use the typed function +log('start', {count: 2}); // output: 'event: start, data: {"count":2}' +log('end', 'success!'); // output: 'event: start, data: "success!" diff --git a/node_modules/typed-function/examples/basic_usage.js b/node_modules/typed-function/examples/basic_usage.js new file mode 100644 index 0000000..4c4649b --- /dev/null +++ b/node_modules/typed-function/examples/basic_usage.js @@ -0,0 +1,56 @@ +var typed = require('../typed-function'); + +// create a typed function +var fn1 = typed({ + 'number, string': function (a, b) { + return 'a is a number, b is a string'; + } +}); + +// create a typed function with multiple types per argument (type union) +var fn2 = typed({ + 'string, number | boolean': function (a, b) { + return 'a is a string, b is a number or a boolean'; + } +}); + +// create a typed function with any type argument +var fn3 = typed({ + 'string, any': function (a, b) { + return 'a is a string, b can be anything'; + } +}); + +// create a typed function with multiple signatures +var fn4 = typed({ + 'number': function (a) { + return 'a is a number'; + }, + 'number, boolean': function (a, b) { + return 'a is a number, b is a boolean'; + }, + 'number, number': function (a, b) { + return 'a is a number, b is a number'; + } +}); + +// create a typed function from a plain function with signature +function fnPlain(a, b) { + return 'a is a number, b is a string'; +} +fnPlain.signature = 'number, string'; +var fn5 = typed(fnPlain); + +// use the functions +console.log(fn1(2, 'foo')); // outputs 'a is a number, b is a string' +console.log(fn4(2)); // outputs 'a is a number' + +// calling the function with a non-supported type signature will throw an error +try { + fn2('hello', 'world'); +} +catch (err) { + console.log(err.toString()); + // outputs: TypeError: Unexpected type of argument. + // Expected: number or boolean, actual: string, index: 1. +} diff --git a/node_modules/typed-function/examples/browser.html b/node_modules/typed-function/examples/browser.html new file mode 100644 index 0000000..8f6f0dc --- /dev/null +++ b/node_modules/typed-function/examples/browser.html @@ -0,0 +1,20 @@ + + + + typed-function | basic usage + + + + + + \ No newline at end of file diff --git a/node_modules/typed-function/examples/browser_amd.html b/node_modules/typed-function/examples/browser_amd.html new file mode 100644 index 0000000..6bbeb2c --- /dev/null +++ b/node_modules/typed-function/examples/browser_amd.html @@ -0,0 +1,25 @@ + + + + typed-function | basic usage with amd + + + + + + + + \ No newline at end of file diff --git a/node_modules/typed-function/examples/custom_type.js b/node_modules/typed-function/examples/custom_type.js new file mode 100644 index 0000000..696a359 --- /dev/null +++ b/node_modules/typed-function/examples/custom_type.js @@ -0,0 +1,39 @@ +var typed = require('../typed-function'); + +// create a prototype +function Person(params) { + this.name = params.name; + this.age = params.age; +} + +// register a test for this new type +typed.addType({ + name: 'Person', + test: function (x) { + return x instanceof Person; + } +}); + +// create a typed function +var stringify = typed({ + 'Person': function (person) { + return JSON.stringify(person); + } +}); + +// use the function +var person = new Person({name: 'John', age: 28}); + +console.log(stringify(person)); +// outputs: '{"name":"John","age":28}' + +// calling the function with a non-supported type signature will throw an error +try { + stringify('ooops'); +} +catch (err) { + console.log('Wrong input will throw an error:'); + console.log(' ' + err.toString()); + // outputs: TypeError: Unexpected type of argument (expected: Person, + // actual: string, index: 0) +} diff --git a/node_modules/typed-function/examples/merge_plain_functions.js b/node_modules/typed-function/examples/merge_plain_functions.js new file mode 100644 index 0000000..85b3cff --- /dev/null +++ b/node_modules/typed-function/examples/merge_plain_functions.js @@ -0,0 +1,20 @@ +var typed = require('../typed-function'); + +// create a couple of plain functions with a signature +function fn1 (a) { + return a + a; +} +fn1.signature = 'number'; + +function fn2 (a) { + var value = +a; + return value + value; +} +fn2.signature = 'string'; + +// merge multiple typed functions +var fn3 = typed('fn3', fn1, fn2); + +// use merged function +console.log(fn3(2)); // outputs 4 +console.log(fn3('3')); // outputs 6 diff --git a/node_modules/typed-function/examples/merge_typed_functions.js b/node_modules/typed-function/examples/merge_typed_functions.js new file mode 100644 index 0000000..decbd27 --- /dev/null +++ b/node_modules/typed-function/examples/merge_typed_functions.js @@ -0,0 +1,21 @@ +var typed = require('../typed-function'); + +// create a couple of typed functions +var fn1 = typed({ + 'number': function (a) { + return a + a; + } +}); +var fn2 = typed({ + 'string': function (a) { + var value = +a; + return value + value; + } +}); + +// merge multiple typed functions +var fn3 = typed(fn1, fn2); + +// use merged function +console.log(fn3(2)); // outputs 4 +console.log(fn3('3')); // outputs 6 diff --git a/node_modules/typed-function/examples/multiple_signatures.js b/node_modules/typed-function/examples/multiple_signatures.js new file mode 100644 index 0000000..546076a --- /dev/null +++ b/node_modules/typed-function/examples/multiple_signatures.js @@ -0,0 +1,18 @@ +var typed = require('../typed-function'); + +// create a typed function with multiple signatures +var fn = typed({ + 'number': function (a) { + return 'a is a number'; + }, + 'number, boolean': function (a, b) { + return 'a is a number, b is a boolean'; + }, + 'number, number': function (a, b) { + return 'a is a number, b is a number'; + } +}); + +// use the function +console.log(fn(2, true)); // outputs 'a is a number, b is a boolean' +console.log(fn(2)); // outputs 'a is a number' diff --git a/node_modules/typed-function/examples/recursion.js b/node_modules/typed-function/examples/recursion.js new file mode 100644 index 0000000..7dad474 --- /dev/null +++ b/node_modules/typed-function/examples/recursion.js @@ -0,0 +1,14 @@ +var typed = require('../typed-function'); + +// create a typed function that invokes itself +var sqrt = typed({ + 'number': function (value) { + return Math.sqrt(value); + }, + 'string': function (value) { + return this(parseInt(value, 10)); + } +}); + +// use the typed function +console.log(sqrt("9")); // output: 3 diff --git a/node_modules/typed-function/examples/rest_parameters.js b/node_modules/typed-function/examples/rest_parameters.js new file mode 100644 index 0000000..35eaa7a --- /dev/null +++ b/node_modules/typed-function/examples/rest_parameters.js @@ -0,0 +1,16 @@ +var typed = require('../typed-function'); + +// create a typed function with a variable number of arguments +var sum = typed({ + '...number': function (values) { + var sum = 0; + for (var i = 0; i < values.length; i++) { + sum += values[i]; + } + return sum; + } +}); + +// use the typed function +console.log(sum(2, 3)); // output: 5 +console.log(sum(2, 3, 1, 2)); // output: 8 diff --git a/node_modules/typed-function/examples/type_conversion.js b/node_modules/typed-function/examples/type_conversion.js new file mode 100644 index 0000000..2a4eb3a --- /dev/null +++ b/node_modules/typed-function/examples/type_conversion.js @@ -0,0 +1,53 @@ +var typed = require('../typed-function'); + +// define type conversions that we want to support order is important. +// There is also an utility function typed.addConversion(conversion) for this. +typed.conversions = [ + { + from: 'boolean', + to: 'number', + convert: function (x) { + return +x; + } + }, + { + from: 'boolean', + to: 'string', + convert: function (x) { + return x + ''; + } + }, + { + from: 'number', + to: 'string', + convert: function (x) { + return x + ''; + } + } +]; + +// create a typed function with multiple signatures +// +// where possible, the created function will automatically convert booleans to +// numbers or strings, and convert numbers to strings. +// +// note that the length property is only available on strings, and the toFixed +// function only on numbers, so this requires the right type of argument else +// the function will throw an exception. +var fn = typed({ + 'string': function (name) { + return 'Name: ' + name + ', length: ' + name.length; + }, + 'string, number': function (name, value) { + return 'Name: ' + name + ', length: ' + name.length + ', value: ' + value.toFixed(3); + } +}); + +// use the function the regular way +console.log(fn('foo')); // outputs 'Name: foo, length: 3' +console.log(fn('foo', 2/3)); // outputs 'Name: foo, length: 3, value: 0.667' + +// calling the function with non-supported but convertible types +// will work just fine: +console.log(fn(false)); // outputs 'Name: false, length: 5' +console.log(fn('foo', true)); // outputs 'Name: foo, length: 3, value: 1.000' diff --git a/node_modules/typed-function/package.json b/node_modules/typed-function/package.json new file mode 100644 index 0000000..c16ed54 --- /dev/null +++ b/node_modules/typed-function/package.json @@ -0,0 +1,41 @@ +{ + "name": "typed-function", + "version": "2.1.0", + "description": "Type checking for JavaScript functions", + "author": "Jos de Jong (https://github.com/josdejong)", + "contributors": [ + "Luke Gumbley (https://github.com/luke-gumbley)" + ], + "homepage": "https://github.com/josdejong/typed-function", + "repository": { + "type": "git", + "url": "https://github.com/josdejong/typed-function.git" + }, + "keywords": [ + "typed", + "function", + "arguments", + "compose", + "types" + ], + "dependencies": {}, + "devDependencies": { + "benchmark": "2.1.4", + "brace-expansion": "2.0.1", + "istanbul": "0.4.5", + "mocha": "8.3.2", + "pad-right": "0.2.2", + "uglify-js": "3.13.3" + }, + "comment": "brace-expansion is installed because an old insecure version is used by one of the dev depencencies (under istanbul)", + "main": "typed-function.js", + "scripts": { + "build": "uglifyjs typed-function.js -o typed-function.min.js -c -m", + "test": "mocha test --recursive", + "coverage": "istanbul cover _mocha -- test --recursive; echo \"\nCoverage report is available at ./coverage/lcov-report/index.html\"", + "prepublishOnly": "npm test && npm run build" + }, + "engines": { + "node": ">= 10" + } +} diff --git a/node_modules/typed-function/test/any_type.test.js b/node_modules/typed-function/test/any_type.test.js new file mode 100644 index 0000000..c85c771 --- /dev/null +++ b/node_modules/typed-function/test/any_type.test.js @@ -0,0 +1,220 @@ +var assert = require('assert'); +var typed = require('../typed-function'); + +describe('any type', function () { + + it('should compose a function with one any type argument', function() { + var fn = typed({ + 'any': function (value) { + return 'any:' + value; + }, + 'string': function (value) { + return 'string:' + value; + }, + 'boolean': function (value) { + return 'boolean:' + value; + } + }); + + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 3); + assert.equal(fn(2), 'any:2'); + assert.equal(fn([1,2,3]), 'any:1,2,3'); + assert.equal(fn('foo'), 'string:foo'); + assert.equal(fn(false), 'boolean:false'); + }); + + it('should compose a function with multiple any type arguments (1)', function() { + var fn = typed({ + 'any,boolean': function () { + return 'any,boolean'; + }, + 'any,string': function () { + return 'any,string'; + } + }); + + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 2); + assert.equal(fn([],true), 'any,boolean'); + assert.equal(fn(2,'foo'), 'any,string'); + assert.throws(function () {fn([], new Date())}, /TypeError: Unexpected type of argument in function unnamed \(expected: string or boolean, actual: Date, index: 1\)/); + assert.throws(function () {fn(2, 2)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string or boolean, actual: number, index: 1\)/); + assert.throws(function () {fn(2)}, /TypeError: Too few arguments in function unnamed \(expected: string or boolean, index: 1\)/); + }); + + it('should compose a function with multiple any type arguments (2)', function() { + var fn = typed({ + 'any,boolean': function () { + return 'any,boolean'; + }, + 'any,number': function () { + return 'any,number'; + }, + 'string,any': function () { + return 'string,any'; + } + }); + + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 3); + assert.equal(fn([],true), 'any,boolean'); + assert.equal(fn([],2), 'any,number'); + assert.equal(fn('foo', 2), 'string,any'); + assert.throws(function () {fn([], new Date())}, /TypeError: Unexpected type of argument in function unnamed \(expected: number or boolean, actual: Date, index: 1\)/); + assert.throws(function () {fn([], 'foo')}, /TypeError: Unexpected type of argument in function unnamed \(expected: number or boolean, actual: string, index: 1\)/) + }); + + it('should compose a function with multiple any type arguments (3)', function() { + var fn = typed({ + 'string,any': function () { + return 'string,any'; + }, + 'any': function () { + return 'any'; + } + }); + + assert(fn.signatures instanceof Object); + assert.deepEqual(Object.keys(fn.signatures), ['string,any', 'any']); + assert.equal(fn('foo', 2), 'string,any'); + assert.equal(fn([]), 'any'); + assert.equal(fn('foo'), 'any'); + assert.throws(function () {fn()}, /TypeError: Too few arguments in function unnamed \(expected: any, index: 0\)/); + assert.throws(function () {fn([], 'foo')}, /TypeError: Too many arguments in function unnamed \(expected: 1, actual: 2\)/); + assert.throws(function () {fn('foo', 4, [])}, /TypeError: Too many arguments in function unnamed \(expected: 2, actual: 3\)/); + }); + + it('should compose a function with multiple any type arguments (4)', function() { + var fn = typed('fn1', { + 'number,number': function () { + return 'number,number'; + }, + 'any,string': function () { + return 'any,string'; + } + }); + + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 2); + assert.equal(fn(2, 2), 'number,number'); + assert.equal(fn(2, 'foo'), 'any,string'); + assert.throws(function () {fn('foo')}, /TypeError: Too few arguments in function fn1 \(expected: string, index: 1\)/); + assert.throws(function () {fn(1,2,3)}, /TypeError: Too many arguments in function fn1 \(expected: 2, actual: 3\)/); + }); + + it('should compose a function with multiple any type arguments (5)', function() { + var fn = typed({ + 'string,string': function () { + return 'string,string'; + }, + 'any': function () { + return 'any'; + } + }); + + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 2); + assert.equal(fn('foo', 'bar'), 'string,string'); + assert.equal(fn([]), 'any'); + assert.equal(fn('foo'), 'any'); + assert.throws(function () {fn('foo', 'bar', 5)}, /TypeError: Too many arguments in function unnamed \(expected: 2, actual: 3\)/); + assert.throws(function () {fn('foo', 2, 5)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string, actual: number, index: 1\)/); + assert.throws(function () {fn('foo', 'bar', 5)}, /TypeError: Too many arguments in function unnamed \(expected: 2, actual: 3\)/); + }); + + it('var arg any type arguments should only handle unmatched types', function() { + var fn = typed({ + 'Array,string': function () { + return 'Array,string'; + }, + '...': function () { + return 'any'; + } + }); + + assert.equal(fn([], 'foo'), 'Array,string'); + assert.equal(fn([], 'foo', 'bar'), 'any'); + assert.equal(fn('string'), 'any'); + assert.equal(fn(2), 'any'); + assert.equal(fn(2,3,4), 'any'); + assert.equal(fn([]), 'any'); + assert.throws(function () {fn()}, /TypeError: Too few arguments in function unnamed \(expected: any, index: 0\)/); + }); + + it('multiple use of any', function() { + var fn = typed({ + 'number,number': function () { + return 'numbers'; + }, + 'any,any': function () { + return 'any'; + } + }); + + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 2); + assert.equal(fn('a','b'), 'any'); + assert.equal(fn(1,1), 'numbers'); + assert.equal(fn(1,'b'), 'any'); + assert.equal(fn('a',1), 'any'); + }); + + it('use one any in combination with vararg', function() { + var fn = typed({ + 'number': function () { + return 'numbers'; + }, + 'any,...any': function () { + return 'any'; + } + }); + + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 2); + assert.equal(fn('a','b'), 'any'); + assert.equal(fn(1), 'numbers'); + assert.equal(fn(1,'b'), 'any'); + assert.equal(fn('a',2), 'any'); + assert.equal(fn(1,2), 'any'); + assert.equal(fn(1,2,3), 'any'); + }); + + it('use multi-layered any in combination with vararg', function() { + var fn = typed({ + 'number,number': function () { + return 'numbers'; + }, + 'any,any,...any': function () { + return 'any'; + } + }); + + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 2); + assert.equal(fn('a','b','c'), 'any'); + assert.equal(fn(1,2), 'numbers'); + assert.equal(fn(1,'b',2), 'any'); + assert.equal(fn('a',2,3), 'any'); + assert.equal(fn(1,2,3), 'any'); + }); + + it('should permit multi-layered use of any', function() { + var fn = typed({ + 'any,any': function () { + return 'two'; + }, + 'number,number,string': function () { + return 'three'; + } + }); + + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 2); + assert.equal(fn('a','b'), 'two'); + assert.equal(fn(1,1), 'two'); + assert.equal(fn(1,1,'a'), 'three'); + assert.throws(function () {fn(1,1,1)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string, actual: number, index: 2\)/); + }); + +}); diff --git a/node_modules/typed-function/test/browser.html b/node_modules/typed-function/test/browser.html new file mode 100644 index 0000000..01a216b --- /dev/null +++ b/node_modules/typed-function/test/browser.html @@ -0,0 +1,20 @@ + + + + browser test + + + + + + \ No newline at end of file diff --git a/node_modules/typed-function/test/browser.min.html b/node_modules/typed-function/test/browser.min.html new file mode 100644 index 0000000..db452b4 --- /dev/null +++ b/node_modules/typed-function/test/browser.min.html @@ -0,0 +1,20 @@ + + + + browser test - minified file + + + + + + \ No newline at end of file diff --git a/node_modules/typed-function/test/compose.test.js b/node_modules/typed-function/test/compose.test.js new file mode 100644 index 0000000..5e2c625 --- /dev/null +++ b/node_modules/typed-function/test/compose.test.js @@ -0,0 +1,77 @@ +var assert = require('assert'); +var typed = require('../typed-function'); + +describe('compose', function () { + + it('should create a composed function with multiple types per argument', function() { + var fn = typed({ + 'string | number, boolean': function () {return 'A';}, + 'boolean, boolean | number': function () {return 'B';}, + 'string': function () {return 'C';} + }); + + assert.equal(fn('str', false), 'A'); + assert.equal(fn(2, true), 'A'); + assert.equal(fn(false, true), 'B'); + assert.equal(fn(false, 2), 'B'); + assert.equal(fn('str'), 'C'); + // FIXME: should return correct error message + assert.throws(function () {fn()}, /TypeError: Too few arguments in function unnamed \(expected: number or string or boolean, index: 0\)/); + assert.throws(function () {fn(1,2,3)}, /TypeError: Unexpected type of argument in function unnamed \(expected: boolean, actual: number, index: 1\)/); + assert.throws(function () {fn('str', 2)}, /TypeError: Unexpected type of argument in function unnamed \(expected: boolean, actual: number, index: 1\)/); + assert.throws(function () {fn(true, 'str')},/TypeError: Unexpected type of argument in function unnamed \(expected: number or boolean, actual: string, index: 1\)/); + assert.throws(function () {fn(2, 3)}, /TypeError: Unexpected type of argument in function unnamed \(expected: boolean, actual: number, index: 1\)/); + assert.throws(function () {fn(2, 'str')}, /TypeError: Unexpected type of argument in function unnamed \(expected: boolean, actual: string, index: 1\)/); + }); + + // TODO: test whether the constructor throws errors when providing wrong arguments to typed(...) + + it('should compose a function with one argument', function() { + var signatures = { + 'number': function (value) { + return 'number:' + value; + }, + 'string': function (value) { + return 'string:' + value; + }, + 'boolean': function (value) { + return 'boolean:' + value; + } + }; + var fn = typed(signatures); + + assert.equal(fn(2), 'number:2'); + assert.equal(fn('foo'), 'string:foo'); + assert.equal(fn(false), 'boolean:false'); + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 3); + assert.strictEqual(fn.signatures['number'], signatures['number']); + assert.strictEqual(fn.signatures['string'], signatures['string']); + assert.strictEqual(fn.signatures['boolean'], signatures['boolean']); + }); + + it('should compose a function with multiple arguments', function() { + var signatures = { + 'number': function (value) { + return 'number:' + value; + }, + 'string': function (value) { + return 'string:' + value; + }, + 'number, boolean': function (a, b) { // mind space after the comma, should be normalized by composer + return 'number,boolean:' + a + ',' + b; + } + }; + var fn = typed(signatures); + + assert.equal(fn(2), 'number:2'); + assert.equal(fn('foo'), 'string:foo'); + assert.equal(fn(2, false), 'number,boolean:2,false'); + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 3); + assert.strictEqual(fn.signatures['number'], signatures['number']); + assert.strictEqual(fn.signatures['string'], signatures['string']); + assert.strictEqual(fn.signatures['number,boolean'], signatures['number, boolean']); + }); + +}); diff --git a/node_modules/typed-function/test/construction.test.js b/node_modules/typed-function/test/construction.test.js new file mode 100644 index 0000000..2e08c76 --- /dev/null +++ b/node_modules/typed-function/test/construction.test.js @@ -0,0 +1,371 @@ +// test parse +var assert = require('assert'); +var typed = require('../typed-function'); + +describe('construction', function() { + + it('should throw an error when not providing any signatures', function() { + assert.throws(function () { + typed({}); + }, /Error: No signatures provided/); + }); + + it('should create a named function', function() { + var fn = typed('myFunction', { + 'string': function (str) { + return 'foo'; + } + }); + + assert.equal(fn('bar'), 'foo'); + assert.equal(fn.name, 'myFunction'); + }); + + it('should create a typed function from a regular function with a signature', function() { + function myFunction(str) { + return 'foo'; + } + myFunction.signature = 'string' + + var fn = typed(myFunction); + + assert.equal(fn('bar'), 'foo'); + assert.equal(fn.name, 'myFunction'); + assert.deepEqual(Object.keys(fn.signatures), ['string']); + }); + + it('should create an unnamed function', function() { + var fn = typed({ + 'string': function (str) { + return 'foo'; + } + }); + + assert.equal(fn('bar'), 'foo'); + assert.equal(fn.name, ''); + }); + + it('should inherit the name of typed functions', function() { + var fn = typed({ + 'string': typed('fn1', { + 'string': function (str) { + return 'foo'; + } + }) + }); + + assert.equal(fn('bar'), 'foo'); + assert.equal(fn.name, 'fn1'); + }); + + it('should not inherit the name of the JavaScript functions (only from typed functions)', function() { + var fn = typed({ + 'string': function fn1 (str) { + return 'foo'; + } + }); + + assert.equal(fn('bar'), 'foo'); + assert.equal(fn.name, ''); + }); + + it('should compose a function with zero arguments', function() { + var signatures = { + '': function () { + return 'noargs'; + } + }; + var fn = typed(signatures); + + assert.equal(fn(), 'noargs'); + assert(fn.signatures instanceof Object); + assert.strictEqual(Object.keys(fn.signatures).length, 1); + assert.strictEqual(fn.signatures[''], signatures['']); + }); + + it('should create a typed function with one argument', function() { + var fn = typed({ + 'string': function () { + return 'string'; + } + }); + + assert.equal(fn('hi'), 'string'); + }); + + it('should create a typed function with two arguments', function() { + var fn = typed({ + 'string, boolean': function () { + return 'foo'; + } + }); + + assert.equal(fn('hi', true), 'foo'); + }); + + it('should create a named, typed function', function() { + var fn = typed('myFunction', { + 'string, boolean': function () { + return 'noargs'; + } + }); + + assert.equal(fn('hi', true), 'noargs'); + assert.equal(fn.name, 'myFunction'); + }); + + it('should correctly recognize Date from Object (both are an Object)', function() { + var signatures = { + 'Object': function (value) { + assert(value instanceof Object); + return 'Object'; + }, + 'Date': function (value) { + assert(value instanceof Date); + return 'Date'; + } + }; + var fn = typed(signatures); + + assert.equal(fn({foo: 'bar'}), 'Object'); + assert.equal(fn(new Date()), 'Date'); + }); + + it('should correctly handle null', function () { + var fn = typed({ + 'Object': function (a) { + return 'Object'; + }, + 'null': function (a) { + return 'null'; + }, + 'undefined': function (a) { + return 'undefined'; + } + }); + + assert.equal(fn(new Object(null)), 'Object'); + assert.equal(fn(null), 'null'); + assert.equal(fn(undefined), 'undefined'); + }); + + it('should throw correct error message when passing null from an Object', function() { + var signatures = { + 'Object': function (value) { + assert(value instanceof Object); + return 'Object'; + } + }; + var fn = typed(signatures); + + assert.equal(fn({}), 'Object'); + assert.throws(function () { fn(null) }, + /TypeError: Unexpected type of argument in function unnamed \(expected: Object, actual: null, index: 0\)/); + }); + + it('should create a new, isolated instance of typed-function', function() { + var typed1 = typed.create(); + var typed2 = typed.create(); + function Person() {} + + typed1.types.push({ + name: 'Person', + test: function (x) { + return x instanceof Person; + } + }); + + assert.strictEqual(typed.create, typed1.create); + assert.notStrictEqual(typed.types, typed1.types); + assert.notStrictEqual(typed.conversions, typed1.conversions); + + assert.strictEqual(typed.create, typed2.create); + assert.notStrictEqual(typed.types, typed2.types); + assert.notStrictEqual(typed.conversions, typed2.conversions); + + assert.strictEqual(typed1.create, typed2.create); + assert.notStrictEqual(typed1.types, typed2.types); + assert.notStrictEqual(typed1.conversions, typed2.conversions); + + typed1({ + 'Person': function (p) {return 'Person'} + }); + + assert.throws(function () { + typed2({ + 'Person': function (p) {return 'Person'} + }); + }, /Error: Unknown type "Person"/) + }); + + it('should add a type using addType (before object)', function() { + var typed2 = typed.create(); + function Person() {} + + var newType = { + name: 'Person', + test: function (x) { + return x instanceof Person; + } + }; + + var objectEntry = typed2.types.find(function (entry) { + return entry.name === 'Object'; + }); + var objectIndex = typed2.types.indexOf(objectEntry); + + typed2.addType(newType); + + assert.strictEqual(typed2.types[objectIndex], newType); + }); + + it('should add a type using addType at the end (after Object)', function() { + var typed2 = typed.create(); + function Person() {} + + var newType = { + name: 'Person', + test: function (x) { + return x instanceof Person; + } + }; + + typed2.addType(newType, false); + + assert.strictEqual(typed2.types[typed2.types.length - 1], newType); + }); + + it('should throw an error when passing an invalid type to addType', function() { + var typed2 = typed.create(); + var errMsg = /TypeError: Object with properties {name: string, test: function} expected/; + + assert.throws(function () {typed2.addType({})}, errMsg); + assert.throws(function () {typed2.addType({name: 2, test: function () {}})}, errMsg); + assert.throws(function () {typed2.addType({name: 'foo', test: 'bar'})}, errMsg); + }); + + it('should throw an error when providing an unsupported type of argument', function() { + var fn = typed('fn1', { + 'number': function (value) { + return 'number:' + value; + } + }); + + assert.throws(function () {fn(new Date())}, /TypeError: Unexpected type of argument in function fn1 \(expected: number, actual: Date, index: 0\)/); + }); + + it('should throw an error when providing a wrong function signature', function() { + var fn = typed('fn1', { + 'number': function (value) { + return 'number:' + value; + } + }); + + assert.throws(function () {fn(1, 2)}, /TypeError: Too many arguments in function fn1 \(expected: 1, actual: 2\)/); + }); + + it('should throw an error when composing with an unknown type', function() { + assert.throws(function () { + var fn = typed({ + 'foo': function (value) { + return 'number:' + value; + } + }); + }, /Error: Unknown type "foo"/); + }); + + it('should ignore types from typed.ignore', function() { + var typed2 = typed.create(); + typed2.ignore = ['string']; + + var fn = typed2({ + 'number': function () {}, + 'number, number': function () {}, + + 'string, number': function () {}, + 'number, string': function () {}, + 'boolean | string, boolean': function () {}, + 'any, ...string': function () {}, + 'string': function () {} + }); + + assert.deepEqual(Object.keys(fn.signatures).sort(), ['boolean,boolean', 'number', 'number,number']); + }); + + it('should give a hint when composing with a wrongly cased type', function() { + assert.throws(function () { + var fn = typed({ + 'array': function (value) { + return 'array:' + value; + } + }); + }, /Error: Unknown type "array". Did you mean "Array"?/); + + assert.throws(function () { + var fn = typed({ + 'function': function (value) { + return 'Function:' + value; + } + }); + }, /Error: Unknown type "function". Did you mean "Function"?/); + }); + + it('should attach signatures to the created typed-function', function() { + var fn1 = function () {} + var fn2 = function () {} + var fn3 = function () {} + var fn4 = function () {} + + var fn = typed({ + 'string': fn1, + 'string, boolean': fn2, + 'number | Date, boolean': fn3, + 'Array | Object, string | RegExp': fn3, + 'number, ...string | number': fn4 + }); + + assert.deepStrictEqual(fn.signatures, { + 'string': fn1, + 'string,boolean': fn2, + 'number,boolean': fn3, + 'Date,boolean': fn3, + 'Array,string': fn3, + 'Array,RegExp': fn3, + 'Object,string': fn3, + 'Object,RegExp': fn3, + 'number,...string|number': fn4 + }); + }); + + it('should correctly order signatures', function () { + var fn = typed({ + 'boolean': function (a) { + return 'boolean'; + }, + 'string': function (a) { + return 'string'; + }, + 'number': function (a) { + return 'number'; + } + }); + + // TODO: this is tricky, object keys do not officially have a guaranteed order + assert.deepEqual(Object.keys(fn.signatures), + ['number', 'string', 'boolean']); + }); + + it('should allow a function to be defined recursively', function () { + var fn = typed({ + 'number': function (value) { + return 'number:' + value; + }, + 'string': function (value) { + return this(parseInt(value, 10)); + } + }); + + assert.equal(fn('2'), 'number:2'); + }) + +}); diff --git a/node_modules/typed-function/test/conversion.test.js b/node_modules/typed-function/test/conversion.test.js new file mode 100644 index 0000000..00a4c11 --- /dev/null +++ b/node_modules/typed-function/test/conversion.test.js @@ -0,0 +1,437 @@ +var assert = require('assert'); +var typed = require('../typed-function'); +var strictEqualArray = require('./strictEqualArray'); + +describe('conversion', function () { + + before(function () { + typed.conversions = [ + {from: 'boolean', to: 'number', convert: function (x) {return +x;}}, + {from: 'boolean', to: 'string', convert: function (x) {return x + '';}}, + {from: 'number', to: 'string', convert: function (x) {return x + '';}}, + { + from: 'string', + to: 'Date', + convert: function (x) { + var d = new Date(x); + return isNaN(d.valueOf()) ? undefined : d; + }, + fallible: true // TODO: not yet supported + } + ]; + }); + + after(function () { + // cleanup conversions + typed.conversions = []; + }); + + it('should add conversions to a function with one argument', function() { + var fn = typed({ + 'string': function (a) { + return a; + } + }); + + assert.equal(fn(2), '2'); + assert.equal(fn(false), 'false'); + assert.equal(fn('foo'), 'foo'); + }); + + it('should add a conversion using addConversion', function() { + var typed2 = typed.create(); + + var conversion = { + from: 'number', + to: 'string', + convert: function (x) { + return x + ''; + } + }; + + assert.equal(typed2.conversions.length, 0); + + typed2.addConversion(conversion); + + assert.equal(typed2.conversions.length, 1); + assert.strictEqual(typed2.conversions[0], conversion); + }); + + it('should throw an error when passing an invalid conversion object to addConversion', function() { + var typed2 = typed.create(); + var errMsg = /TypeError: Object with properties \{from: string, to: string, convert: function} expected/; + + assert.throws(function () {typed2.addConversion({})}, errMsg); + assert.throws(function () {typed2.addConversion({from: 'number', to: 'string'})}, errMsg); + assert.throws(function () {typed2.addConversion({from: 'number', convert: function () {}})}, errMsg); + assert.throws(function () {typed2.addConversion({to: 'string', convert: function () {}})}, errMsg); + assert.throws(function () {typed2.addConversion({from: 2, to: 'string', convert: function () {}})}, errMsg); + assert.throws(function () {typed2.addConversion({from: 'number', to: 2, convert: function () {}})}, errMsg); + assert.throws(function () {typed2.addConversion({from: 'number', to: 'string', convert: 'foo'})}, errMsg); + }); + + it('should add conversions to a function with multiple arguments', function() { + // note: we add 'string, string' first, and `string, number` afterwards, + // to test whether the conversions are correctly ordered. + var fn = typed({ + 'string, string': function (a, b) { + assert.equal(typeof a, 'string'); + assert.equal(typeof b, 'string'); + return 'string, string'; + }, + 'string, number': function (a, b) { + assert.equal(typeof a, 'string'); + assert.equal(typeof b, 'number'); + return 'string, number'; + } + }); + + assert.equal(fn(true, false), 'string, number'); + assert.equal(fn(true, 2), 'string, number'); + assert.equal(fn(true, 'foo'), 'string, string'); + assert.equal(fn(2, false), 'string, number'); + assert.equal(fn(2, 3), 'string, number'); + assert.equal(fn(2, 'foo'), 'string, string'); + assert.equal(fn('foo', true), 'string, number'); + assert.equal(fn('foo', 2), 'string, number'); + assert.equal(fn('foo', 'foo'), 'string, string'); + assert.deepEqual(Object.keys(fn.signatures), [ + 'string,number', + 'string,string' + ]); + }); + + it('should add conversions to a function with rest parameters (1)', function() { + var toNumber = typed({ + '...number': function (values) { + assert(Array.isArray(values)); + return values; + } + }); + + assert.deepStrictEqual(toNumber(2,3,4), [2,3,4]); + assert.deepStrictEqual(toNumber(2,true,4), [2,1,4]); + assert.deepStrictEqual(toNumber(1,2,false), [1,2,0]); + assert.deepStrictEqual(toNumber(1,2,true), [1,2,1]); + assert.deepStrictEqual(toNumber(true,1,2), [1,1,2]); + assert.deepStrictEqual(toNumber(true,false, true), [1,0,1]); + }); + + it('should add conversions to a function with rest parameters (2)', function() { + var sum = typed({ + 'string, ...number': function (name, values) { + assert.equal(typeof name, 'string'); + assert(Array.isArray(values)); + var sum = 0; + for (var i = 0; i < values.length; i++) { + sum += values[i]; + } + return sum; + } + }); + + assert.equal(sum('foo', 2,3,4), 9); + assert.equal(sum('foo', 2,true,4), 7); + assert.equal(sum('foo', 1,2,false), 3); + assert.equal(sum('foo', 1,2,true), 4); + assert.equal(sum('foo', true,1,2), 4); + assert.equal(sum('foo', true,false, true), 2); + assert.equal(sum(123, 2,3), 5); + assert.equal(sum(false, 2,3), 5); + }); + + it('should add conversions to a function with rest parameters in a non-conflicting way', function() { + var fn = typed({ + '...number': function (values) { + return values; + }, + 'boolean': function (value) { + assert.equal(typeof value, 'boolean'); + return 'boolean'; + } + }); + + assert.deepStrictEqual(fn(2,3,4), [2,3,4]); + assert.deepStrictEqual(fn(2,true,4), [2,1,4]); + assert.deepStrictEqual(fn(true,3,4), [1,3,4]); + assert.equal(fn(false), 'boolean'); + assert.equal(fn(true), 'boolean'); + }); + + it('should add conversions to a function with rest parameters in a non-conflicting way', function() { + var typed2 = typed.create(); + typed2.conversions = [ + {from: 'boolean', to: 'number', convert: function (x) {return +x}}, + {from: 'string', to: 'number', convert: function (x) {return parseFloat(x)}}, + {from: 'string', to: 'boolean', convert: function (x) {return !!x}} + ]; + + // booleans can be converted to numbers, so the `...number` signature + // will match. But the `...boolean` signature is a better (exact) match so that + // should be picked + var fn = typed2({ + '...number': function (values) { + return values; + }, + '...boolean': function (values) { + return values; + } + }); + + assert.deepStrictEqual(fn(2,3,4), [2,3,4]); + assert.deepStrictEqual(fn(2,true,4), [2,1,4]); + assert.deepStrictEqual(fn(true,true,true), [true,true,true]); + }); + + it('should add conversions to a function with variable and union arguments', function() { + var fn = typed({ + '...string | number': function (values) { + assert(Array.isArray(values)); + return values; + } + }); + + assert.deepStrictEqual(fn(2,3,4), [2,3,4]); + assert.deepStrictEqual(fn(2,true,4), [2,1,4]); + assert.deepStrictEqual(fn(2,'str'), [2,'str']); + assert.deepStrictEqual(fn('str', true, false), ['str', 1, 0]); + assert.deepStrictEqual(fn('str', 2, false), ['str', 2, 0]); + + assert.throws(function () {fn(new Date(), '2')}, /TypeError: Unexpected type of argument in function unnamed \(expected: string or number or boolean, actual: Date, index: 0\)/) + }); + + it('should order conversions and type Object correctly ', function() { + var typed2 = typed.create(); + typed2.conversions = [ + {from: 'Date', to: 'string', convert: function (x) {return x.toISOString()}} + ]; + + var fn = typed2({ + 'string': function () { + return 'string'; + }, + 'Object': function () { + return 'object'; + } + }); + + assert.equal(fn('foo'), 'string'); + assert.equal(fn(new Date(2018, 1, 20)), 'string'); + assert.equal(fn({a: 2}), 'object'); + }); + + it('should add non-conflicting conversions to a function with one argument', function() { + var fn = typed({ + 'number': function (a) { + return a; + }, + 'string': function (a) { + return a; + } + }); + + // booleans should be converted to number + assert.strictEqual(fn(false), 0); + assert.strictEqual(fn(true), 1); + + // numbers and strings should be left as is + assert.strictEqual(fn(2), 2); + assert.strictEqual(fn('foo'), 'foo'); + }); + + it('should add non-conflicting conversions to a function with one argument', function() { + var fn = typed({ + 'boolean': function (a) { + return a; + } + }); + + // booleans should be converted to number + assert.equal(fn(false), 0); + assert.equal(fn(true), 1); + }); + + it('should add non-conflicting conversions to a function with two arguments', function() { + var fn = typed({ + 'boolean, boolean': function (a, b) { + return 'boolean, boolean'; + }, + 'number, number': function (a, b) { + return 'number, number'; + } + }); + + //console.log('FN', fn.toString()); + + // booleans should be converted to number + assert.equal(fn(false, true), 'boolean, boolean'); + assert.equal(fn(2, 4), 'number, number'); + assert.equal(fn(false, 4), 'number, number'); + assert.equal(fn(2, true), 'number, number'); + }); + + it('should add non-conflicting conversions to a function with three arguments', function() { + var fn = typed({ + 'boolean, boolean, boolean': function (a, b, c) { + return 'booleans'; + }, + 'number, number, number': function (a, b, c) { + return 'numbers'; + } + }); + + //console.log('FN', fn.toString()); + + // booleans should be converted to number + assert.equal(fn(false, true, true), 'booleans'); + assert.equal(fn(false, false, 5), 'numbers'); + assert.equal(fn(false, 4, false), 'numbers'); + assert.equal(fn(2, false, false), 'numbers'); + assert.equal(fn(false, 4, 5), 'numbers'); + assert.equal(fn(2, false, 5), 'numbers'); + assert.equal(fn(2, 4, false), 'numbers'); + assert.equal(fn(2, 4, 5), 'numbers'); + }); + + it('should not apply conversions when having an any type argument', function() { + var fn = typed({ + 'number': function (a) { + return 'number'; + }, + 'any': function (a) { + return 'any'; + } + }); + + assert.equal(fn(2), 'number'); + assert.equal(fn(true), 'any'); + assert.equal(fn('foo'), 'any'); + assert.equal(fn('{}'), 'any'); + }); + + describe ('ordering', function () { + + it('should correctly select the signatures with the least amount of conversions', function () { + typed.conversions = [ + {from: 'boolean', to: 'number', convert: function (x) {return +x;}}, + {from: 'number', to: 'string', convert: function (x) {return x + '';}}, + {from: 'boolean', to: 'string', convert: function (x) {return x + '';}} + ]; + + var fn = typed({ + 'boolean, boolean': function (a, b) { + assert.equal(typeof a, 'boolean'); + assert.equal(typeof b, 'boolean'); + return 'booleans'; + }, + 'number, number': function (a, b) { + assert.equal(typeof a, 'number'); + assert.equal(typeof b, 'number'); + return 'numbers'; + }, + 'string, string': function (a, b) { + assert.equal(typeof a, 'string'); + assert.equal(typeof b, 'string'); + return 'strings'; + } + }); + + assert.equal(fn(true, true), 'booleans'); + assert.equal(fn(2, true), 'numbers'); + assert.equal(fn(true, 2), 'numbers'); + assert.equal(fn(2, 2), 'numbers'); + assert.equal(fn('foo', 'bar'), 'strings'); + assert.equal(fn('foo', 2), 'strings'); + assert.equal(fn(2, 'foo'), 'strings'); + assert.equal(fn(true, 'foo'), 'strings'); + assert.equal(fn('foo', true), 'strings'); + + assert.deepEqual(Object.keys(fn.signatures), [ + 'number,number', + 'string,string', + 'boolean,boolean' + ]); + }); + + it('should select the signatures with the conversion with the lowest index (1)', function () { + typed.conversions = [ + {from: 'boolean', to: 'string', convert: function (x) {return x + '';}}, + {from: 'boolean', to: 'number', convert: function (x) {return x + 0;}} + ]; + + // in the following typed function, a boolean input can be converted to + // both a string or a number, which is both ok. In that case, + // the conversion with the lowest index should be picked: boolean -> string + var fn = typed({ + 'string | number': function (a) { + return a; + } + }); + + assert.strictEqual(fn(true), 'true'); + + assert.deepEqual(Object.keys(fn.signatures), [ + 'number', + 'string' + ]); + }); + + it('should select the signatures with the conversion with the lowest index (2)', function () { + typed.conversions = [ + {from: 'boolean', to: 'number', convert: function (x) {return x + 0;}}, + {from: 'boolean', to: 'string', convert: function (x) {return x + '';}} + ]; + + // in the following typed function, a boolean input can be converted to + // both a string or a number, which is both ok. In that case, + // the conversion with the lowest index should be picked: boolean -> number + var fn = typed({ + 'string | number': function (a) { + return a; + } + }); + + assert.strictEqual(fn(true), 1); + }); + + it('should select the signatures with least needed conversions (1)', function () { + typed.conversions = [ + {from: 'number', to: 'boolean', convert: function (x) {return !!x }}, + {from: 'number', to: 'string', convert: function (x) {return x + '' }}, + {from: 'boolean', to: 'string', convert: function (x) {return x + '' }} + ]; + + // in the following typed function, the number input can be converted to + // both a string or a boolean, which is both ok. It should pick the + // conversion to boolean because that is defined first + var fn = typed({ + 'string': function (a) { return a; }, + 'boolean': function (a) { return a; } + }); + + assert.strictEqual(fn(1), true); + }); + + it('should select the signatures with least needed conversions (2)', function () { + typed.conversions = [ + {from: 'number', to: 'boolean', convert: function (x) {return !!x }}, + {from: 'number', to: 'string', convert: function (x) {return x + '' }}, + {from: 'boolean', to: 'string', convert: function (x) {return x + '' }} + ]; + + // in the following typed function, the number input can be converted to + // both a string or a boolean, which is both ok. It should pick the + // conversion to boolean because that conversion is defined first + var fn = typed({ + 'number, number': function (a, b) { return [a, b]; }, + 'string, string': function (a, b) { return [a, b]; }, + 'boolean, boolean': function (a, b) { return [a, b]; } + }); + + assert.deepStrictEqual(fn('foo', 2), ['foo', '2']); + assert.deepStrictEqual(fn(1, true), [true, true]); + }); + + }); + +}); diff --git a/node_modules/typed-function/test/convert.test.js b/node_modules/typed-function/test/convert.test.js new file mode 100644 index 0000000..ec422e8 --- /dev/null +++ b/node_modules/typed-function/test/convert.test.js @@ -0,0 +1,42 @@ +var assert = require('assert'); +var typed = require('../typed-function'); + +describe('convert', function () { + + before(function () { + typed.conversions = [ + {from: 'boolean', to: 'number', convert: function (x) {return +x;}}, + {from: 'boolean', to: 'string', convert: function (x) {return x + '';}}, + {from: 'number', to: 'string', convert: function (x) {return x + '';}}, + { + from: 'string', + to: 'Date', + convert: function (x) { + var d = new Date(x); + return isNaN(d.valueOf()) ? undefined : d; + }, + fallible: true // TODO: not yet supported + } + ]; + }); + + after(function () { + // cleanup conversions + typed.conversions = []; + }); + + it('should convert a value', function() { + assert.strictEqual(typed.convert(2, 'string'), '2'); + assert.strictEqual(typed.convert(true, 'string'), 'true'); + assert.strictEqual(typed.convert(true, 'number'), 1); + }); + + it('should return same value when conversion is not needed', function () { + assert.strictEqual(typed.convert(2, 'number'), 2); + assert.strictEqual(typed.convert(true, 'boolean'), true); + }); + + it('should throw an error when no conversion function is found', function() { + assert.throws(function () {typed.convert(2, 'boolean')}, /Error: Cannot convert from number to boolean/); + }); +}); diff --git a/node_modules/typed-function/test/errors.test.js b/node_modules/typed-function/test/errors.test.js new file mode 100644 index 0000000..10837ca --- /dev/null +++ b/node_modules/typed-function/test/errors.test.js @@ -0,0 +1,157 @@ +var assert = require('assert'); +var typed = require('../typed-function'); + +describe('errors', function () { + it('should give correct error in case of too few arguments (named function)', function() { + var fn = typed('fn1', {'string, boolean': function () {}}); + + assert.throws(function () {fn()}, /TypeError: Too few arguments in function fn1 \(expected: string, index: 0\)/); + assert.throws(function () {fn('foo')}, /TypeError: Too few arguments in function fn1 \(expected: boolean, index: 1\)/); + }); + + it('should give correct error in case of too few arguments (unnamed function)', function() { + var fn = typed({'string, boolean': function () {}}); + + assert.throws(function () {fn()}, /TypeError: Too few arguments in function unnamed \(expected: string, index: 0\)/); + assert.throws(function () {fn('foo')}, /TypeError: Too few arguments in function unnamed \(expected: boolean, index: 1\)/); + }); + + it('should give correct error in case of too few arguments (rest params)', function() { + var fn = typed({'...string': function () {}}); + + assert.throws(function () {fn()}, /TypeError: Too few arguments in function unnamed \(expected: string, index: 0\)/); + }); + + it('should give correct error in case of too few arguments (rest params) (2)', function() { + var fn = typed({'boolean, ...string': function () {}}); + + assert.throws(function () {fn()}, /TypeError: Too few arguments in function unnamed \(expected: boolean, index: 0\)/); + assert.throws(function () {fn(true)}, /TypeError: Too few arguments in function unnamed \(expected: string, index: 1\)/); + }); + + it('should give correct error in case of too many arguments (unnamed function)', function() { + var fn = typed({'string, boolean': function () {}}); + + assert.throws(function () {fn('foo', true, 2)}, /TypeError: Too many arguments in function unnamed \(expected: 2, actual: 3\)/); + assert.throws(function () {fn('foo', true, 2, 1)}, /TypeError: Too many arguments in function unnamed \(expected: 2, actual: 4\)/); + }); + + it('should give correct error in case of too many arguments (named function)', function() { + var fn = typed('fn2', {'string, boolean': function () {}}); + + assert.throws(function () {fn('foo', true, 2)}, /TypeError: Too many arguments in function fn2 \(expected: 2, actual: 3\)/); + assert.throws(function () {fn('foo', true, 2, 1)}, /TypeError: Too many arguments in function fn2 \(expected: 2, actual: 4\)/); + }); + + it('should give correct error in case of wrong type of argument (unnamed function)', function() { + var fn = typed({'boolean': function () {}}); + + assert.throws(function () {fn('foo')}, /TypeError: Unexpected type of argument in function unnamed \(expected: boolean, actual: string, index: 0\)/); + }); + + it('should give correct error in case of wrong type of argument (named function)', function() { + var fn = typed('fn3', {'boolean': function () {}}); + + assert.throws(function () {fn('foo')}, /TypeError: Unexpected type of argument in function fn3 \(expected: boolean, actual: string, index: 0\)/); + }); + + it('should give correct error in case of wrong type of argument (union args)', function() { + var fn = typed({'boolean | string | Date': function () {}}); + + assert.throws(function () {fn(2)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string or boolean or Date, actual: number, index: 0\)/); + }); + + it('should give correct error in case of conflicting union arguments', function() { + assert.throws(function () { + var fn = typed({ + 'string | number': function () {}, + 'string': function () {} + }); + }, /TypeError: Conflicting signatures "string\|number" and "string"/); + }); + + it('should give correct error in case of conflicting union arguments (2)', function() { + assert.throws(function () { + var fn = typed({ + '...string | number': function () {}, + '...string': function () {} + }); + }, /TypeError: Conflicting signatures "...string\|number" and "...string"/); + }); + + it('should give correct error in case of conflicting rest params (1)', function() { + assert.throws(function () { + var fn = typed({ + '...string': function () {}, + 'string': function () {} + }); + }, /TypeError: Conflicting signatures "...string" and "string"/); + }); + + it('should give correct error in case of conflicting rest params (2)', function() { + // should not throw + var fn = typed({ + '...string': function () {}, + 'string, number': function () {} + }); + + assert.throws(function () { + var fn = typed({ + '...string': function () {}, + 'string, string': function () {} + }); + }, /TypeError: Conflicting signatures "...string" and "string,string"/); + }); + + it('should give correct error in case of conflicting rest params (3)', function() { + assert.throws(function () { + var fn = typed({ + '...number|string': function () {}, + 'number, string': function () {} + }); + }, /TypeError: Conflicting signatures "...number\|string" and "number,string"/); + }); + + it('should give correct error in case of wrong type of argument (rest params)', function() { + var fn = typed({'...number': function () {}}); + + assert.throws(function () {fn(true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: boolean, index: 0\)/); + assert.throws(function () {fn(2, true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: boolean, index: 1\)/); + assert.throws(function () {fn(2, 3, true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: boolean, index: 2\)/); + }); + + it('should give correct error in case of wrong type of argument (nested rest params)', function() { + var fn = typed({'string, ...number': function () {}}); + + assert.throws(function () {fn(true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string, actual: boolean, index: 0\)/); + assert.throws(function () {fn('foo', true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: boolean, index: 1\)/); + assert.throws(function () {fn('foo', 2, true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: boolean, index: 2\)/); + assert.throws(function () {fn('foo', 2, 3, true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: boolean, index: 3\)/); + }); + + it('should give correct error in case of wrong type of argument (union and rest params)', function() { + var fn = typed({'...number|boolean': function () {}}); + + assert.throws(function () {fn('foo')}, /TypeError: Unexpected type of argument in function unnamed \(expected: number or boolean, actual: string, index: 0\)/); + assert.throws(function () {fn(2, 'foo')}, /TypeError: Unexpected type of argument in function unnamed \(expected: number or boolean, actual: string, index: 1\)/); + assert.throws(function () {fn(2, true, 'foo')}, /TypeError: Unexpected type of argument in function unnamed \(expected: number or boolean, actual: string, index: 2\)/); + }); + + it('should only list matches of exact and convertable types', function() { + var typed2 = typed.create(); + typed2.conversions.push({ + from: 'number', + to: 'string', + convert: function (x) { + return +x; + } + }); + + var fn1 = typed2({'string': function () {}}); + var fn2 = typed2({'...string': function () {}}); + + assert.throws(function () {fn1(true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string or number, actual: boolean, index: 0\)/); + assert.throws(function () {fn2(true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string or number, actual: boolean, index: 0\)/); + assert.throws(function () {fn2(2, true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string or number, actual: boolean, index: 1\)/); + }); +}); diff --git a/node_modules/typed-function/test/find.test.js b/node_modules/typed-function/test/find.test.js new file mode 100644 index 0000000..2770a58 --- /dev/null +++ b/node_modules/typed-function/test/find.test.js @@ -0,0 +1,48 @@ +var assert = require('assert'); +var typed = require('../typed-function'); + +describe('find', function () { + + function a () {} + function b () {} + function c () {} + function d () {} + function e () {} + + var fn = typed('fn', { + 'number': a, + 'string, ...number': b, + 'number, boolean': c, + 'any': d, + '': e + }); + + + it('should find a signature from an array with types', function() { + assert.strictEqual(typed.find(fn, ['number']), a); + assert.strictEqual(typed.find(fn, ['number', 'boolean']), c); + assert.strictEqual(typed.find(fn, ['any']), d); + assert.strictEqual(typed.find(fn, []), e); + + }); + + it('should find a signature from a comma separated string with types', function() { + assert.strictEqual(typed.find(fn, 'number'), a); + assert.strictEqual(typed.find(fn, 'number,boolean'), c); + assert.strictEqual(typed.find(fn, ' number, boolean '), c); // with spaces + assert.strictEqual(typed.find(fn, 'any'), d); + assert.strictEqual(typed.find(fn, ''), e); + }); + + it('should throw an error when not found', function() { + assert.throws(function () { + typed.find(fn, 'number, number'); + }, /TypeError: Signature not found \(signature: fn\(number, number\)\)/); + }); + + + // TODO: implement support for matching non-exact signatures + //assert.strictEqual(typed.find(fn, ['Array']), d); + + +}); diff --git a/node_modules/typed-function/test/merge.test.js b/node_modules/typed-function/test/merge.test.js new file mode 100644 index 0000000..e32ea5c --- /dev/null +++ b/node_modules/typed-function/test/merge.test.js @@ -0,0 +1,118 @@ +var assert = require('assert'); +var typed = require('../typed-function'); + +describe('merge', function () { + it('should merge two typed-functions', function () { + var typed1 = typed({'boolean': function (value) { return 'boolean:' + value; }}); + var typed2 = typed({'number': function (value) { return 'number:' + value; }}); + + var typed3 = typed(typed1, typed2); + + assert.deepEqual(Object.keys(typed3.signatures).sort(), ['boolean', 'number']); + + assert.strictEqual(typed3(true), 'boolean:true'); + assert.strictEqual(typed3(2), 'number:2'); + assert.throws(function () {typed3('foo')}, /TypeError: Unexpected type of argument in function unnamed \(expected: number or boolean, actual: string, index: 0\)/); + }); + + it('should merge three typed-functions', function () { + var typed1 = typed({'boolean': function (value) { return 'boolean:' + value; }}); + var typed2 = typed({'number': function (value) { return 'number:' + value; }}); + var typed3 = typed({'string': function (value) { return 'string:' + value; }}); + + var typed4 = typed(typed1, typed2, typed3); + + assert.deepEqual(Object.keys(typed4.signatures).sort(), ['boolean', 'number', 'string']); + + assert.strictEqual(typed4(true), 'boolean:true'); + assert.strictEqual(typed4(2), 'number:2'); + assert.strictEqual(typed4('foo'), 'string:foo'); + assert.throws(function () {typed4(new Date())}, /TypeError: Unexpected type of argument in function unnamed \(expected: number or string or boolean, actual: Date, index: 0\)/); + }); + + it('should merge two typed-functions with a custom name', function () { + var typed1 = typed('typed1', {'boolean': function (value) { return 'boolean:' + value; }}); + var typed2 = typed('typed2', {'number': function (value) { return 'number:' + value; }}); + + var typed3 = typed('typed3', typed1, typed2); + + assert.equal(typed3.name, 'typed3'); + }); + + it('should not copy conversions as exact signatures', function () { + var typed2 = typed.create(); + typed2.conversions = [ + {from: 'string', to: 'number', convert: function (x) {return parseFloat(x)}} + ]; + + var fn2 = typed2({'number': function (value) { return value }}); + + assert.strictEqual(fn2(2), 2); + assert.strictEqual(fn2('123'), 123); + + var fn1 = typed({ 'Date': function (value) {return value} }); + var fn3 = typed(fn1, fn2); // create via typed which has no conversions + + var date = new Date() + assert.strictEqual(fn3(2), 2); + assert.strictEqual(fn3(date), date); + assert.throws(function () {fn3('123') }, /TypeError: Unexpected type of argument in function unnamed \(expected: number or Date, actual: string, index: 0\)/); + }); + + it('should allow merging duplicate signatures when pointing to the same function', function () { + var typed1 = typed({'boolean': function (value) { return 'boolean:' + value; }}); + + var merged = typed(typed1, typed1); + + assert.deepEqual(Object.keys(merged.signatures).sort(), ['boolean']); + }); + + it('should throw an error in case of conflicting signatures when merging', function () { + var typed1 = typed({'boolean': function (value) { return 'boolean:' + value; }}); + var typed2 = typed({'boolean': function (value) { return 'boolean:' + value; }}); + + assert.throws(function () { + typed(typed1, typed2) + }, /Error: Signature "boolean" is defined twice/); + }); + + it('should throw an error in case of conflicting names when merging', function () { + var typed1 = typed('fn1', {'boolean': function () {}}); + var typed2 = typed('fn2', {'string': function () {}}); + var typed3 = typed({'number': function () {}}); + + assert.throws(function () { + typed(typed1, typed2) + }, /Error: Function names do not match \(expected: fn1, actual: fn2\)/); + + var typed4 = typed(typed2, typed3); + assert.equal(typed4.name, 'fn2'); + }); + + it('should allow recursive across merged signatures', function () { + var fn1 = typed({ + '...number': function (values) { + var sum = 0; + for (var i = 0; i < values.length; i++) { + sum += values[i]; + } + return sum; + } + }); + + var fn2 = typed({ + '...string': function (values) { + var newValues = []; + for (var i = 0; i < values.length; i++) { + newValues[i] = parseInt(values[i], 10); + } + return this.apply(null, newValues); + } + }); + + var fn3 = typed(fn1, fn2); + + assert.equal(fn3('1', '2', '3'), '6'); + assert.equal(fn3(1, 2, 3), 6); + }) +}); diff --git a/node_modules/typed-function/test/onMismatch.test.js b/node_modules/typed-function/test/onMismatch.test.js new file mode 100644 index 0000000..e951468 --- /dev/null +++ b/node_modules/typed-function/test/onMismatch.test.js @@ -0,0 +1,40 @@ +var assert = require('assert'); +var typed = require('../typed-function'); + +describe('onMismatch handler', () => { + const square = typed('square', { + number: x => x*x, + string: s => s + s + }) + + it('should replace the return value of a mismatched call', () => { + typed.onMismatch = () => 42 + assert.strictEqual(square(5), 25) + assert.strictEqual(square('yo'), 'yoyo') + assert.strictEqual(square([13]), 42) + }) + + const myErrorLog = [] + it('should allow error logging', () => { + typed.onMismatch = (name, args, signatures) => { + myErrorLog.push(typed.createError(name, args, signatures)) + return null + } + square({the: 'circle'}) + square(7) + square('me') + square(1,2) + assert.strictEqual(myErrorLog.length, 2) + assert('data' in myErrorLog[0]) + }) + + it('should allow changing the error', () => { + typed.onMismatch = name => { throw Error('Problem with ' + name) } + assert.throws(() => square(['one']), /Problem with square/) + }) + + it('should allow a return to standard behavior', () => { + typed.onMismatch = typed.throwMismatchError + assert.throws(() => square('be', 'there'), TypeError) + }) +}) diff --git a/node_modules/typed-function/test/rest_params.js b/node_modules/typed-function/test/rest_params.js new file mode 100644 index 0000000..5a88912 --- /dev/null +++ b/node_modules/typed-function/test/rest_params.js @@ -0,0 +1,200 @@ +var assert = require('assert'); +var typed = require('../typed-function'); +var strictEqualArray = require('./strictEqualArray'); + +describe('rest parameters', function () { + + it('should create a typed function with rest parameters', function() { + var sum = typed({ + '...number': function (values) { + assert(Array.isArray(values)); + var sum = 0; + for (var i = 0; i < values.length; i++) { + sum += values[i]; + } + return sum; + } + }); + + assert.equal(sum(2), 2); + assert.equal(sum(2,3,4), 9); + assert.throws(function () {sum()}, /TypeError: Too few arguments in function unnamed \(expected: number, index: 0\)/); + assert.throws(function () {sum(true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: boolean, index: 0\)/); + assert.throws(function () {sum('string')}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: string, index: 0\)/); + assert.throws(function () {sum(2, 'string')}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: string, index: 1\)/); + assert.throws(function () {sum(2, 3, 'string')}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: string, index: 2\)/); + }); + + it('should create a typed function with rest parameters (2)', function() { + var fn = typed({ + 'string, ...number': function (str, values) { + assert.equal(typeof str, 'string'); + assert(Array.isArray(values)); + return str + ': ' + values.join(', '); + } + }); + + assert.equal(fn('foo', 2), 'foo: 2'); + assert.equal(fn('foo', 2, 4), 'foo: 2, 4'); + assert.throws(function () {fn(2, 4)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string, actual: number, index: 0\)/); + assert.throws(function () {fn('string')}, /TypeError: Too few arguments in function unnamed \(expected: number, index: 1\)/); + assert.throws(function () {fn('string', 'string')}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: string, index: 1\)/); + }); + + it('should create a typed function with any type arguments (1)', function() { + var fn = typed({ + 'string, ...any': function (str, values) { + assert.equal(typeof str, 'string'); + assert(Array.isArray(values)); + return str + ': ' + values.join(', '); + } + }); + + assert.equal(fn('foo', 2), 'foo: 2'); + assert.equal(fn('foo', 2, true, 'bar'), 'foo: 2, true, bar'); + assert.equal(fn('foo', 'bar'), 'foo: bar'); + assert.throws(function () {fn(2, 4)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string, actual: number, index: 0\)/); + assert.throws(function () {fn('string')}, /TypeError: Too few arguments in function unnamed \(expected: any, index: 1\)/); + }); + + it('should create a typed function with implicit any type arguments', function() { + var fn = typed({ + 'string, ...': function (str, values) { + assert.equal(typeof str, 'string'); + assert(Array.isArray(values)); + return str + ': ' + values.join(', '); + } + }); + + assert.equal(fn('foo', 2), 'foo: 2'); + assert.equal(fn('foo', 2, true, 'bar'), 'foo: 2, true, bar'); + assert.equal(fn('foo', 'bar'), 'foo: bar'); + assert.throws(function () {fn(2, 4)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string, actual: number, index: 0\)/); + assert.throws(function () {fn('string')}, /TypeError: Too few arguments in function unnamed \(expected: any, index: 1\)/); + }); + + it('should create a typed function with any type arguments (2)', function() { + var fn = typed({ + 'any, ...number': function (any, values) { + assert(Array.isArray(values)); + return any + ': ' + values.join(', '); + } + }); + + assert.equal(fn('foo', 2), 'foo: 2'); + assert.equal(fn(1, 2, 4), '1: 2, 4'); + assert.equal(fn(null, 2, 4), 'null: 2, 4'); + assert.throws(function () {fn('string')}, /TypeError: Too few arguments in function unnamed \(expected: number, index: 1\)/); + assert.throws(function () {fn('string', 'string')}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: string, index: 1\)/); + }); + + it('should create a typed function with union type arguments', function() { + var fn = typed({ + '...number|string': function (values) { + assert(Array.isArray(values)); + return values; + } + }); + + strictEqualArray(fn(2,3,4), [2,3,4]); + strictEqualArray(fn('a','b','c'), ['a','b','c']); + strictEqualArray(fn('a',2,'c',3), ['a',2,'c',3]); + assert.throws(function () {fn()}, /TypeError: Too few arguments in function unnamed \(expected: number or string, index: 0\)/); + assert.throws(function () {fn('string', true)}, /TypeError: Unexpected type of argument. Index: 1 in function unnamed \(expected: string | number/); + assert.throws(function () {fn(2, false)}, /TypeError: Unexpected type of argument. Index: 1 in function unnamed \(expected: string | number/); + assert.throws(function () {fn(2, 3, false)}, /TypeError: Unexpected type of argument. Index: 2 in function unnamed \(expected: string | number/); + }); + + it('should create a composed function with rest parameters', function() { + var fn = typed({ + 'string, ...number': function (str, values) { + assert.equal(typeof str, 'string'); + assert(Array.isArray(values)); + return str + ': ' + values.join(', '); + }, + + '...boolean': function (values) { + assert(Array.isArray(values)); + return 'booleans'; + } + }); + + assert.equal(fn('foo', 2), 'foo: 2'); + assert.equal(fn('foo', 2, 4), 'foo: 2, 4'); + assert.equal(fn(true, false, false), 'booleans'); + assert.throws(function () {fn(2, 4)}, /TypeError: Unexpected type of argument in function unnamed \(expected: string or boolean, actual: number, index: 0\)/); + assert.throws(function () {fn('string')}, /TypeError: Too few arguments in function unnamed \(expected: number, index: 1\)/); + assert.throws(function () {fn('string', true)}, /TypeError: Unexpected type of argument in function unnamed \(expected: number, actual: boolean, index: 1\)/); + }); + + it('should continue with other options if rest params do not match', function() { + var fn = typed({ + '...number': function (values) { + return '...number'; + }, + + 'Object': function (value) { + return 'Object'; + } + }); + + assert.equal(fn(2, 3), '...number'); + assert.equal(fn(2), '...number'); + assert.equal(fn({}), 'Object'); + assert.deepEqual(Object.keys(fn.signatures), [ + 'Object', + '...number' + ]); + }); + + it('should split rest params with conversions in two and order them correctly', function() { + var typed2 = typed.create() + typed2.conversions = [ + {from: 'string', to: 'number', convert: function (x) {return parseFloat(x)}} + ]; + + var fn = typed2({ + '...number': function (values) { + return values; + }, + + '...string': function (value) { + return value; + } + }); + + assert.deepEqual(fn(2, 3), [2,3]); + assert.deepEqual(fn(2), [2]); + assert.deepEqual(fn(2, '4'), [2, 4]); + assert.deepEqual(fn('2', 4), [2, 4]); + assert.deepEqual(fn('foo'), ['foo']); + assert.deepEqual(Object.keys(fn.signatures), [ + '...number', + '...string' + ]); + }); + + it('should throw an error in case of unexpected rest parameters', function() { + assert.throws(function () { + typed({'...number, string': function () {}}); + }, /SyntaxError: Unexpected rest parameter "...number": only allowed for the last parameter/); + }); + + it('should correctly interact with any', function() { + var fn = typed({ + 'string': function () { + return 'one'; + }, + '...any': function () { + return 'two'; + } + }); + + assert.equal(fn('a'), 'one'); + assert.equal(fn([]), 'two'); + assert.equal(fn('a','a'), 'two'); + assert.equal(fn('a',[]), 'two'); + assert.equal(fn([],[]), 'two'); + }); + +}); diff --git a/node_modules/typed-function/test/security.test.js b/node_modules/typed-function/test/security.test.js new file mode 100644 index 0000000..0b5a5f8 --- /dev/null +++ b/node_modules/typed-function/test/security.test.js @@ -0,0 +1,17 @@ +var assert = require('assert'); +var typed = require('../typed-function'); + +describe('security', function () { + + it ('should not allow bad code in the function name', function () { + // simple example: + // var fn = typed("(){}+console.log('hacked...');function a", { + // "": function () {} + // }); + + // example resulting in throwing an error if successful + var fn = typed("(){}+(function(){throw new Error('Hacked... should not have executed this function!!!')})();function a", { + "": function () {} + }); + }) +}) diff --git a/node_modules/typed-function/test/strictEqualArray.js b/node_modules/typed-function/test/strictEqualArray.js new file mode 100644 index 0000000..2cb2124 --- /dev/null +++ b/node_modules/typed-function/test/strictEqualArray.js @@ -0,0 +1,14 @@ +var assert = require('assert'); + +/** + * Test strict equality of all elements in two arrays. + * @param {Array} a + * @param {Array} b + */ +module.exports = function strictEqualArray(a, b) { + assert.strictEqual(a.length, b.length); + + for (var i = 0; i < a.length; a++) { + assert.strictEqual(a[i], b[i]); + } +}; diff --git a/node_modules/typed-function/test/union_types.test.js b/node_modules/typed-function/test/union_types.test.js new file mode 100644 index 0000000..9bf15aa --- /dev/null +++ b/node_modules/typed-function/test/union_types.test.js @@ -0,0 +1,18 @@ +var assert = require('assert'); +var typed = require('../typed-function'); + +describe('union types', function () { + + it('should create a typed function with union types', function() { + var fn = typed({ + 'number | boolean': function (arg) { + return typeof arg; + } + }); + + assert.equal(fn(true), 'boolean'); + assert.equal(fn(2), 'number'); + assert.throws(function () {fn('string')}, /TypeError: Unexpected type of argument in function unnamed \(expected: number or boolean, actual: string, index: 0\)/); + }); + +}); diff --git a/node_modules/typed-function/typed-function.js b/node_modules/typed-function/typed-function.js new file mode 100644 index 0000000..a62e5ca --- /dev/null +++ b/node_modules/typed-function/typed-function.js @@ -0,0 +1,1404 @@ +/** + * typed-function + * + * Type checking for JavaScript functions + * + * https://github.com/josdejong/typed-function + */ +'use strict'; + +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([], factory); + } else if (typeof exports === 'object') { + // OldNode. Does not work with strict CommonJS, but + // only CommonJS-like environments that support module.exports, + // like OldNode. + module.exports = factory(); + } else { + // Browser globals (root is window) + root.typed = factory(); + } +}(this, function () { + + function ok () { + return true; + } + + function notOk () { + return false; + } + + function undef () { + return undefined; + } + + /** + * @typedef {{ + * params: Param[], + * fn: function + * }} Signature + * + * @typedef {{ + * types: Type[], + * restParam: boolean + * }} Param + * + * @typedef {{ + * name: string, + * typeIndex: number, + * test: function, + * conversion?: ConversionDef, + * conversionIndex: number, + * }} Type + * + * @typedef {{ + * from: string, + * to: string, + * convert: function (*) : * + * }} ConversionDef + * + * @typedef {{ + * name: string, + * test: function(*) : boolean + * }} TypeDef + */ + + // create a new instance of typed-function + function create () { + // data type tests + var _types = [ + { name: 'number', test: function (x) { return typeof x === 'number' } }, + { name: 'string', test: function (x) { return typeof x === 'string' } }, + { name: 'boolean', test: function (x) { return typeof x === 'boolean' } }, + { name: 'Function', test: function (x) { return typeof x === 'function'} }, + { name: 'Array', test: Array.isArray }, + { name: 'Date', test: function (x) { return x instanceof Date } }, + { name: 'RegExp', test: function (x) { return x instanceof RegExp } }, + { name: 'Object', test: function (x) { + return typeof x === 'object' && x !== null && x.constructor === Object + }}, + { name: 'null', test: function (x) { return x === null } }, + { name: 'undefined', test: function (x) { return x === undefined } } + ]; + + var anyType = { + name: 'any', + test: ok + } + + // types which need to be ignored + var _ignore = []; + + // type conversions + var _conversions = []; + + // This is a temporary object, will be replaced with a typed function at the end + var typed = { + types: _types, + conversions: _conversions, + ignore: _ignore + }; + + /** + * Find the test function for a type + * @param {String} typeName + * @return {TypeDef} Returns the type definition when found, + * Throws a TypeError otherwise + */ + function findTypeByName (typeName) { + var entry = findInArray(typed.types, function (entry) { + return entry.name === typeName; + }); + + if (entry) { + return entry; + } + + if (typeName === 'any') { // special baked-in case 'any' + return anyType; + } + + var hint = findInArray(typed.types, function (entry) { + return entry.name.toLowerCase() === typeName.toLowerCase(); + }); + + throw new TypeError('Unknown type "' + typeName + '"' + + (hint ? ('. Did you mean "' + hint.name + '"?') : '')); + } + + /** + * Find the index of a type definition. Handles special case 'any' + * @param {TypeDef} type + * @return {number} + */ + function findTypeIndex(type) { + if (type === anyType) { + return 999; + } + + return typed.types.indexOf(type); + } + + /** + * Find a type that matches a value. + * @param {*} value + * @return {string} Returns the name of the first type for which + * the type test matches the value. + */ + function findTypeName(value) { + var entry = findInArray(typed.types, function (entry) { + return entry.test(value); + }); + + if (entry) { + return entry.name; + } + + throw new TypeError('Value has unknown type. Value: ' + value); + } + + /** + * Find a specific signature from a (composed) typed function, for example: + * + * typed.find(fn, ['number', 'string']) + * typed.find(fn, 'number, string') + * + * Function find only only works for exact matches. + * + * @param {Function} fn A typed-function + * @param {string | string[]} signature Signature to be found, can be + * an array or a comma separated string. + * @return {Function} Returns the matching signature, or + * throws an error when no signature + * is found. + */ + function find (fn, signature) { + if (!fn.signatures) { + throw new TypeError('Function is no typed-function'); + } + + // normalize input + var arr; + if (typeof signature === 'string') { + arr = signature.split(','); + for (var i = 0; i < arr.length; i++) { + arr[i] = arr[i].trim(); + } + } + else if (Array.isArray(signature)) { + arr = signature; + } + else { + throw new TypeError('String array or a comma separated string expected'); + } + + var str = arr.join(','); + + // find an exact match + var match = fn.signatures[str]; + if (match) { + return match; + } + + // TODO: extend find to match non-exact signatures + + throw new TypeError('Signature not found (signature: ' + (fn.name || 'unnamed') + '(' + arr.join(', ') + '))'); + } + + /** + * Convert a given value to another data type. + * @param {*} value + * @param {string} type + */ + function convert (value, type) { + var from = findTypeName(value); + + // check conversion is needed + if (type === from) { + return value; + } + + for (var i = 0; i < typed.conversions.length; i++) { + var conversion = typed.conversions[i]; + if (conversion.from === from && conversion.to === type) { + return conversion.convert(value); + } + } + + throw new Error('Cannot convert from ' + from + ' to ' + type); + } + + /** + * Stringify parameters in a normalized way + * @param {Param[]} params + * @return {string} + */ + function stringifyParams (params) { + return params + .map(function (param) { + var typeNames = param.types.map(getTypeName); + + return (param.restParam ? '...' : '') + typeNames.join('|'); + }) + .join(','); + } + + /** + * Parse a parameter, like "...number | boolean" + * @param {string} param + * @param {ConversionDef[]} conversions + * @return {Param} param + */ + function parseParam (param, conversions) { + var restParam = param.indexOf('...') === 0; + var types = (!restParam) + ? param + : (param.length > 3) + ? param.slice(3) + : 'any'; + + var typeNames = types.split('|').map(trim) + .filter(notEmpty) + .filter(notIgnore); + + var matchingConversions = filterConversions(conversions, typeNames); + + var exactTypes = typeNames.map(function (typeName) { + var type = findTypeByName(typeName); + + return { + name: typeName, + typeIndex: findTypeIndex(type), + test: type.test, + conversion: null, + conversionIndex: -1 + }; + }); + + var convertibleTypes = matchingConversions.map(function (conversion) { + var type = findTypeByName(conversion.from); + + return { + name: conversion.from, + typeIndex: findTypeIndex(type), + test: type.test, + conversion: conversion, + conversionIndex: conversions.indexOf(conversion) + }; + }); + + return { + types: exactTypes.concat(convertibleTypes), + restParam: restParam + }; + } + + /** + * Parse a signature with comma separated parameters, + * like "number | boolean, ...string" + * @param {string} signature + * @param {function} fn + * @param {ConversionDef[]} conversions + * @return {Signature | null} signature + */ + function parseSignature (signature, fn, conversions) { + var params = []; + + if (signature.trim() !== '') { + params = signature + .split(',') + .map(trim) + .map(function (param, index, array) { + var parsedParam = parseParam(param, conversions); + + if (parsedParam.restParam && (index !== array.length - 1)) { + throw new SyntaxError('Unexpected rest parameter "' + param + '": ' + + 'only allowed for the last parameter'); + } + + return parsedParam; + }); + } + + if (params.some(isInvalidParam)) { + // invalid signature: at least one parameter has no types + // (they may have been filtered) + return null; + } + + return { + params: params, + fn: fn + }; + } + + /** + * Test whether a set of params contains a restParam + * @param {Param[]} params + * @return {boolean} Returns true when the last parameter is a restParam + */ + function hasRestParam(params) { + var param = last(params) + return param ? param.restParam : false; + } + + /** + * Test whether a parameter contains conversions + * @param {Param} param + * @return {boolean} Returns true when at least one of the parameters + * contains a conversion. + */ + function hasConversions(param) { + return param.types.some(function (type) { + return type.conversion != null; + }); + } + + /** + * Create a type test for a single parameter, which can have one or multiple + * types. + * @param {Param} param + * @return {function(x: *) : boolean} Returns a test function + */ + function compileTest(param) { + if (!param || param.types.length === 0) { + // nothing to do + return ok; + } + else if (param.types.length === 1) { + return findTypeByName(param.types[0].name).test; + } + else if (param.types.length === 2) { + var test0 = findTypeByName(param.types[0].name).test; + var test1 = findTypeByName(param.types[1].name).test; + return function or(x) { + return test0(x) || test1(x); + } + } + else { // param.types.length > 2 + var tests = param.types.map(function (type) { + return findTypeByName(type.name).test; + }) + return function or(x) { + for (var i = 0; i < tests.length; i++) { + if (tests[i](x)) { + return true; + } + } + return false; + } + } + } + + /** + * Create a test for all parameters of a signature + * @param {Param[]} params + * @return {function(args: Array<*>) : boolean} + */ + function compileTests(params) { + var tests, test0, test1; + + if (hasRestParam(params)) { + // variable arguments like '...number' + tests = initial(params).map(compileTest); + var varIndex = tests.length; + var lastTest = compileTest(last(params)); + var testRestParam = function (args) { + for (var i = varIndex; i < args.length; i++) { + if (!lastTest(args[i])) { + return false; + } + } + return true; + } + + return function testArgs(args) { + for (var i = 0; i < tests.length; i++) { + if (!tests[i](args[i])) { + return false; + } + } + return testRestParam(args) && (args.length >= varIndex + 1); + }; + } + else { + // no variable arguments + if (params.length === 0) { + return function testArgs(args) { + return args.length === 0; + }; + } + else if (params.length === 1) { + test0 = compileTest(params[0]); + return function testArgs(args) { + return test0(args[0]) && args.length === 1; + }; + } + else if (params.length === 2) { + test0 = compileTest(params[0]); + test1 = compileTest(params[1]); + return function testArgs(args) { + return test0(args[0]) && test1(args[1]) && args.length === 2; + }; + } + else { // arguments.length > 2 + tests = params.map(compileTest); + return function testArgs(args) { + for (var i = 0; i < tests.length; i++) { + if (!tests[i](args[i])) { + return false; + } + } + return args.length === tests.length; + }; + } + } + } + + /** + * Find the parameter at a specific index of a signature. + * Handles rest parameters. + * @param {Signature} signature + * @param {number} index + * @return {Param | null} Returns the matching parameter when found, + * null otherwise. + */ + function getParamAtIndex(signature, index) { + return index < signature.params.length + ? signature.params[index] + : hasRestParam(signature.params) + ? last(signature.params) + : null + } + + /** + * Get all type names of a parameter + * @param {Signature} signature + * @param {number} index + * @param {boolean} excludeConversions + * @return {string[]} Returns an array with type names + */ + function getExpectedTypeNames (signature, index, excludeConversions) { + var param = getParamAtIndex(signature, index); + var types = param + ? excludeConversions + ? param.types.filter(isExactType) + : param.types + : []; + + return types.map(getTypeName); + } + + /** + * Returns the name of a type + * @param {Type} type + * @return {string} Returns the type name + */ + function getTypeName(type) { + return type.name; + } + + /** + * Test whether a type is an exact type or conversion + * @param {Type} type + * @return {boolean} Returns true when + */ + function isExactType(type) { + return type.conversion === null || type.conversion === undefined; + } + + /** + * Helper function for creating error messages: create an array with + * all available types on a specific argument index. + * @param {Signature[]} signatures + * @param {number} index + * @return {string[]} Returns an array with available types + */ + function mergeExpectedParams(signatures, index) { + var typeNames = uniq(flatMap(signatures, function (signature) { + return getExpectedTypeNames(signature, index, false); + })); + + return (typeNames.indexOf('any') !== -1) ? ['any'] : typeNames; + } + + /** + * Create + * @param {string} name The name of the function + * @param {array.<*>} args The actual arguments passed to the function + * @param {Signature[]} signatures A list with available signatures + * @return {TypeError} Returns a type error with additional data + * attached to it in the property `data` + */ + function createError(name, args, signatures) { + var err, expected; + var _name = name || 'unnamed'; + + // test for wrong type at some index + var matchingSignatures = signatures; + var index; + for (index = 0; index < args.length; index++) { + var nextMatchingDefs = matchingSignatures.filter(function (signature) { + var test = compileTest(getParamAtIndex(signature, index)); + return (index < signature.params.length || hasRestParam(signature.params)) && + test(args[index]); + }); + + if (nextMatchingDefs.length === 0) { + // no matching signatures anymore, throw error "wrong type" + expected = mergeExpectedParams(matchingSignatures, index); + if (expected.length > 0) { + var actualType = findTypeName(args[index]); + + err = new TypeError('Unexpected type of argument in function ' + _name + + ' (expected: ' + expected.join(' or ') + + ', actual: ' + actualType + ', index: ' + index + ')'); + err.data = { + category: 'wrongType', + fn: _name, + index: index, + actual: actualType, + expected: expected + } + return err; + } + } + else { + matchingSignatures = nextMatchingDefs; + } + } + + // test for too few arguments + var lengths = matchingSignatures.map(function (signature) { + return hasRestParam(signature.params) ? Infinity : signature.params.length; + }); + if (args.length < Math.min.apply(null, lengths)) { + expected = mergeExpectedParams(matchingSignatures, index); + err = new TypeError('Too few arguments in function ' + _name + + ' (expected: ' + expected.join(' or ') + + ', index: ' + args.length + ')'); + err.data = { + category: 'tooFewArgs', + fn: _name, + index: args.length, + expected: expected + } + return err; + } + + // test for too many arguments + var maxLength = Math.max.apply(null, lengths); + if (args.length > maxLength) { + err = new TypeError('Too many arguments in function ' + _name + + ' (expected: ' + maxLength + ', actual: ' + args.length + ')'); + err.data = { + category: 'tooManyArgs', + fn: _name, + index: args.length, + expectedLength: maxLength + } + return err; + } + + err = new TypeError('Arguments of type "' + args.join(', ') + + '" do not match any of the defined signatures of function ' + _name + '.'); + err.data = { + category: 'mismatch', + actual: args.map(findTypeName) + } + return err; + } + + /** + * Find the lowest index of all exact types of a parameter (no conversions) + * @param {Param} param + * @return {number} Returns the index of the lowest type in typed.types + */ + function getLowestTypeIndex (param) { + var min = 999; + + for (var i = 0; i < param.types.length; i++) { + if (isExactType(param.types[i])) { + min = Math.min(min, param.types[i].typeIndex); + } + } + + return min; + } + + /** + * Find the lowest index of the conversion of all types of the parameter + * having a conversion + * @param {Param} param + * @return {number} Returns the lowest index of the conversions of this type + */ + function getLowestConversionIndex (param) { + var min = 999; + + for (var i = 0; i < param.types.length; i++) { + if (!isExactType(param.types[i])) { + min = Math.min(min, param.types[i].conversionIndex); + } + } + + return min; + } + + /** + * Compare two params + * @param {Param} param1 + * @param {Param} param2 + * @return {number} returns a negative number when param1 must get a lower + * index than param2, a positive number when the opposite, + * or zero when both are equal + */ + function compareParams (param1, param2) { + var c; + + // compare having a rest parameter or not + c = param1.restParam - param2.restParam; + if (c !== 0) { + return c; + } + + // compare having conversions or not + c = hasConversions(param1) - hasConversions(param2); + if (c !== 0) { + return c; + } + + // compare the index of the types + c = getLowestTypeIndex(param1) - getLowestTypeIndex(param2); + if (c !== 0) { + return c; + } + + // compare the index of any conversion + return getLowestConversionIndex(param1) - getLowestConversionIndex(param2); + } + + /** + * Compare two signatures + * @param {Signature} signature1 + * @param {Signature} signature2 + * @return {number} returns a negative number when param1 must get a lower + * index than param2, a positive number when the opposite, + * or zero when both are equal + */ + function compareSignatures (signature1, signature2) { + var len = Math.min(signature1.params.length, signature2.params.length); + var i; + var c; + + // compare whether the params have conversions at all or not + c = signature1.params.some(hasConversions) - signature2.params.some(hasConversions) + if (c !== 0) { + return c; + } + + // next compare whether the params have conversions one by one + for (i = 0; i < len; i++) { + c = hasConversions(signature1.params[i]) - hasConversions(signature2.params[i]); + if (c !== 0) { + return c; + } + } + + // compare the types of the params one by one + for (i = 0; i < len; i++) { + c = compareParams(signature1.params[i], signature2.params[i]); + if (c !== 0) { + return c; + } + } + + // compare the number of params + return signature1.params.length - signature2.params.length; + } + + /** + * Get params containing all types that can be converted to the defined types. + * + * @param {ConversionDef[]} conversions + * @param {string[]} typeNames + * @return {ConversionDef[]} Returns the conversions that are available + * for every type (if any) + */ + function filterConversions(conversions, typeNames) { + var matches = {}; + + conversions.forEach(function (conversion) { + if (typeNames.indexOf(conversion.from) === -1 && + typeNames.indexOf(conversion.to) !== -1 && + !matches[conversion.from]) { + matches[conversion.from] = conversion; + } + }); + + return Object.keys(matches).map(function (from) { + return matches[from]; + }); + } + + /** + * Preprocess arguments before calling the original function: + * - if needed convert the parameters + * - in case of rest parameters, move the rest parameters into an Array + * @param {Param[]} params + * @param {function} fn + * @return {function} Returns a wrapped function + */ + function compileArgsPreprocessing(params, fn) { + var fnConvert = fn; + + // TODO: can we make this wrapper function smarter/simpler? + + if (params.some(hasConversions)) { + var restParam = hasRestParam(params); + var compiledConversions = params.map(compileArgConversion) + + fnConvert = function convertArgs() { + var args = []; + var last = restParam ? arguments.length - 1 : arguments.length; + for (var i = 0; i < last; i++) { + args[i] = compiledConversions[i](arguments[i]); + } + if (restParam) { + args[last] = arguments[last].map(compiledConversions[last]); + } + + return fn.apply(this, args); + } + } + + var fnPreprocess = fnConvert; + if (hasRestParam(params)) { + var offset = params.length - 1; + + fnPreprocess = function preprocessRestParams () { + return fnConvert.apply(this, + slice(arguments, 0, offset).concat([slice(arguments, offset)])); + } + } + + return fnPreprocess; + } + + /** + * Compile conversion for a parameter to the right type + * @param {Param} param + * @return {function} Returns the wrapped function that will convert arguments + * + */ + function compileArgConversion(param) { + var test0, test1, conversion0, conversion1; + var tests = []; + var conversions = []; + + param.types.forEach(function (type) { + if (type.conversion) { + tests.push(findTypeByName(type.conversion.from).test); + conversions.push(type.conversion.convert); + } + }); + + // create optimized conversion functions depending on the number of conversions + switch (conversions.length) { + case 0: + return function convertArg(arg) { + return arg; + } + + case 1: + test0 = tests[0] + conversion0 = conversions[0]; + return function convertArg(arg) { + if (test0(arg)) { + return conversion0(arg) + } + return arg; + } + + case 2: + test0 = tests[0] + test1 = tests[1] + conversion0 = conversions[0]; + conversion1 = conversions[1]; + return function convertArg(arg) { + if (test0(arg)) { + return conversion0(arg) + } + if (test1(arg)) { + return conversion1(arg) + } + return arg; + } + + default: + return function convertArg(arg) { + for (var i = 0; i < conversions.length; i++) { + if (tests[i](arg)) { + return conversions[i](arg); + } + } + return arg; + } + } + } + + /** + * Convert an array with signatures into a map with signatures, + * where signatures with union types are split into separate signatures + * + * Throws an error when there are conflicting types + * + * @param {Signature[]} signatures + * @return {Object.} Returns a map with signatures + * as key and the original function + * of this signature as value. + */ + function createSignaturesMap(signatures) { + var signaturesMap = {}; + signatures.forEach(function (signature) { + if (!signature.params.some(hasConversions)) { + splitParams(signature.params, true).forEach(function (params) { + signaturesMap[stringifyParams(params)] = signature.fn; + }); + } + }); + + return signaturesMap; + } + + /** + * Split params with union types in to separate params. + * + * For example: + * + * splitParams([['Array', 'Object'], ['string', 'RegExp']) + * // returns: + * // [ + * // ['Array', 'string'], + * // ['Array', 'RegExp'], + * // ['Object', 'string'], + * // ['Object', 'RegExp'] + * // ] + * + * @param {Param[]} params + * @param {boolean} ignoreConversionTypes + * @return {Param[]} + */ + function splitParams(params, ignoreConversionTypes) { + function _splitParams(params, index, types) { + if (index < params.length) { + var param = params[index] + var filteredTypes = ignoreConversionTypes + ? param.types.filter(isExactType) + : param.types; + var typeGroups + + if (param.restParam) { + // split the types of a rest parameter in two: + // one with only exact types, and one with exact types and conversions + var exactTypes = filteredTypes.filter(isExactType) + typeGroups = exactTypes.length < filteredTypes.length + ? [exactTypes, filteredTypes] + : [filteredTypes] + + } + else { + // split all the types of a regular parameter into one type per group + typeGroups = filteredTypes.map(function (type) { + return [type] + }) + } + + // recurse over the groups with types + return flatMap(typeGroups, function (typeGroup) { + return _splitParams(params, index + 1, types.concat([typeGroup])); + }); + + } + else { + // we've reached the end of the parameters. Now build a new Param + var splittedParams = types.map(function (type, typeIndex) { + return { + types: type, + restParam: (typeIndex === params.length - 1) && hasRestParam(params) + } + }); + + return [splittedParams]; + } + } + + return _splitParams(params, 0, []); + } + + /** + * Test whether two signatures have a conflicting signature + * @param {Signature} signature1 + * @param {Signature} signature2 + * @return {boolean} Returns true when the signatures conflict, false otherwise. + */ + function hasConflictingParams(signature1, signature2) { + var ii = Math.max(signature1.params.length, signature2.params.length); + + for (var i = 0; i < ii; i++) { + var typesNames1 = getExpectedTypeNames(signature1, i, true); + var typesNames2 = getExpectedTypeNames(signature2, i, true); + + if (!hasOverlap(typesNames1, typesNames2)) { + return false; + } + } + + var len1 = signature1.params.length; + var len2 = signature2.params.length; + var restParam1 = hasRestParam(signature1.params); + var restParam2 = hasRestParam(signature2.params); + + return restParam1 + ? restParam2 ? (len1 === len2) : (len2 >= len1) + : restParam2 ? (len1 >= len2) : (len1 === len2) + } + + /** + * Create a typed function + * @param {String} name The name for the typed function + * @param {Object.} signaturesMap + * An object with one or + * multiple signatures as key, and the + * function corresponding to the + * signature as value. + * @return {function} Returns the created typed function. + */ + function createTypedFunction(name, signaturesMap) { + if (Object.keys(signaturesMap).length === 0) { + throw new SyntaxError('No signatures provided'); + } + + // parse the signatures, and check for conflicts + var parsedSignatures = []; + Object.keys(signaturesMap) + .map(function (signature) { + return parseSignature(signature, signaturesMap[signature], typed.conversions); + }) + .filter(notNull) + .forEach(function (parsedSignature) { + // check whether this parameter conflicts with already parsed signatures + var conflictingSignature = findInArray(parsedSignatures, function (s) { + return hasConflictingParams(s, parsedSignature) + }); + if (conflictingSignature) { + throw new TypeError('Conflicting signatures "' + + stringifyParams(conflictingSignature.params) + '" and "' + + stringifyParams(parsedSignature.params) + '".'); + } + + parsedSignatures.push(parsedSignature); + }); + + // split and filter the types of the signatures, and then order them + var signatures = flatMap(parsedSignatures, function (parsedSignature) { + var params = parsedSignature ? splitParams(parsedSignature.params, false) : [] + + return params.map(function (params) { + return { + params: params, + fn: parsedSignature.fn + }; + }); + }).filter(notNull); + + signatures.sort(compareSignatures); + + // we create a highly optimized checks for the first couple of signatures with max 2 arguments + var ok0 = signatures[0] && signatures[0].params.length <= 2 && !hasRestParam(signatures[0].params); + var ok1 = signatures[1] && signatures[1].params.length <= 2 && !hasRestParam(signatures[1].params); + var ok2 = signatures[2] && signatures[2].params.length <= 2 && !hasRestParam(signatures[2].params); + var ok3 = signatures[3] && signatures[3].params.length <= 2 && !hasRestParam(signatures[3].params); + var ok4 = signatures[4] && signatures[4].params.length <= 2 && !hasRestParam(signatures[4].params); + var ok5 = signatures[5] && signatures[5].params.length <= 2 && !hasRestParam(signatures[5].params); + var allOk = ok0 && ok1 && ok2 && ok3 && ok4 && ok5; + + // compile the tests + var tests = signatures.map(function (signature) { + return compileTests(signature.params); + }); + + var test00 = ok0 ? compileTest(signatures[0].params[0]) : notOk; + var test10 = ok1 ? compileTest(signatures[1].params[0]) : notOk; + var test20 = ok2 ? compileTest(signatures[2].params[0]) : notOk; + var test30 = ok3 ? compileTest(signatures[3].params[0]) : notOk; + var test40 = ok4 ? compileTest(signatures[4].params[0]) : notOk; + var test50 = ok5 ? compileTest(signatures[5].params[0]) : notOk; + + var test01 = ok0 ? compileTest(signatures[0].params[1]) : notOk; + var test11 = ok1 ? compileTest(signatures[1].params[1]) : notOk; + var test21 = ok2 ? compileTest(signatures[2].params[1]) : notOk; + var test31 = ok3 ? compileTest(signatures[3].params[1]) : notOk; + var test41 = ok4 ? compileTest(signatures[4].params[1]) : notOk; + var test51 = ok5 ? compileTest(signatures[5].params[1]) : notOk; + + // compile the functions + var fns = signatures.map(function(signature) { + return compileArgsPreprocessing(signature.params, signature.fn); + }); + + var fn0 = ok0 ? fns[0] : undef; + var fn1 = ok1 ? fns[1] : undef; + var fn2 = ok2 ? fns[2] : undef; + var fn3 = ok3 ? fns[3] : undef; + var fn4 = ok4 ? fns[4] : undef; + var fn5 = ok5 ? fns[5] : undef; + + var len0 = ok0 ? signatures[0].params.length : -1; + var len1 = ok1 ? signatures[1].params.length : -1; + var len2 = ok2 ? signatures[2].params.length : -1; + var len3 = ok3 ? signatures[3].params.length : -1; + var len4 = ok4 ? signatures[4].params.length : -1; + var len5 = ok5 ? signatures[5].params.length : -1; + + // simple and generic, but also slow + var iStart = allOk ? 6 : 0; + var iEnd = signatures.length; + var generic = function generic() { + 'use strict'; + + for (var i = iStart; i < iEnd; i++) { + if (tests[i](arguments)) { + return fns[i].apply(this, arguments); + } + } + + return typed.onMismatch(name, arguments, signatures); + } + + // create the typed function + // fast, specialized version. Falls back to the slower, generic one if needed + var fn = function fn(arg0, arg1) { + 'use strict'; + + if (arguments.length === len0 && test00(arg0) && test01(arg1)) { return fn0.apply(fn, arguments); } + if (arguments.length === len1 && test10(arg0) && test11(arg1)) { return fn1.apply(fn, arguments); } + if (arguments.length === len2 && test20(arg0) && test21(arg1)) { return fn2.apply(fn, arguments); } + if (arguments.length === len3 && test30(arg0) && test31(arg1)) { return fn3.apply(fn, arguments); } + if (arguments.length === len4 && test40(arg0) && test41(arg1)) { return fn4.apply(fn, arguments); } + if (arguments.length === len5 && test50(arg0) && test51(arg1)) { return fn5.apply(fn, arguments); } + + return generic.apply(fn, arguments); + } + + // attach name the typed function + try { + Object.defineProperty(fn, 'name', {value: name}); + } + catch (err) { + // old browsers do not support Object.defineProperty and some don't support setting the name property + // the function name is not essential for the functioning, it's mostly useful for debugging, + // so it's fine to have unnamed functions. + } + + // attach signatures to the function + fn.signatures = createSignaturesMap(signatures); + + return fn; + } + + /** + * Action to take on mismatch + * @param {string} name Name of function that was attempted to be called + * @param {Array} args Actual arguments to the call + * @param {Array} signatures Known signatures of the named typed-function + */ + function _onMismatch(name, args, signatures) { + throw createError(name, args, signatures); + } + + /** + * Test whether a type should be NOT be ignored + * @param {string} typeName + * @return {boolean} + */ + function notIgnore(typeName) { + return typed.ignore.indexOf(typeName) === -1; + } + + /** + * trim a string + * @param {string} str + * @return {string} + */ + function trim(str) { + return str.trim(); + } + + /** + * Test whether a string is not empty + * @param {string} str + * @return {boolean} + */ + function notEmpty(str) { + return !!str; + } + + /** + * test whether a value is not strict equal to null + * @param {*} value + * @return {boolean} + */ + function notNull(value) { + return value !== null; + } + + /** + * Test whether a parameter has no types defined + * @param {Param} param + * @return {boolean} + */ + function isInvalidParam (param) { + return param.types.length === 0; + } + + /** + * Return all but the last items of an array + * @param {Array} arr + * @return {Array} + */ + function initial(arr) { + return arr.slice(0, arr.length - 1); + } + + /** + * return the last item of an array + * @param {Array} arr + * @return {*} + */ + function last(arr) { + return arr[arr.length - 1]; + } + + /** + * Slice an array or function Arguments + * @param {Array | Arguments | IArguments} arr + * @param {number} start + * @param {number} [end] + * @return {Array} + */ + function slice(arr, start, end) { + return Array.prototype.slice.call(arr, start, end); + } + + /** + * Test whether an array contains some item + * @param {Array} array + * @param {*} item + * @return {boolean} Returns true if array contains item, false if not. + */ + function contains(array, item) { + return array.indexOf(item) !== -1; + } + + /** + * Test whether two arrays have overlapping items + * @param {Array} array1 + * @param {Array} array2 + * @return {boolean} Returns true when at least one item exists in both arrays + */ + function hasOverlap(array1, array2) { + for (var i = 0; i < array1.length; i++) { + if (contains(array2, array1[i])) { + return true; + } + } + + return false; + } + + /** + * Return the first item from an array for which test(arr[i]) returns true + * @param {Array} arr + * @param {function} test + * @return {* | undefined} Returns the first matching item + * or undefined when there is no match + */ + function findInArray(arr, test) { + for (var i = 0; i < arr.length; i++) { + if (test(arr[i])) { + return arr[i]; + } + } + return undefined; + } + + /** + * Filter unique items of an array with strings + * @param {string[]} arr + * @return {string[]} + */ + function uniq(arr) { + var entries = {} + for (var i = 0; i < arr.length; i++) { + entries[arr[i]] = true; + } + return Object.keys(entries); + } + + /** + * Flat map the result invoking a callback for every item in an array. + * https://gist.github.com/samgiles/762ee337dff48623e729 + * @param {Array} arr + * @param {function} callback + * @return {Array} + */ + function flatMap(arr, callback) { + return Array.prototype.concat.apply([], arr.map(callback)); + } + + /** + * Retrieve the function name from a set of typed functions, + * and check whether the name of all functions match (if given) + * @param {function[]} fns + */ + function getName (fns) { + var name = ''; + + for (var i = 0; i < fns.length; i++) { + var fn = fns[i]; + + // check whether the names are the same when defined + if ((typeof fn.signatures === 'object' || typeof fn.signature === 'string') && fn.name !== '') { + if (name === '') { + name = fn.name; + } + else if (name !== fn.name) { + var err = new Error('Function names do not match (expected: ' + name + ', actual: ' + fn.name + ')'); + err.data = { + actual: fn.name, + expected: name + }; + throw err; + } + } + } + + return name; + } + + // extract and merge all signatures of a list with typed functions + function extractSignatures(fns) { + var err; + var signaturesMap = {}; + + function validateUnique(_signature, _fn) { + if (signaturesMap.hasOwnProperty(_signature) && _fn !== signaturesMap[_signature]) { + err = new Error('Signature "' + _signature + '" is defined twice'); + err.data = {signature: _signature}; + throw err; + // else: both signatures point to the same function, that's fine + } + } + + for (var i = 0; i < fns.length; i++) { + var fn = fns[i]; + + // test whether this is a typed-function + if (typeof fn.signatures === 'object') { + // merge the signatures + for (var signature in fn.signatures) { + if (fn.signatures.hasOwnProperty(signature)) { + validateUnique(signature, fn.signatures[signature]); + signaturesMap[signature] = fn.signatures[signature]; + } + } + } + else if (typeof fn.signature === 'string') { + validateUnique(fn.signature, fn); + signaturesMap[fn.signature] = fn; + } + else { + err = new TypeError('Function is no typed-function (index: ' + i + ')'); + err.data = {index: i}; + throw err; + } + } + + return signaturesMap; + } + + typed = createTypedFunction('typed', { + 'string, Object': createTypedFunction, + 'Object': function (signaturesMap) { + // find existing name + var fns = []; + for (var signature in signaturesMap) { + if (signaturesMap.hasOwnProperty(signature)) { + fns.push(signaturesMap[signature]); + } + } + var name = getName(fns); + return createTypedFunction(name, signaturesMap); + }, + '...Function': function (fns) { + return createTypedFunction(getName(fns), extractSignatures(fns)); + }, + 'string, ...Function': function (name, fns) { + return createTypedFunction(name, extractSignatures(fns)); + } + }); + + typed.create = create; + typed.types = _types; + typed.conversions = _conversions; + typed.ignore = _ignore; + typed.onMismatch = _onMismatch; + typed.throwMismatchError = _onMismatch; + typed.createError = createError; + typed.convert = convert; + typed.find = find; + + /** + * add a type + * @param {{name: string, test: function}} type + * @param {boolean} [beforeObjectTest=true] + * If true, the new test will be inserted before + * the test with name 'Object' (if any), since + * tests for Object match Array and classes too. + */ + typed.addType = function (type, beforeObjectTest) { + if (!type || typeof type.name !== 'string' || typeof type.test !== 'function') { + throw new TypeError('Object with properties {name: string, test: function} expected'); + } + + if (beforeObjectTest !== false) { + for (var i = 0; i < typed.types.length; i++) { + if (typed.types[i].name === 'Object') { + typed.types.splice(i, 0, type); + return + } + } + } + + typed.types.push(type); + }; + + // add a conversion + typed.addConversion = function (conversion) { + if (!conversion + || typeof conversion.from !== 'string' + || typeof conversion.to !== 'string' + || typeof conversion.convert !== 'function') { + throw new TypeError('Object with properties {from: string, to: string, convert: function} expected'); + } + + typed.conversions.push(conversion); + }; + + return typed; + } + + return create(); +})); diff --git a/node_modules/typed-function/typed-function.min.js b/node_modules/typed-function/typed-function.min.js new file mode 100644 index 0000000..0290e6f --- /dev/null +++ b/node_modules/typed-function/typed-function.min.js @@ -0,0 +1 @@ +"use strict";!function(n,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?module.exports=t():n.typed=t()}(this,function(){function O(){return!0}function en(){return!1}function an(){}return function n(){var t=[{name:"number",test:function(n){return"number"==typeof n}},{name:"string",test:function(n){return"string"==typeof n}},{name:"boolean",test:function(n){return"boolean"==typeof n}},{name:"Function",test:function(n){return"function"==typeof n}},{name:"Array",test:Array.isArray},{name:"Date",test:function(n){return n instanceof Date}},{name:"RegExp",test:function(n){return n instanceof RegExp}},{name:"Object",test:function(n){return"object"==typeof n&&null!==n&&n.constructor===Object}},{name:"null",test:function(n){return null===n}},{name:"undefined",test:function(n){return void 0===n}}],r={name:"any",test:O},e=[],a=[],q={types:t,conversions:a,ignore:e};function u(t){var n=tn(q.types,function(n){return n.name===t});if(n)return n;if("any"===t)return r;throw n=tn(q.types,function(n){return n.name.toLowerCase()===t.toLowerCase()}),new TypeError('Unknown type "'+t+'"'+(n?'. Did you mean "'+n.name+'"?':""))}function i(n){return n===r?999:q.types.indexOf(n)}function c(t){var n=tn(q.types,function(n){return n.test(t)});if(n)return n.name;throw new TypeError("Value has unknown type. Value: "+t)}function z(n){return n.map(function(n){var t=n.types.map(o);return(n.restParam?"...":"")+t.join("|")}).join(",")}function B(n,r){var t,e,a=0===n.indexOf("..."),o=(a?3=o+1}}return 0===n.length?function(n){return 0===n.length}:1===n.length?(t=J(n[0]),function(n){return t(n[0])&&1===n.length}):2===n.length?(t=J(n[0]),r=J(n[1]),function(n){return t(n[0])&&r(n[1])&&2===n.length}):(a=n.map(J),function(n){for(var t=0;tt?(s=new TypeError("Too many arguments in function "+a+" (expected: "+t+", actual: "+r.length+")")).data={category:"tooManyArgs",fn:a,index:r.length,expectedLength:t}:(s=new TypeError('Arguments of type "'+r.join(", ")+'" do not match any of the defined signatures of function '+a+".")).data={category:"mismatch",actual:r.map(c)}),s}function h(n){for(var t=999,r=0;r=6.9.0" + } + }, + "node_modules/complex.js": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/complex.js/-/complex.js-2.1.1.tgz", + "integrity": "sha512-8njCHOTtFFLtegk6zQo0kkVX1rngygb/KQI6z1qZxlFI3scluC+LVTCFbrkWjBv4vvLlbQ9t88IPMC6k95VTTg==", + "engines": { + "node": "*" + }, + "funding": { + "type": "patreon", + "url": "https://www.patreon.com/infusion" + } + }, + "node_modules/decimal.js": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.3.1.tgz", + "integrity": "sha512-V0pfhfr8suzyPGOx3nmq4aHqabehUZn6Ch9kyFpV79TGDTWFmHqUqXdabR7QHqxzrYolF4+tVmJhUG4OURg5dQ==" + }, + "node_modules/escape-latex": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/escape-latex/-/escape-latex-1.2.0.tgz", + "integrity": "sha512-nV5aVWW1K0wEiUIEdZ4erkGGH8mDxGyxSeqPzRNtWP7ataw+/olFObw7hujFWlVjNsaDFw5VZ5NzVSIqRgfTiw==" + }, + "node_modules/fraction.js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.2.0.tgz", + "integrity": "sha512-MhLuK+2gUcnZe8ZHlaaINnQLl0xRIGRfcGk2yl8xoQAfHrSsL3rYu6FCmBdkdbhc9EPlwyGHewaRsvwRMJtAlA==", + "engines": { + "node": "*" + }, + "funding": { + "type": "patreon", + "url": "https://www.patreon.com/infusion" + } + }, + "node_modules/javascript-natural-sort": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/javascript-natural-sort/-/javascript-natural-sort-0.7.1.tgz", + "integrity": "sha1-+eIwPUUH9tdDVac2ZNFED7Wg71k=" + }, + "node_modules/mathjs": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/mathjs/-/mathjs-10.4.3.tgz", + "integrity": "sha512-C50lWorCOplBec9Ik5fzhHuOx4G4+mtdz3r1G2I1/r8yj+CpYFXLXNqTdg59oKmIF1tKcIzpxlC4s2dGL7f3pg==", + "dependencies": { + "@babel/runtime": "^7.17.8", + "complex.js": "^2.1.0", + "decimal.js": "^10.3.1", + "escape-latex": "^1.2.0", + "fraction.js": "^4.2.0", + "javascript-natural-sort": "^0.7.1", + "seedrandom": "^3.0.5", + "tiny-emitter": "^2.1.0", + "typed-function": "^2.1.0" + }, + "bin": { + "mathjs": "bin/cli.js" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.13.9", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", + "integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==" + }, + "node_modules/seedrandom": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/seedrandom/-/seedrandom-3.0.5.tgz", + "integrity": "sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==" + }, + "node_modules/tiny-emitter": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tiny-emitter/-/tiny-emitter-2.1.0.tgz", + "integrity": "sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q==" + }, + "node_modules/typed-function": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/typed-function/-/typed-function-2.1.0.tgz", + "integrity": "sha512-bctQIOqx2iVbWGDGPWwIm18QScpu2XRmkC19D8rQGFsjKSgteq/o1hTZvIG/wuDq8fanpBDrLkLq+aEN/6y5XQ==", + "engines": { + "node": ">= 10" + } + } + }, + "dependencies": { + "@babel/runtime": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.17.9.tgz", + "integrity": "sha512-lSiBBvodq29uShpWGNbgFdKYNiFDo5/HIYsaCEY9ff4sb10x9jizo2+pRrSyF4jKZCXqgzuqBOQKbUm90gQwJg==", + "requires": { + "regenerator-runtime": "^0.13.4" + } + }, + "complex.js": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/complex.js/-/complex.js-2.1.1.tgz", + "integrity": "sha512-8njCHOTtFFLtegk6zQo0kkVX1rngygb/KQI6z1qZxlFI3scluC+LVTCFbrkWjBv4vvLlbQ9t88IPMC6k95VTTg==" + }, + "decimal.js": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.3.1.tgz", + "integrity": "sha512-V0pfhfr8suzyPGOx3nmq4aHqabehUZn6Ch9kyFpV79TGDTWFmHqUqXdabR7QHqxzrYolF4+tVmJhUG4OURg5dQ==" + }, + "escape-latex": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/escape-latex/-/escape-latex-1.2.0.tgz", + "integrity": "sha512-nV5aVWW1K0wEiUIEdZ4erkGGH8mDxGyxSeqPzRNtWP7ataw+/olFObw7hujFWlVjNsaDFw5VZ5NzVSIqRgfTiw==" + }, + "fraction.js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.2.0.tgz", + "integrity": "sha512-MhLuK+2gUcnZe8ZHlaaINnQLl0xRIGRfcGk2yl8xoQAfHrSsL3rYu6FCmBdkdbhc9EPlwyGHewaRsvwRMJtAlA==" + }, + "javascript-natural-sort": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/javascript-natural-sort/-/javascript-natural-sort-0.7.1.tgz", + "integrity": "sha1-+eIwPUUH9tdDVac2ZNFED7Wg71k=" + }, + "mathjs": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/mathjs/-/mathjs-10.4.3.tgz", + "integrity": "sha512-C50lWorCOplBec9Ik5fzhHuOx4G4+mtdz3r1G2I1/r8yj+CpYFXLXNqTdg59oKmIF1tKcIzpxlC4s2dGL7f3pg==", + "requires": { + "@babel/runtime": "^7.17.8", + "complex.js": "^2.1.0", + "decimal.js": "^10.3.1", + "escape-latex": "^1.2.0", + "fraction.js": "^4.2.0", + "javascript-natural-sort": "^0.7.1", + "seedrandom": "^3.0.5", + "tiny-emitter": "^2.1.0", + "typed-function": "^2.1.0" + } + }, + "regenerator-runtime": { + "version": "0.13.9", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", + "integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==" + }, + "seedrandom": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/seedrandom/-/seedrandom-3.0.5.tgz", + "integrity": "sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==" + }, + "tiny-emitter": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tiny-emitter/-/tiny-emitter-2.1.0.tgz", + "integrity": "sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q==" + }, + "typed-function": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/typed-function/-/typed-function-2.1.0.tgz", + "integrity": "sha512-bctQIOqx2iVbWGDGPWwIm18QScpu2XRmkC19D8rQGFsjKSgteq/o1hTZvIG/wuDq8fanpBDrLkLq+aEN/6y5XQ==" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..22cc05c --- /dev/null +++ b/package.json @@ -0,0 +1,15 @@ +{ + "name": "squiggle-simplex", + "version": "1.0.0", + "description": "", + "main": "index.js", + "type": "module", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "mathjs": "^10.4.3" + } +}